diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 000000000..7f90959f9 Binary files /dev/null and b/.DS_Store differ diff --git a/.gitignore b/.gitignore index 5f8086b26..9b653b141 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,7 @@ logs results npm-debug.log -#node_modules +# dependency +/node_modules +node_modules +keys.js \ No newline at end of file diff --git a/README.md b/README.md index 994ece49e..744239677 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -repo +Fluffy socks 120 app ==== -Project Description +Team 4: app that reminds breaktime and offers breaktime ideas diff --git a/actLog.json b/actLog.json new file mode 100644 index 000000000..877983f73 --- /dev/null +++ b/actLog.json @@ -0,0 +1,34 @@ +{ + "toLog": [ + { + "ID": "1", + "Category": "exercise", + "Activity": "Yoga", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/dkg-zps94uw/1600x900", + "Link": "https://www.youtube.com/embed/b1H3xO3x_Js", + "Description": "I'm new to yoga, so this was a bit harder than I thought. Still had a great time exercising and being more mindful!" + }, + { + "ID": "2", + "Category": "kitchen fun", + "Activity": "Bake Cookies", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/tDoHiqXl9b8/1600x900", + "Link": "https://www.youtube.com/embed/uJwekkbGPns", + "Description": "Made chocolate chip cookies today! Great recipe, and 10/10 recommend!" + }, + { + "ID": "3", + "Category": "nature", + "Activity": "Plant A Seed", + "minTime": 10, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/4PG6wLlVag4/1600x900", + "Link": "https://www.youtube.com/embed/w77zPAtVTuI", + "Description": "Started growing an apple tree in the backyard! I can't wait to see how much this seed grows." + } + ] +} \ No newline at end of file diff --git a/activites.json b/activites.json new file mode 100644 index 000000000..2f531036b --- /dev/null +++ b/activites.json @@ -0,0 +1,571 @@ +{ + "activites": [ + { + "Category": "exercise", + "Activity": "Yoga", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/dkg-zps94uw/1600x900", + "Link": "https://www.youtube.com/watch?v=FRAEaBtP2r4&feature=emb_title", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "exercise", + "Activity": "Yoga", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/dkg-zps94uw/1600x900", + "Link": "https://www.youtube.com/watch?v=v7AYKMP6rOE&feature=emb_title", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "exercise", + "Activity": "Yoga", + "minTime": 40, + "Tags": "indoor", + "Image": "https://source.unsplash.com/dkg-zps94uw/1600x900", + "Link": "https://www.youtube.com/watch?v=oBu-pQG6sTY&feature=emb_title", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "exercise", + "Activity": "Yoga", + "minTime": 60, + "Tags": "indoor", + "Image": "https://source.unsplash.com/dkg-zps94uw/1600x900", + "Link": "https://www.youtube.com/watch?v=w0cLgFg4Zsw&feature=emb_title", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "exercise", + "Activity": "Yoga", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/dkg-zps94uw/1600x900", + "Link": "https://www.youtube.com/watch?v=4pKly2JojMw&feature=emb_title", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "exercise", + "Activity": "Yoga", + "minTime": 15, + "Tags": "indoor", + "Image": "https://source.unsplash.com/dkg-zps94uw/1600x900", + "Link": "https://www.youtube.com/watch?v=4vTJHUDB5ak&feature=emb_title", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "exercise", + "Activity": "Biking", + "minTime": 20, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/IE9PKXWpRGU/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "exercise", + "Activity": "Jump rope", + "minTime": 5, + "Tags": "both", + "Image": "https://source.unsplash.com/7QYd1VxLRbM/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "exercise", + "Activity": "hula hoop", + "minTime": 5, + "Tags": "both", + "Image": "https://source.unsplash.com/HC1I-tgIDq0/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "exercise", + "Activity": "going for a walk", + "minTime": 10, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/nVDB1IGq64s/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "exercise", + "Activity": "going for a run", + "minTime": 10, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/7DCZgKyp8vw/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "music", + "Activity": "make a spotify playlist", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/3NgcTH0CFJg/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "music", + "Activity": "learn a new piece of music with the intrument you play", + "minTime": 20, + "Tags": "indoor", + "Image": "https://source.unsplash.com/bu-6kNWQj6U/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "music", + "Activity": "listen to an album from an artist you've never heard of", + "minTime": 20, + "Tags": "indoor", + "Image": "https://source.unsplash.com/tgmyo9lWll4/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "music", + "Activity": "write a song", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/ddwbTn5HDdQ/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "music", + "Activity": "look up your current mood on spotify and listen to that playlist", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/RNYB6v3XoE8/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "creative", + "Activity": "paint", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/QrYt4_K5TIc/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "creative", + "Activity": "draw", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/eKkeKfDt1Vk/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "creative", + "Activity": "color", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/ZsvuETrThX8/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "creative", + "Activity": "craft something for a friend", + "minTime": 15, + "Tags": "indoor", + "Image": "https://source.unsplash.com/lJU5KvoHQHk/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "creative", + "Activity": "decorate something for your room", + "minTime": 15, + "Tags": "indoor", + "Image": "https://source.unsplash.com/4W5WWKaxsKs/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "creative", + "Activity": "sidewalk chalk in your neighborhood or nearby park", + "minTime": 10, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/StgZKNLVeJg/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "creative", + "Activity": "take a photograph of yourself and edit it", + "minTime": 10, + "Tags": "both", + "Image": "https://source.unsplash.com/ZcOaFnQ8ACk/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "creative", + "Activity": "make a graphic", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/ubIWo074QlU/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "creative", + "Activity": "take a photograph of something in your house from a different point of view", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/9ryNj0e_XNY/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "creative", + "Activity": "do a puzzle", + "minTime": 20, + "Tags": "indoor", + "Image": "https://source.unsplash.com/LuaT29bdjMA/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "creative", + "Activity": "start a journal, or continue journalling", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/CKlHKtCJZKk/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "creative", + "Activity": "write a poem", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/NUQtVifTqs4/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "creative", + "Activity": "write a song", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/ddwbTn5HDdQ/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "creative", + "Activity": "write a letter to a penpal", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/U_DJOoSDhNo/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "creative", + "Activity": "upcycle a piece of clothing", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/WgRj6Hc7yZw/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "creative", + "Activity": "design a tattoo", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/77yU7LB7gBk/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "nature", + "Activity": "Plant A Seed", + "minTime": 10, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/4PG6wLlVag4/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "nature", + "Activity": "go on a walk", + "minTime": 10, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/nVDB1IGq64s/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "nature", + "Activity": "go on a hike", + "minTime": 10, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/Yizrl9N_eDA/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "nature", + "Activity": "tend to your garden", + "minTime": 20, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/sFydXGrt5OA/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "nature", + "Activity": "read about a plant in your garden", + "minTime": 10, + "Tags": "outdoor", + "Image": "https://source.unsplash.com/D9hyvnamCn0/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "learning", + "Activity": "read a book that you've been meaning to read", + "minTime": 40, + "Tags": "indoor", + "Image": "https://source.unsplash.com/4RNLzJzEMMs/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "learning", + "Activity": "read an article about ____", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/dwbzzB03gUE/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "learning", + "Activity": "listen to an audiobook", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/v0HbU2CNJFs/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "learning", + "Activity": "listen to a podcast", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/UUPpu2sYV6E/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "learning", + "Activity": "whats your favorite animal? read an article about them.", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/BuQ1RZckYW4/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "learning", + "Activity": "read the first news article that pops up when you click the \"News\" tab on Google", + "minTime": 15, + "Tags": "indoor", + "Image": "https://source.unsplash.com/aId-xYRTlEc/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "relaxation", + "Activity": "yoga", + "minTime": 30, + "Tags": "both", + "Image": "https://source.unsplash.com/dkg-zps94uw/1600x900", + "Link": "https://www.youtube.com/watch?v=hJbRpHZr_d0&feature=emb_title", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "relaxation", + "Activity": "meditate", + "minTime": 20, + "Tags": "both", + "Image": "https://source.unsplash.com/NTyBbu66_SI/1600x900", + "Link": "https://www.youtube.com/watch?v=rM_km4E3NYs", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "relaxation", + "Activity": "meditate", + "minTime": 10, + "Tags": "both", + "Image": "https://source.unsplash.com/NTyBbu66_SI/1600x900", + "Link": "https://www.youtube.com/watch?v=6p_yaNFSYao", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "relaxation", + "Activity": "meditate", + "minTime": 5, + "Tags": "both", + "Image": "https://source.unsplash.com/NTyBbu66_SI/1600x900", + "Link": "https://www.youtube.com/watch?v=i50ZAs7v9es", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "relaxation", + "Activity": "meditate", + "minTime": 15, + "Tags": "both", + "Image": "https://source.unsplash.com/NTyBbu66_SI/1600x900", + "Link": "https://www.youtube.com/watch?v=p29mwfzpNc4", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "relaxation", + "Activity": "do a face mask", + "minTime": 10, + "Tags": "indoor", + "Image": "https://source.unsplash.com/AyqNM8D2aEI/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "relaxation", + "Activity": "stretch", + "minTime": 30, + "Tags": "both", + "Image": "https://source.unsplash.com/We6cFKHo8sQ/1600x900", + "Link": "https://www.youtube.com/watch?v=qULTwquOuT4", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "relaxation", + "Activity": "stretch", + "minTime": 5, + "Tags": "both", + "Image": "https://source.unsplash.com/We6cFKHo8sQ/1600x900", + "Link": "https://www.youtube.com/watch?v=pH6KMX0V7d0", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "kitchen fun", + "Activity": "bake bread", + "minTime": 60, + "Tags": "indoor", + "Image": "https://source.unsplash.com/ir3VHDcw-fY/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "kitchen fun", + "Activity": "bake a cake", + "minTime": 60, + "Tags": "indoor", + "Image": "https://source.unsplash.com/3K6qK5ZA_7w/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "kitchen fun", + "Activity": "bake cupcakes", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/IVcI_J7ETLg/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "kitchen fun", + "Activity": "make pasta from scratch", + "minTime": 60, + "Tags": "indoor", + "Image": "https://source.unsplash.com/JG5tkvNqbZk/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "kitchen fun", + "Activity": "make your favorite dish from your childhood", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/geG4C3qyiG0/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "kitchen fun", + "Activity": "Bake Cookies", + "minTime": 30, + "Tags": "indoor", + "Image": "https://source.unsplash.com/tDoHiqXl9b8/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "kitchen fun", + "Activity": "recreate your favorite resturaunt meal", + "minTime": 60, + "Tags": "indoor", + "Image": "https://source.unsplash.com/nj22gb3XKCM/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "productivity", + "Activity": "clean/organize your bathroom", + "minTime": 15, + "Tags": "indoor", + "Image": "https://source.unsplash.com/d0WU6KSp918/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "productivity", + "Activity": "organize your closet", + "minTime": 20, + "Tags": "indoor", + "Image": "https://source.unsplash.com/XjR-Y8PKeww/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + }, + { + "Category": "productivity", + "Activity": "rotate your mattress", + "minTime": 5, + "Tags": "indoor", + "Image": "https://source.unsplash.com/h_xf5vHZmRM/1600x900", + "Link": "", + "Description": "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." + }, + { + "Category": "productivity", + "Activity": "update your resume", + "minTime": 15, + "Tags": "indoor", + "Image": "https://source.unsplash.com/7iSEHWsxPLw/1600x900", + "Link": "", + "Description": "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur." + }, + { + "Category": "productivity", + "Activity": "make some personal finance goals, or check in with your past financial goals", + "minTime": 20, + "Tags": "indoor", + "Image": "https://source.unsplash.com/IrRbSND5EUc/1600x900", + "Link": "", + "Description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." + } + ] +} \ No newline at end of file diff --git a/app.js b/app.js index edb9f73ea..637b8e82a 100644 --- a/app.js +++ b/app.js @@ -1,4 +1,3 @@ - /** * Module dependencies. */ @@ -6,9 +5,20 @@ var express = require('express'); var http = require('http'); var path = require('path'); -var handlebars = require('express3-handlebars') +var handlebars = require('express3-handlebars'); var index = require('./routes/index'); +var project = require('./routes/project'); +var filter = require('./routes/filter'); +var filter2 = require('./routes/filter2'); +var filter3 = require('./routes/filter3'); +var activity = require('./routes/activity'); +var setting = require('./routes/setting'); +var about = require('./routes/about'); +var complete = require('./routes/complete'); +var logIn = require('./routes/logIn'); +var logIn = require('./routes/logIn'); +var filtered = require('./routes/filtered'); // Example route // var user = require('./routes/user'); @@ -24,20 +34,31 @@ app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); -app.use(express.cookieParser('IxD secret key')); +app.use(express.cookieParser('Intro HCI secret key')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { - app.use(express.errorHandler()); + app.use(express.errorHandler()); } -app.get('/', index.view); -// Example route -// app.get('/users', user.list); +// Add routes here +app.get('/', logIn.view); +app.get('/filter', filter.view); +app.get('/filter2', filter2.view); +app.get('/filter3', filter3.view); +//app.get('/activity', activity.view); +app.get('/setting', setting.view); +app.get('/about', about.view); +app.get('/filtered', filtered.view); +app.get('/project/:id', project.projectInfo); +app.get('/logIn', logIn.view); +app.get('/complete', complete.view); +app.get('/index', index.view); +app.get('/activity/:id', activity.activityInfo); -http.createServer(app).listen(app.get('port'), function(){ - console.log('Express server listening on port ' + app.get('port')); +http.createServer(app).listen(app.get('port'), function() { + console.log('Express server listening on port ' + app.get('port')); }); diff --git a/node_modules/.bin/express b/node_modules/.bin/express deleted file mode 120000 index b741d99c6..000000000 --- a/node_modules/.bin/express +++ /dev/null @@ -1 +0,0 @@ -../express/bin/express \ No newline at end of file diff --git a/node_modules/express/.npmignore b/node_modules/express/.npmignore deleted file mode 100644 index caf574de4..000000000 --- a/node_modules/express/.npmignore +++ /dev/null @@ -1,9 +0,0 @@ -.git* -docs/ -examples/ -support/ -test/ -testing.js -.DS_Store -coverage.html -lib-cov diff --git a/node_modules/express/.travis.yml b/node_modules/express/.travis.yml deleted file mode 100644 index a12e3f0fd..000000000 --- a/node_modules/express/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" \ No newline at end of file diff --git a/node_modules/express/History.md b/node_modules/express/History.md deleted file mode 100644 index 9d53bef43..000000000 --- a/node_modules/express/History.md +++ /dev/null @@ -1,1274 +0,0 @@ -4.0.0 / -================== - - * remove: - - express(1) - moved to [express-generator](https://github.com/expressjs/generator) - - `req.accepted*` - use `req.accepts*()` instead - - `app.configure` - use logic in your own app code - * change: - - `req.accepts*` -> `req.accepts*s` - i.e. `req.acceptsEncoding` -> `req.acceptsEncodings` - - `req.params` is now an object instead of an array - - `json spaces` no longer enabled by default in development - * refactor: - - `req.accepts*` with [accepts](https://github.com/expressjs/accepts) - - `req.is` with [type-is](https://github.com/expressjs/type-is) - -3.4.8 / 2014-01-13 -================== - - * prevent incorrect automatic OPTIONS responses #1868 @dpatti - * update binary and examples for jade 1.0 #1876 @yossi, #1877 @reqshark, #1892 @matheusazzi - * throw 400 in case of malformed paths @rlidwka - -3.4.7 / 2013-12-10 -================== - - * update connect - -3.4.6 / 2013-12-01 -================== - - * update connect (raw-body) - -3.4.5 / 2013-11-27 -================== - - * update connect - * res.location: remove leading ./ #1802 @kapouer - * res.redirect: fix `res.redirect('toString') #1829 @michaelficarra - * res.send: always send ETag when content-length > 0 - * router: add Router.all() method - -3.4.4 / 2013-10-29 -================== - - * update connect - * update supertest - * update methods - * express(1): replace bodyParser() with urlencoded() and json() #1795 @chirag04 - -3.4.3 / 2013-10-23 -================== - - * update connect - -3.4.2 / 2013-10-18 -================== - - * update connect - * downgrade commander - -3.4.1 / 2013-10-15 -================== - - * update connect - * update commander - * jsonp: check if callback is a function - * router: wrap encodeURIComponent in a try/catch #1735 (@lxe) - * res.format: now includes chraset @1747 (@sorribas) - * res.links: allow multiple calls @1746 (@sorribas) - -3.4.0 / 2013-09-07 -================== - - * add res.vary(). Closes #1682 - * update connect - -3.3.8 / 2013-09-02 -================== - - * update connect - -3.3.7 / 2013-08-28 -================== - - * update connect - -3.3.6 / 2013-08-27 -================== - - * Revert "remove charset from json responses. Closes #1631" (causes issues in some clients) - * add: req.accepts take an argument list - -3.3.4 / 2013-07-08 -================== - - * update send and connect - -3.3.3 / 2013-07-04 -================== - - * update connect - -3.3.2 / 2013-07-03 -================== - - * update connect - * update send - * remove .version export - -3.3.1 / 2013-06-27 -================== - - * update connect - -3.3.0 / 2013-06-26 -================== - - * update connect - * add support for multiple X-Forwarded-Proto values. Closes #1646 - * change: remove charset from json responses. Closes #1631 - * change: return actual booleans from req.accept* functions - * fix jsonp callback array throw - -3.2.6 / 2013-06-02 -================== - - * update connect - -3.2.5 / 2013-05-21 -================== - - * update connect - * update node-cookie - * add: throw a meaningful error when there is no default engine - * change generation of ETags with res.send() to GET requests only. Closes #1619 - -3.2.4 / 2013-05-09 -================== - - * fix `req.subdomains` when no Host is present - * fix `req.host` when no Host is present, return undefined - -3.2.3 / 2013-05-07 -================== - - * update connect / qs - -3.2.2 / 2013-05-03 -================== - - * update qs - -3.2.1 / 2013-04-29 -================== - - * add app.VERB() paths array deprecation warning - * update connect - * update qs and remove all ~ semver crap - * fix: accept number as value of Signed Cookie - -3.2.0 / 2013-04-15 -================== - - * add "view" constructor setting to override view behaviour - * add req.acceptsEncoding(name) - * add req.acceptedEncodings - * revert cookie signature change causing session race conditions - * fix sorting of Accept values of the same quality - -3.1.2 / 2013-04-12 -================== - - * add support for custom Accept parameters - * update cookie-signature - -3.1.1 / 2013-04-01 -================== - - * add X-Forwarded-Host support to `req.host` - * fix relative redirects - * update mkdirp - * update buffer-crc32 - * remove legacy app.configure() method from app template. - -3.1.0 / 2013-01-25 -================== - - * add support for leading "." in "view engine" setting - * add array support to `res.set()` - * add node 0.8.x to travis.yml - * add "subdomain offset" setting for tweaking `req.subdomains` - * add `res.location(url)` implementing `res.redirect()`-like setting of Location - * use app.get() for x-powered-by setting for inheritance - * fix colons in passwords for `req.auth` - -3.0.6 / 2013-01-04 -================== - - * add http verb methods to Router - * update connect - * fix mangling of the `res.cookie()` options object - * fix jsonp whitespace escape. Closes #1132 - -3.0.5 / 2012-12-19 -================== - - * add throwing when a non-function is passed to a route - * fix: explicitly remove Transfer-Encoding header from 204 and 304 responses - * revert "add 'etag' option" - -3.0.4 / 2012-12-05 -================== - - * add 'etag' option to disable `res.send()` Etags - * add escaping of urls in text/plain in `res.redirect()` - for old browsers interpreting as html - * change crc32 module for a more liberal license - * update connect - -3.0.3 / 2012-11-13 -================== - - * update connect - * update cookie module - * fix cookie max-age - -3.0.2 / 2012-11-08 -================== - - * add OPTIONS to cors example. Closes #1398 - * fix route chaining regression. Closes #1397 - -3.0.1 / 2012-11-01 -================== - - * update connect - -3.0.0 / 2012-10-23 -================== - - * add `make clean` - * add "Basic" check to req.auth - * add `req.auth` test coverage - * add cb && cb(payload) to `res.jsonp()`. Closes #1374 - * add backwards compat for `res.redirect()` status. Closes #1336 - * add support for `res.json()` to retain previously defined Content-Types. Closes #1349 - * update connect - * change `res.redirect()` to utilize a pathname-relative Location again. Closes #1382 - * remove non-primitive string support for `res.send()` - * fix view-locals example. Closes #1370 - * fix route-separation example - -3.0.0rc5 / 2012-09-18 -================== - - * update connect - * add redis search example - * add static-files example - * add "x-powered-by" setting (`app.disable('x-powered-by')`) - * add "application/octet-stream" redirect Accept test case. Closes #1317 - -3.0.0rc4 / 2012-08-30 -================== - - * add `res.jsonp()`. Closes #1307 - * add "verbose errors" option to error-pages example - * add another route example to express(1) so people are not so confused - * add redis online user activity tracking example - * update connect dep - * fix etag quoting. Closes #1310 - * fix error-pages 404 status - * fix jsonp callback char restrictions - * remove old OPTIONS default response - -3.0.0rc3 / 2012-08-13 -================== - - * update connect dep - * fix signed cookies to work with `connect.cookieParser()` ("s:" prefix was missing) [tnydwrds] - * fix `res.render()` clobbering of "locals" - -3.0.0rc2 / 2012-08-03 -================== - - * add CORS example - * update connect dep - * deprecate `.createServer()` & remove old stale examples - * fix: escape `res.redirect()` link - * fix vhost example - -3.0.0rc1 / 2012-07-24 -================== - - * add more examples to view-locals - * add scheme-relative redirects (`res.redirect("//foo.com")`) support - * update cookie dep - * update connect dep - * update send dep - * fix `express(1)` -h flag, use -H for hogan. Closes #1245 - * fix `res.sendfile()` socket error handling regression - -3.0.0beta7 / 2012-07-16 -================== - - * update connect dep for `send()` root normalization regression - -3.0.0beta6 / 2012-07-13 -================== - - * add `err.view` property for view errors. Closes #1226 - * add "jsonp callback name" setting - * add support for "/foo/:bar*" non-greedy matches - * change `res.sendfile()` to use `send()` module - * change `res.send` to use "response-send" module - * remove `app.locals.use` and `res.locals.use`, use regular middleware - -3.0.0beta5 / 2012-07-03 -================== - - * add "make check" support - * add route-map example - * add `res.json(obj, status)` support back for BC - * add "methods" dep, remove internal methods module - * update connect dep - * update auth example to utilize cores pbkdf2 - * updated tests to use "supertest" - -3.0.0beta4 / 2012-06-25 -================== - - * Added `req.auth` - * Added `req.range(size)` - * Added `res.links(obj)` - * Added `res.send(body, status)` support back for backwards compat - * Added `.default()` support to `res.format()` - * Added 2xx / 304 check to `req.fresh` - * Revert "Added + support to the router" - * Fixed `res.send()` freshness check, respect res.statusCode - -3.0.0beta3 / 2012-06-15 -================== - - * Added hogan `--hjs` to express(1) [nullfirm] - * Added another example to content-negotiation - * Added `fresh` dep - * Changed: `res.send()` always checks freshness - * Fixed: expose connects mime module. Cloases #1165 - -3.0.0beta2 / 2012-06-06 -================== - - * Added `+` support to the router - * Added `req.host` - * Changed `req.param()` to check route first - * Update connect dep - -3.0.0beta1 / 2012-06-01 -================== - - * Added `res.format()` callback to override default 406 behaviour - * Fixed `res.redirect()` 406. Closes #1154 - -3.0.0alpha5 / 2012-05-30 -================== - - * Added `req.ip` - * Added `{ signed: true }` option to `res.cookie()` - * Removed `res.signedCookie()` - * Changed: dont reverse `req.ips` - * Fixed "trust proxy" setting check for `req.ips` - -3.0.0alpha4 / 2012-05-09 -================== - - * Added: allow `[]` in jsonp callback. Closes #1128 - * Added `PORT` env var support in generated template. Closes #1118 [benatkin] - * Updated: connect 2.2.2 - -3.0.0alpha3 / 2012-05-04 -================== - - * Added public `app.routes`. Closes #887 - * Added _view-locals_ example - * Added _mvc_ example - * Added `res.locals.use()`. Closes #1120 - * Added conditional-GET support to `res.send()` - * Added: coerce `res.set()` values to strings - * Changed: moved `static()` in generated apps below router - * Changed: `res.send()` only set ETag when not previously set - * Changed connect 2.2.1 dep - * Changed: `make test` now runs unit / acceptance tests - * Fixed req/res proto inheritance - -3.0.0alpha2 / 2012-04-26 -================== - - * Added `make benchmark` back - * Added `res.send()` support for `String` objects - * Added client-side data exposing example - * Added `res.header()` and `req.header()` aliases for BC - * Added `express.createServer()` for BC - * Perf: memoize parsed urls - * Perf: connect 2.2.0 dep - * Changed: make `expressInit()` middleware self-aware - * Fixed: use app.get() for all core settings - * Fixed redis session example - * Fixed session example. Closes #1105 - * Fixed generated express dep. Closes #1078 - -3.0.0alpha1 / 2012-04-15 -================== - - * Added `app.locals.use(callback)` - * Added `app.locals` object - * Added `app.locals(obj)` - * Added `res.locals` object - * Added `res.locals(obj)` - * Added `res.format()` for content-negotiation - * Added `app.engine()` - * Added `res.cookie()` JSON cookie support - * Added "trust proxy" setting - * Added `req.subdomains` - * Added `req.protocol` - * Added `req.secure` - * Added `req.path` - * Added `req.ips` - * Added `req.fresh` - * Added `req.stale` - * Added comma-delmited / array support for `req.accepts()` - * Added debug instrumentation - * Added `res.set(obj)` - * Added `res.set(field, value)` - * Added `res.get(field)` - * Added `app.get(setting)`. Closes #842 - * Added `req.acceptsLanguage()` - * Added `req.acceptsCharset()` - * Added `req.accepted` - * Added `req.acceptedLanguages` - * Added `req.acceptedCharsets` - * Added "json replacer" setting - * Added "json spaces" setting - * Added X-Forwarded-Proto support to `res.redirect()`. Closes #92 - * Added `--less` support to express(1) - * Added `express.response` prototype - * Added `express.request` prototype - * Added `express.application` prototype - * Added `app.path()` - * Added `app.render()` - * Added `res.type()` to replace `res.contentType()` - * Changed: `res.redirect()` to add relative support - * Changed: enable "jsonp callback" by default - * Changed: renamed "case sensitive routes" to "case sensitive routing" - * Rewrite of all tests with mocha - * Removed "root" setting - * Removed `res.redirect('home')` support - * Removed `req.notify()` - * Removed `app.register()` - * Removed `app.redirect()` - * Removed `app.is()` - * Removed `app.helpers()` - * Removed `app.dynamicHelpers()` - * Fixed `res.sendfile()` with non-GET. Closes #723 - * Fixed express(1) public dir for windows. Closes #866 - -2.5.9/ 2012-04-02 -================== - - * Added support for PURGE request method [pbuyle] - * Fixed `express(1)` generated app `app.address()` before `listening` [mmalecki] - -2.5.8 / 2012-02-08 -================== - - * Update mkdirp dep. Closes #991 - -2.5.7 / 2012-02-06 -================== - - * Fixed `app.all` duplicate DELETE requests [mscdex] - -2.5.6 / 2012-01-13 -================== - - * Updated hamljs dev dep. Closes #953 - -2.5.5 / 2012-01-08 -================== - - * Fixed: set `filename` on cached templates [matthewleon] - -2.5.4 / 2012-01-02 -================== - - * Fixed `express(1)` eol on 0.4.x. Closes #947 - -2.5.3 / 2011-12-30 -================== - - * Fixed `req.is()` when a charset is present - -2.5.2 / 2011-12-10 -================== - - * Fixed: express(1) LF -> CRLF for windows - -2.5.1 / 2011-11-17 -================== - - * Changed: updated connect to 1.8.x - * Removed sass.js support from express(1) - -2.5.0 / 2011-10-24 -================== - - * Added ./routes dir for generated app by default - * Added npm install reminder to express(1) app gen - * Added 0.5.x support - * Removed `make test-cov` since it wont work with node 0.5.x - * Fixed express(1) public dir for windows. Closes #866 - -2.4.7 / 2011-10-05 -================== - - * Added mkdirp to express(1). Closes #795 - * Added simple _json-config_ example - * Added shorthand for the parsed request's pathname via `req.path` - * Changed connect dep to 1.7.x to fix npm issue... - * Fixed `res.redirect()` __HEAD__ support. [reported by xerox] - * Fixed `req.flash()`, only escape args - * Fixed absolute path checking on windows. Closes #829 [reported by andrewpmckenzie] - -2.4.6 / 2011-08-22 -================== - - * Fixed multiple param callback regression. Closes #824 [reported by TroyGoode] - -2.4.5 / 2011-08-19 -================== - - * Added support for routes to handle errors. Closes #809 - * Added `app.routes.all()`. Closes #803 - * Added "basepath" setting to work in conjunction with reverse proxies etc. - * Refactored `Route` to use a single array of callbacks - * Added support for multiple callbacks for `app.param()`. Closes #801 -Closes #805 - * Changed: removed .call(self) for route callbacks - * Dependency: `qs >= 0.3.1` - * Fixed `res.redirect()` on windows due to `join()` usage. Closes #808 - -2.4.4 / 2011-08-05 -================== - - * Fixed `res.header()` intention of a set, even when `undefined` - * Fixed `*`, value no longer required - * Fixed `res.send(204)` support. Closes #771 - -2.4.3 / 2011-07-14 -================== - - * Added docs for `status` option special-case. Closes #739 - * Fixed `options.filename`, exposing the view path to template engines - -2.4.2. / 2011-07-06 -================== - - * Revert "removed jsonp stripping" for XSS - -2.4.1 / 2011-07-06 -================== - - * Added `res.json()` JSONP support. Closes #737 - * Added _extending-templates_ example. Closes #730 - * Added "strict routing" setting for trailing slashes - * Added support for multiple envs in `app.configure()` calls. Closes #735 - * Changed: `res.send()` using `res.json()` - * Changed: when cookie `path === null` don't default it - * Changed; default cookie path to "home" setting. Closes #731 - * Removed _pids/logs_ creation from express(1) - -2.4.0 / 2011-06-28 -================== - - * Added chainable `res.status(code)` - * Added `res.json()`, an explicit version of `res.send(obj)` - * Added simple web-service example - -2.3.12 / 2011-06-22 -================== - - * \#express is now on freenode! come join! - * Added `req.get(field, param)` - * Added links to Japanese documentation, thanks @hideyukisaito! - * Added; the `express(1)` generated app outputs the env - * Added `content-negotiation` example - * Dependency: connect >= 1.5.1 < 2.0.0 - * Fixed view layout bug. Closes #720 - * Fixed; ignore body on 304. Closes #701 - -2.3.11 / 2011-06-04 -================== - - * Added `npm test` - * Removed generation of dummy test file from `express(1)` - * Fixed; `express(1)` adds express as a dep - * Fixed; prune on `prepublish` - -2.3.10 / 2011-05-27 -================== - - * Added `req.route`, exposing the current route - * Added _package.json_ generation support to `express(1)` - * Fixed call to `app.param()` function for optional params. Closes #682 - -2.3.9 / 2011-05-25 -================== - - * Fixed bug-ish with `../' in `res.partial()` calls - -2.3.8 / 2011-05-24 -================== - - * Fixed `app.options()` - -2.3.7 / 2011-05-23 -================== - - * Added route `Collection`, ex: `app.get('/user/:id').remove();` - * Added support for `app.param(fn)` to define param logic - * Removed `app.param()` support for callback with return value - * Removed module.parent check from express(1) generated app. Closes #670 - * Refactored router. Closes #639 - -2.3.6 / 2011-05-20 -================== - - * Changed; using devDependencies instead of git submodules - * Fixed redis session example - * Fixed markdown example - * Fixed view caching, should not be enabled in development - -2.3.5 / 2011-05-20 -================== - - * Added export `.view` as alias for `.View` - -2.3.4 / 2011-05-08 -================== - - * Added `./examples/say` - * Fixed `res.sendfile()` bug preventing the transfer of files with spaces - -2.3.3 / 2011-05-03 -================== - - * Added "case sensitive routes" option. - * Changed; split methods supported per rfc [slaskis] - * Fixed route-specific middleware when using the same callback function several times - -2.3.2 / 2011-04-27 -================== - - * Fixed view hints - -2.3.1 / 2011-04-26 -================== - - * Added `app.match()` as `app.match.all()` - * Added `app.lookup()` as `app.lookup.all()` - * Added `app.remove()` for `app.remove.all()` - * Added `app.remove.VERB()` - * Fixed template caching collision issue. Closes #644 - * Moved router over from connect and started refactor - -2.3.0 / 2011-04-25 -================== - - * Added options support to `res.clearCookie()` - * Added `res.helpers()` as alias of `res.locals()` - * Added; json defaults to UTF-8 with `res.send()`. Closes #632. [Daniel * Dependency `connect >= 1.4.0` - * Changed; auto set Content-Type in res.attachement [Aaron Heckmann] - * Renamed "cache views" to "view cache". Closes #628 - * Fixed caching of views when using several apps. Closes #637 - * Fixed gotcha invoking `app.param()` callbacks once per route middleware. -Closes #638 - * Fixed partial lookup precedence. Closes #631 -Shaw] - -2.2.2 / 2011-04-12 -================== - - * Added second callback support for `res.download()` connection errors - * Fixed `filename` option passing to template engine - -2.2.1 / 2011-04-04 -================== - - * Added `layout(path)` helper to change the layout within a view. Closes #610 - * Fixed `partial()` collection object support. - Previously only anything with `.length` would work. - When `.length` is present one must still be aware of holes, - however now `{ collection: {foo: 'bar'}}` is valid, exposes - `keyInCollection` and `keysInCollection`. - - * Performance improved with better view caching - * Removed `request` and `response` locals - * Changed; errorHandler page title is now `Express` instead of `Connect` - -2.2.0 / 2011-03-30 -================== - - * Added `app.lookup.VERB()`, ex `app.lookup.put('/user/:id')`. Closes #606 - * Added `app.match.VERB()`, ex `app.match.put('/user/12')`. Closes #606 - * Added `app.VERB(path)` as alias of `app.lookup.VERB()`. - * Dependency `connect >= 1.2.0` - -2.1.1 / 2011-03-29 -================== - - * Added; expose `err.view` object when failing to locate a view - * Fixed `res.partial()` call `next(err)` when no callback is given [reported by aheckmann] - * Fixed; `res.send(undefined)` responds with 204 [aheckmann] - -2.1.0 / 2011-03-24 -================== - - * Added `/_?` partial lookup support. Closes #447 - * Added `request`, `response`, and `app` local variables - * Added `settings` local variable, containing the app's settings - * Added `req.flash()` exception if `req.session` is not available - * Added `res.send(bool)` support (json response) - * Fixed stylus example for latest version - * Fixed; wrap try/catch around `res.render()` - -2.0.0 / 2011-03-17 -================== - - * Fixed up index view path alternative. - * Changed; `res.locals()` without object returns the locals - -2.0.0rc3 / 2011-03-17 -================== - - * Added `res.locals(obj)` to compliment `res.local(key, val)` - * Added `res.partial()` callback support - * Fixed recursive error reporting issue in `res.render()` - -2.0.0rc2 / 2011-03-17 -================== - - * Changed; `partial()` "locals" are now optional - * Fixed `SlowBuffer` support. Closes #584 [reported by tyrda01] - * Fixed .filename view engine option [reported by drudge] - * Fixed blog example - * Fixed `{req,res}.app` reference when mounting [Ben Weaver] - -2.0.0rc / 2011-03-14 -================== - - * Fixed; expose `HTTPSServer` constructor - * Fixed express(1) default test charset. Closes #579 [reported by secoif] - * Fixed; default charset to utf-8 instead of utf8 for lame IE [reported by NickP] - -2.0.0beta3 / 2011-03-09 -================== - - * Added support for `res.contentType()` literal - The original `res.contentType('.json')`, - `res.contentType('application/json')`, and `res.contentType('json')` - will work now. - * Added `res.render()` status option support back - * Added charset option for `res.render()` - * Added `.charset` support (via connect 1.0.4) - * Added view resolution hints when in development and a lookup fails - * Added layout lookup support relative to the page view. - For example while rendering `./views/user/index.jade` if you create - `./views/user/layout.jade` it will be used in favour of the root layout. - * Fixed `res.redirect()`. RFC states absolute url [reported by unlink] - * Fixed; default `res.send()` string charset to utf8 - * Removed `Partial` constructor (not currently used) - -2.0.0beta2 / 2011-03-07 -================== - - * Added res.render() `.locals` support back to aid in migration process - * Fixed flash example - -2.0.0beta / 2011-03-03 -================== - - * Added HTTPS support - * Added `res.cookie()` maxAge support - * Added `req.header()` _Referrer_ / _Referer_ special-case, either works - * Added mount support for `res.redirect()`, now respects the mount-point - * Added `union()` util, taking place of `merge(clone())` combo - * Added stylus support to express(1) generated app - * Added secret to session middleware used in examples and generated app - * Added `res.local(name, val)` for progressive view locals - * Added default param support to `req.param(name, default)` - * Added `app.disabled()` and `app.enabled()` - * Added `app.register()` support for omitting leading ".", either works - * Added `res.partial()`, using the same interface as `partial()` within a view. Closes #539 - * Added `app.param()` to map route params to async/sync logic - * Added; aliased `app.helpers()` as `app.locals()`. Closes #481 - * Added extname with no leading "." support to `res.contentType()` - * Added `cache views` setting, defaulting to enabled in "production" env - * Added index file partial resolution, eg: partial('user') may try _views/user/index.jade_. - * Added `req.accepts()` support for extensions - * Changed; `res.download()` and `res.sendfile()` now utilize Connect's - static file server `connect.static.send()`. - * Changed; replaced `connect.utils.mime()` with npm _mime_ module - * Changed; allow `req.query` to be pre-defined (via middleware or other parent - * Changed view partial resolution, now relative to parent view - * Changed view engine signature. no longer `engine.render(str, options, callback)`, now `engine.compile(str, options) -> Function`, the returned function accepts `fn(locals)`. - * Fixed `req.param()` bug returning Array.prototype methods. Closes #552 - * Fixed; using `Stream#pipe()` instead of `sys.pump()` in `res.sendfile()` - * Fixed; using _qs_ module instead of _querystring_ - * Fixed; strip unsafe chars from jsonp callbacks - * Removed "stream threshold" setting - -1.0.8 / 2011-03-01 -================== - - * Allow `req.query` to be pre-defined (via middleware or other parent app) - * "connect": ">= 0.5.0 < 1.0.0". Closes #547 - * Removed the long deprecated __EXPRESS_ENV__ support - -1.0.7 / 2011-02-07 -================== - - * Fixed `render()` setting inheritance. - Mounted apps would not inherit "view engine" - -1.0.6 / 2011-02-07 -================== - - * Fixed `view engine` setting bug when period is in dirname - -1.0.5 / 2011-02-05 -================== - - * Added secret to generated app `session()` call - -1.0.4 / 2011-02-05 -================== - - * Added `qs` dependency to _package.json_ - * Fixed namespaced `require()`s for latest connect support - -1.0.3 / 2011-01-13 -================== - - * Remove unsafe characters from JSONP callback names [Ryan Grove] - -1.0.2 / 2011-01-10 -================== - - * Removed nested require, using `connect.router` - -1.0.1 / 2010-12-29 -================== - - * Fixed for middleware stacked via `createServer()` - previously the `foo` middleware passed to `createServer(foo)` - would not have access to Express methods such as `res.send()` - or props like `req.query` etc. - -1.0.0 / 2010-11-16 -================== - - * Added; deduce partial object names from the last segment. - For example by default `partial('forum/post', postObject)` will - give you the _post_ object, providing a meaningful default. - * Added http status code string representation to `res.redirect()` body - * Added; `res.redirect()` supporting _text/plain_ and _text/html_ via __Accept__. - * Added `req.is()` to aid in content negotiation - * Added partial local inheritance [suggested by masylum]. Closes #102 - providing access to parent template locals. - * Added _-s, --session[s]_ flag to express(1) to add session related middleware - * Added _--template_ flag to express(1) to specify the - template engine to use. - * Added _--css_ flag to express(1) to specify the - stylesheet engine to use (or just plain css by default). - * Added `app.all()` support [thanks aheckmann] - * Added partial direct object support. - You may now `partial('user', user)` providing the "user" local, - vs previously `partial('user', { object: user })`. - * Added _route-separation_ example since many people question ways - to do this with CommonJS modules. Also view the _blog_ example for - an alternative. - * Performance; caching view path derived partial object names - * Fixed partial local inheritance precedence. [reported by Nick Poulden] Closes #454 - * Fixed jsonp support; _text/javascript_ as per mailinglist discussion - -1.0.0rc4 / 2010-10-14 -================== - - * Added _NODE_ENV_ support, _EXPRESS_ENV_ is deprecated and will be removed in 1.0.0 - * Added route-middleware support (very helpful, see the [docs](http://expressjs.com/guide.html#Route-Middleware)) - * Added _jsonp callback_ setting to enable/disable jsonp autowrapping [Dav Glass] - * Added callback query check on response.send to autowrap JSON objects for simple webservice implementations [Dav Glass] - * Added `partial()` support for array-like collections. Closes #434 - * Added support for swappable querystring parsers - * Added session usage docs. Closes #443 - * Added dynamic helper caching. Closes #439 [suggested by maritz] - * Added authentication example - * Added basic Range support to `res.sendfile()` (and `res.download()` etc) - * Changed; `express(1)` generated app using 2 spaces instead of 4 - * Default env to "development" again [aheckmann] - * Removed _context_ option is no more, use "scope" - * Fixed; exposing _./support_ libs to examples so they can run without installs - * Fixed mvc example - -1.0.0rc3 / 2010-09-20 -================== - - * Added confirmation for `express(1)` app generation. Closes #391 - * Added extending of flash formatters via `app.flashFormatters` - * Added flash formatter support. Closes #411 - * Added streaming support to `res.sendfile()` using `sys.pump()` when >= "stream threshold" - * Added _stream threshold_ setting for `res.sendfile()` - * Added `res.send()` __HEAD__ support - * Added `res.clearCookie()` - * Added `res.cookie()` - * Added `res.render()` headers option - * Added `res.redirect()` response bodies - * Added `res.render()` status option support. Closes #425 [thanks aheckmann] - * Fixed `res.sendfile()` responding with 403 on malicious path - * Fixed `res.download()` bug; when an error occurs remove _Content-Disposition_ - * Fixed; mounted apps settings now inherit from parent app [aheckmann] - * Fixed; stripping Content-Length / Content-Type when 204 - * Fixed `res.send()` 204. Closes #419 - * Fixed multiple _Set-Cookie_ headers via `res.header()`. Closes #402 - * Fixed bug messing with error handlers when `listenFD()` is called instead of `listen()`. [thanks guillermo] - - -1.0.0rc2 / 2010-08-17 -================== - - * Added `app.register()` for template engine mapping. Closes #390 - * Added `res.render()` callback support as second argument (no options) - * Added callback support to `res.download()` - * Added callback support for `res.sendfile()` - * Added support for middleware access via `express.middlewareName()` vs `connect.middlewareName()` - * Added "partials" setting to docs - * Added default expresso tests to `express(1)` generated app. Closes #384 - * Fixed `res.sendfile()` error handling, defer via `next()` - * Fixed `res.render()` callback when a layout is used [thanks guillermo] - * Fixed; `make install` creating ~/.node_libraries when not present - * Fixed issue preventing error handlers from being defined anywhere. Closes #387 - -1.0.0rc / 2010-07-28 -================== - - * Added mounted hook. Closes #369 - * Added connect dependency to _package.json_ - - * Removed "reload views" setting and support code - development env never caches, production always caches. - - * Removed _param_ in route callbacks, signature is now - simply (req, res, next), previously (req, res, params, next). - Use _req.params_ for path captures, _req.query_ for GET params. - - * Fixed "home" setting - * Fixed middleware/router precedence issue. Closes #366 - * Fixed; _configure()_ callbacks called immediately. Closes #368 - -1.0.0beta2 / 2010-07-23 -================== - - * Added more examples - * Added; exporting `Server` constructor - * Added `Server#helpers()` for view locals - * Added `Server#dynamicHelpers()` for dynamic view locals. Closes #349 - * Added support for absolute view paths - * Added; _home_ setting defaults to `Server#route` for mounted apps. Closes #363 - * Added Guillermo Rauch to the contributor list - * Added support for "as" for non-collection partials. Closes #341 - * Fixed _install.sh_, ensuring _~/.node_libraries_ exists. Closes #362 [thanks jf] - * Fixed `res.render()` exceptions, now passed to `next()` when no callback is given [thanks guillermo] - * Fixed instanceof `Array` checks, now `Array.isArray()` - * Fixed express(1) expansion of public dirs. Closes #348 - * Fixed middleware precedence. Closes #345 - * Fixed view watcher, now async [thanks aheckmann] - -1.0.0beta / 2010-07-15 -================== - - * Re-write - - much faster - - much lighter - - Check [ExpressJS.com](http://expressjs.com) for migration guide and updated docs - -0.14.0 / 2010-06-15 -================== - - * Utilize relative requires - * Added Static bufferSize option [aheckmann] - * Fixed caching of view and partial subdirectories [aheckmann] - * Fixed mime.type() comments now that ".ext" is not supported - * Updated haml submodule - * Updated class submodule - * Removed bin/express - -0.13.0 / 2010-06-01 -================== - - * Added node v0.1.97 compatibility - * Added support for deleting cookies via Request#cookie('key', null) - * Updated haml submodule - * Fixed not-found page, now using using charset utf-8 - * Fixed show-exceptions page, now using using charset utf-8 - * Fixed view support due to fs.readFile Buffers - * Changed; mime.type() no longer accepts ".type" due to node extname() changes - -0.12.0 / 2010-05-22 -================== - - * Added node v0.1.96 compatibility - * Added view `helpers` export which act as additional local variables - * Updated haml submodule - * Changed ETag; removed inode, modified time only - * Fixed LF to CRLF for setting multiple cookies - * Fixed cookie complation; values are now urlencoded - * Fixed cookies parsing; accepts quoted values and url escaped cookies - -0.11.0 / 2010-05-06 -================== - - * Added support for layouts using different engines - - this.render('page.html.haml', { layout: 'super-cool-layout.html.ejs' }) - - this.render('page.html.haml', { layout: 'foo' }) // assumes 'foo.html.haml' - - this.render('page.html.haml', { layout: false }) // no layout - * Updated ext submodule - * Updated haml submodule - * Fixed EJS partial support by passing along the context. Issue #307 - -0.10.1 / 2010-05-03 -================== - - * Fixed binary uploads. - -0.10.0 / 2010-04-30 -================== - - * Added charset support via Request#charset (automatically assigned to 'UTF-8' when respond()'s - encoding is set to 'utf8' or 'utf-8'. - * Added "encoding" option to Request#render(). Closes #299 - * Added "dump exceptions" setting, which is enabled by default. - * Added simple ejs template engine support - * Added error reponse support for text/plain, application/json. Closes #297 - * Added callback function param to Request#error() - * Added Request#sendHead() - * Added Request#stream() - * Added support for Request#respond(304, null) for empty response bodies - * Added ETag support to Request#sendfile() - * Added options to Request#sendfile(), passed to fs.createReadStream() - * Added filename arg to Request#download() - * Performance enhanced due to pre-reversing plugins so that plugins.reverse() is not called on each request - * Performance enhanced by preventing several calls to toLowerCase() in Router#match() - * Changed; Request#sendfile() now streams - * Changed; Renamed Request#halt() to Request#respond(). Closes #289 - * Changed; Using sys.inspect() instead of JSON.encode() for error output - * Changed; run() returns the http.Server instance. Closes #298 - * Changed; Defaulting Server#host to null (INADDR_ANY) - * Changed; Logger "common" format scale of 0.4f - * Removed Logger "request" format - * Fixed; Catching ENOENT in view caching, preventing error when "views/partials" is not found - * Fixed several issues with http client - * Fixed Logger Content-Length output - * Fixed bug preventing Opera from retaining the generated session id. Closes #292 - -0.9.0 / 2010-04-14 -================== - - * Added DSL level error() route support - * Added DSL level notFound() route support - * Added Request#error() - * Added Request#notFound() - * Added Request#render() callback function. Closes #258 - * Added "max upload size" setting - * Added "magic" variables to collection partials (\_\_index\_\_, \_\_length\_\_, \_\_isFirst\_\_, \_\_isLast\_\_). Closes #254 - * Added [haml.js](http://github.com/visionmedia/haml.js) submodule; removed haml-js - * Added callback function support to Request#halt() as 3rd/4th arg - * Added preprocessing of route param wildcards using param(). Closes #251 - * Added view partial support (with collections etc) - * Fixed bug preventing falsey params (such as ?page=0). Closes #286 - * Fixed setting of multiple cookies. Closes #199 - * Changed; view naming convention is now NAME.TYPE.ENGINE (for example page.html.haml) - * Changed; session cookie is now httpOnly - * Changed; Request is no longer global - * Changed; Event is no longer global - * Changed; "sys" module is no longer global - * Changed; moved Request#download to Static plugin where it belongs - * Changed; Request instance created before body parsing. Closes #262 - * Changed; Pre-caching views in memory when "cache view contents" is enabled. Closes #253 - * Changed; Pre-caching view partials in memory when "cache view partials" is enabled - * Updated support to node --version 0.1.90 - * Updated dependencies - * Removed set("session cookie") in favour of use(Session, { cookie: { ... }}) - * Removed utils.mixin(); use Object#mergeDeep() - -0.8.0 / 2010-03-19 -================== - - * Added coffeescript example app. Closes #242 - * Changed; cache api now async friendly. Closes #240 - * Removed deprecated 'express/static' support. Use 'express/plugins/static' - -0.7.6 / 2010-03-19 -================== - - * Added Request#isXHR. Closes #229 - * Added `make install` (for the executable) - * Added `express` executable for setting up simple app templates - * Added "GET /public/*" to Static plugin, defaulting to /public - * Added Static plugin - * Fixed; Request#render() only calls cache.get() once - * Fixed; Namespacing View caches with "view:" - * Fixed; Namespacing Static caches with "static:" - * Fixed; Both example apps now use the Static plugin - * Fixed set("views"). Closes #239 - * Fixed missing space for combined log format - * Deprecated Request#sendfile() and 'express/static' - * Removed Server#running - -0.7.5 / 2010-03-16 -================== - - * Added Request#flash() support without args, now returns all flashes - * Updated ext submodule - -0.7.4 / 2010-03-16 -================== - - * Fixed session reaper - * Changed; class.js replacing js-oo Class implementation (quite a bit faster, no browser cruft) - -0.7.3 / 2010-03-16 -================== - - * Added package.json - * Fixed requiring of haml / sass due to kiwi removal - -0.7.2 / 2010-03-16 -================== - - * Fixed GIT submodules (HAH!) - -0.7.1 / 2010-03-16 -================== - - * Changed; Express now using submodules again until a PM is adopted - * Changed; chat example using millisecond conversions from ext - -0.7.0 / 2010-03-15 -================== - - * Added Request#pass() support (finds the next matching route, or the given path) - * Added Logger plugin (default "common" format replaces CommonLogger) - * Removed Profiler plugin - * Removed CommonLogger plugin - -0.6.0 / 2010-03-11 -================== - - * Added seed.yml for kiwi package management support - * Added HTTP client query string support when method is GET. Closes #205 - - * Added support for arbitrary view engines. - For example "foo.engine.html" will now require('engine'), - the exports from this module are cached after the first require(). - - * Added async plugin support - - * Removed usage of RESTful route funcs as http client - get() etc, use http.get() and friends - - * Removed custom exceptions - -0.5.0 / 2010-03-10 -================== - - * Added ext dependency (library of js extensions) - * Removed extname() / basename() utils. Use path module - * Removed toArray() util. Use arguments.values - * Removed escapeRegexp() util. Use RegExp.escape() - * Removed process.mixin() dependency. Use utils.mixin() - * Removed Collection - * Removed ElementCollection - * Shameless self promotion of ebook "Advanced JavaScript" (http://dev-mag.com) ;) - -0.4.0 / 2010-02-11 -================== - - * Added flash() example to sample upload app - * Added high level restful http client module (express/http) - * Changed; RESTful route functions double as HTTP clients. Closes #69 - * Changed; throwing error when routes are added at runtime - * Changed; defaulting render() context to the current Request. Closes #197 - * Updated haml submodule - -0.3.0 / 2010-02-11 -================== - - * Updated haml / sass submodules. Closes #200 - * Added flash message support. Closes #64 - * Added accepts() now allows multiple args. fixes #117 - * Added support for plugins to halt. Closes #189 - * Added alternate layout support. Closes #119 - * Removed Route#run(). Closes #188 - * Fixed broken specs due to use(Cookie) missing - -0.2.1 / 2010-02-05 -================== - - * Added "plot" format option for Profiler (for gnuplot processing) - * Added request number to Profiler plugin - * Fixed binary encoding for multi-part file uploads, was previously defaulting to UTF8 - * Fixed issue with routes not firing when not files are present. Closes #184 - * Fixed process.Promise -> events.Promise - -0.2.0 / 2010-02-03 -================== - - * Added parseParam() support for name[] etc. (allows for file inputs with "multiple" attr) Closes #180 - * Added Both Cache and Session option "reapInterval" may be "reapEvery". Closes #174 - * Added expiration support to cache api with reaper. Closes #133 - * Added cache Store.Memory#reap() - * Added Cache; cache api now uses first class Cache instances - * Added abstract session Store. Closes #172 - * Changed; cache Memory.Store#get() utilizing Collection - * Renamed MemoryStore -> Store.Memory - * Fixed use() of the same plugin several time will always use latest options. Closes #176 - -0.1.0 / 2010-02-03 -================== - - * Changed; Hooks (before / after) pass request as arg as well as evaluated in their context - * Updated node support to 0.1.27 Closes #169 - * Updated dirname(__filename) -> __dirname - * Updated libxmljs support to v0.2.0 - * Added session support with memory store / reaping - * Added quick uid() helper - * Added multi-part upload support - * Added Sass.js support / submodule - * Added production env caching view contents and static files - * Added static file caching. Closes #136 - * Added cache plugin with memory stores - * Added support to StaticFile so that it works with non-textual files. - * Removed dirname() helper - * Removed several globals (now their modules must be required) - -0.0.2 / 2010-01-10 -================== - - * Added view benchmarks; currently haml vs ejs - * Added Request#attachment() specs. Closes #116 - * Added use of node's parseQuery() util. Closes #123 - * Added `make init` for submodules - * Updated Haml - * Updated sample chat app to show messages on load - * Updated libxmljs parseString -> parseHtmlString - * Fixed `make init` to work with older versions of git - * Fixed specs can now run independant specs for those who cant build deps. Closes #127 - * Fixed issues introduced by the node url module changes. Closes 126. - * Fixed two assertions failing due to Collection#keys() returning strings - * Fixed faulty Collection#toArray() spec due to keys() returning strings - * Fixed `make test` now builds libxmljs.node before testing - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/LICENSE b/node_modules/express/LICENSE deleted file mode 100644 index d23e93ce9..000000000 --- a/node_modules/express/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2009-2013 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/Makefile b/node_modules/express/Makefile deleted file mode 100644 index a1f33a702..000000000 --- a/node_modules/express/Makefile +++ /dev/null @@ -1,34 +0,0 @@ - -MOCHA_OPTS= --check-leaks -REPORTER = dot - -check: test - -test: test-unit test-acceptance - -test-unit: - @NODE_ENV=test ./node_modules/.bin/mocha \ - --reporter $(REPORTER) \ - --globals setImmediate,clearImmediate \ - $(MOCHA_OPTS) - -test-acceptance: - @NODE_ENV=test ./node_modules/.bin/mocha \ - --reporter $(REPORTER) \ - --bail \ - test/acceptance/*.js - -test-cov: lib-cov - @EXPRESS_COV=1 $(MAKE) test REPORTER=html-cov > coverage.html - -lib-cov: - @jscoverage lib lib-cov - -bench: - @$(MAKE) -C benchmarks - -clean: - rm -f coverage.html - rm -fr lib-cov - -.PHONY: test test-unit test-acceptance bench clean diff --git a/node_modules/express/Readme.md b/node_modules/express/Readme.md deleted file mode 100644 index e1e3f7e98..000000000 --- a/node_modules/express/Readme.md +++ /dev/null @@ -1,126 +0,0 @@ -[![express logo](http://f.cl.ly/items/0V2S1n0K1i3y1c122g04/Screen%20Shot%202012-04-11%20at%209.59.42%20AM.png)](http://expressjs.com/) - - Fast, unopinionated, minimalist web framework for [node](http://nodejs.org). - - [![Build Status](https://secure.travis-ci.org/visionmedia/express.png)](http://travis-ci.org/visionmedia/express) [![Gittip](http://img.shields.io/gittip/visionmedia.png)](https://www.gittip.com/visionmedia/) - -```js -var express = require('express'); -var app = express(); - -app.get('/', function(req, res){ - res.send('Hello World'); -}); - -app.listen(3000); -``` - -## Installation - - $ npm install -g express - -## Quick Start - - The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below: - - Create the app: - - $ npm install -g express - $ express /tmp/foo && cd /tmp/foo - - Install dependencies: - - $ npm install - - Start the server: - - $ node app - -## Features - - * Built on [Connect](http://github.com/senchalabs/connect) - * Robust routing - * HTTP helpers (redirection, caching, etc) - * View system supporting 14+ template engines - * Content negotiation - * Focus on high performance - * Environment based configuration - * Executable for generating applications quickly - * High test coverage - -## Philosophy - - The Express philosophy is to provide small, robust tooling for HTTP servers, making - it a great solution for single page applications, web sites, hybrids, or public - HTTP APIs. - - Built on Connect, you can use _only_ what you need, and nothing more. Applications - can be as big or as small as you like, even a single file. Express does - not force you to use any specific ORM or template engine. With support for over - 14 template engines via [Consolidate.js](http://github.com/visionmedia/consolidate.js), - you can quickly craft your perfect framework. - -## More Information - - * [Website and Documentation](http://expressjs.com/) stored at [visionmedia/expressjs.com](https://github.com/visionmedia/expressjs.com) - * Join #express on freenode - * [Google Group](http://groups.google.com/group/express-js) for discussion - * Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) on twitter for updates - * Visit the [Wiki](http://github.com/visionmedia/express/wiki) - * [Русскоязычная документация](http://jsman.ru/express/) - * Run express examples [online](https://runnable.com/express) - -## Viewing Examples - -Clone the Express repo, then install the dev dependencies to install all the example / test suite dependencies: - - $ git clone git://github.com/visionmedia/express.git --depth 1 - $ cd express - $ npm install - -Then run whichever tests you want: - - $ node examples/content-negotiation - -You can also view live examples here: - - - -## Running Tests - -To run the test suite, first invoke the following command within the repo, installing the development dependencies: - - $ npm install - -Then run the tests: - - $ make test - -## Contributors - - https://github.com/visionmedia/express/graphs/contributors - -## License - -(The MIT License) - -Copyright (c) 2009-2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/benchmarks/Makefile b/node_modules/express/benchmarks/Makefile deleted file mode 100644 index baf0d6fce..000000000 --- a/node_modules/express/benchmarks/Makefile +++ /dev/null @@ -1,13 +0,0 @@ - -all: - @./run 1 middleware - @./run 5 middleware - @./run 10 middleware - @./run 15 middleware - @./run 20 middleware - @./run 30 middleware - @./run 50 middleware - @./run 100 middleware - @echo - -.PHONY: all diff --git a/node_modules/express/benchmarks/middleware.js b/node_modules/express/benchmarks/middleware.js deleted file mode 100644 index 3aa7a8b4a..000000000 --- a/node_modules/express/benchmarks/middleware.js +++ /dev/null @@ -1,23 +0,0 @@ - -var http = require('http'); -var express = require('..'); -var app = express(); - -// number of middleware - -var n = parseInt(process.env.MW || '1', 10); -console.log(' %s middleware', n); - -while (n--) { - app.use(function(req, res, next){ - next(); - }); -} - -var body = new Buffer('Hello World'); - -app.use(function(req, res, next){ - res.send(body); -}); - -app.listen(3333); diff --git a/node_modules/express/benchmarks/run b/node_modules/express/benchmarks/run deleted file mode 100644 index 93b5bc52f..000000000 --- a/node_modules/express/benchmarks/run +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env bash - -echo -MW=$1 node $2 & -pid=$! - -sleep 2 - -wrk 'http://localhost:3333/?foo[bar]=baz' \ - -d 3 \ - -c 50 \ - -t 8 \ - | grep 'Requests/sec' \ - | awk '{ print " " $2 }' - -kill $pid diff --git a/node_modules/express/bin/express b/node_modules/express/bin/express deleted file mode 100644 index cb9792883..000000000 --- a/node_modules/express/bin/express +++ /dev/null @@ -1,423 +0,0 @@ -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander') - , mkdirp = require('mkdirp') - , pkg = require('../package.json') - , version = pkg.version - , os = require('os') - , fs = require('fs'); - -// CLI - -program - .version(version) - .usage('[options] [dir]') - .option('-s, --sessions', 'add session support') - .option('-e, --ejs', 'add ejs engine support (defaults to jade)') - .option('-J, --jshtml', 'add jshtml engine support (defaults to jade)') - .option('-H, --hogan', 'add hogan.js engine support') - .option('-c, --css ', 'add stylesheet support (less|stylus) (defaults to plain css)') - .option('-f, --force', 'force on non-empty directory') - .parse(process.argv); - -// Path - -var path = program.args.shift() || '.'; - -// end-of-line code - -var eol = os.EOL - -// Template engine - -program.template = 'jade'; -if (program.ejs) program.template = 'ejs'; -if (program.jshtml) program.template = 'jshtml'; -if (program.hogan) program.template = 'hjs'; - -/** - * Routes index template. - */ - -var index = [ - '' - , '/*' - , ' * GET home page.' - , ' */' - , '' - , 'exports.index = function(req, res){' - , ' res.render(\'index\', { title: \'Express\' });' - , '};' -].join(eol); - -/** - * Routes users template. - */ - -var users = [ - '' - , '/*' - , ' * GET users listing.' - , ' */' - , '' - , 'exports.list = function(req, res){' - , ' res.send("respond with a resource");' - , '};' -].join(eol); - -/** - * Jade layout template. - */ - -var jadeLayout = [ - 'doctype html' - , 'html' - , ' head' - , ' title= title' - , ' link(rel=\'stylesheet\', href=\'/stylesheets/style.css\')' - , ' body' - , ' block content' -].join(eol); - -/** - * Jade index template. - */ - -var jadeIndex = [ - 'extends layout' - , '' - , 'block content' - , ' h1= title' - , ' p Welcome to #{title}' -].join(eol); - -/** - * EJS index template. - */ - -var ejsIndex = [ - '' - , '' - , ' ' - , ' <%= title %>' - , ' ' - , ' ' - , ' ' - , '

<%= title %>

' - , '

Welcome to <%= title %>

' - , ' ' - , '' -].join(eol); - -/** - * JSHTML layout template. - */ - -var jshtmlLayout = [ - '' - , '' - , ' ' - , ' @write(title) ' - , ' ' - , ' ' - , ' ' - , ' @write(body)' - , ' ' - , '' -].join(eol); - -/** - * JSHTML index template. - */ - -var jshtmlIndex = [ - '

@write(title)

' - , '

Welcome to @write(title)

' -].join(eol); - -/** - * Hogan.js index template. - */ -var hoganIndex = [ - '' - , '' - , ' ' - , ' {{ title }}' - , ' ' - , ' ' - , ' ' - , '

{{ title }}

' - , '

Welcome to {{ title }}

' - , ' ' - , '' -].join(eol); - -/** - * Default css template. - */ - -var css = [ - 'body {' - , ' padding: 50px;' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;' - , '}' - , '' - , 'a {' - , ' color: #00B7FF;' - , '}' -].join(eol); - -/** - * Default less template. - */ - -var less = [ - 'body {' - , ' padding: 50px;' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;' - , '}' - , '' - , 'a {' - , ' color: #00B7FF;' - , '}' -].join(eol); - -/** - * Default stylus template. - */ - -var stylus = [ - 'body' - , ' padding: 50px' - , ' font: 14px "Lucida Grande", Helvetica, Arial, sans-serif' - , 'a' - , ' color: #00B7FF' -].join(eol); - -/** - * App template. - */ - -var app = [ - '' - , '/**' - , ' * Module dependencies.' - , ' */' - , '' - , 'var express = require(\'express\');' - , 'var routes = require(\'./routes\');' - , 'var user = require(\'./routes/user\');' - , 'var http = require(\'http\');' - , 'var path = require(\'path\');' - , '' - , 'var app = express();' - , '' - , '// all environments' - , 'app.set(\'port\', process.env.PORT || 3000);' - , 'app.set(\'views\', path.join(__dirname, \'views\'));' - , 'app.set(\'view engine\', \':TEMPLATE\');' - , 'app.use(express.favicon());' - , 'app.use(express.logger(\'dev\'));' - , 'app.use(express.json());' - , 'app.use(express.urlencoded());' - , 'app.use(express.methodOverride());{sess}' - , 'app.use(app.router);{css}' - , 'app.use(express.static(path.join(__dirname, \'public\')));' - , '' - , '// development only' - , 'if (\'development\' == app.get(\'env\')) {' - , ' app.use(express.errorHandler());' - , '}' - , '' - , 'app.get(\'/\', routes.index);' - , 'app.get(\'/users\', user.list);' - , '' - , 'http.createServer(app).listen(app.get(\'port\'), function(){' - , ' console.log(\'Express server listening on port \' + app.get(\'port\'));' - , '});' - , '' -].join(eol); - -// Generate application - -(function createApplication(path) { - emptyDirectory(path, function(empty){ - if (empty || program.force) { - createApplicationAt(path); - } else { - program.confirm('destination is not empty, continue? ', function(ok){ - if (ok) { - process.stdin.destroy(); - createApplicationAt(path); - } else { - abort('aborting'); - } - }); - } - }); -})(path); - -/** - * Create application at the given directory `path`. - * - * @param {String} path - */ - -function createApplicationAt(path) { - console.log(); - process.on('exit', function(){ - console.log(); - console.log(' install dependencies:'); - console.log(' $ cd %s && npm install', path); - console.log(); - console.log(' run the app:'); - console.log(' $ node app'); - console.log(); - }); - - mkdir(path, function(){ - mkdir(path + '/public'); - mkdir(path + '/public/javascripts'); - mkdir(path + '/public/images'); - mkdir(path + '/public/stylesheets', function(){ - switch (program.css) { - case 'less': - write(path + '/public/stylesheets/style.less', less); - break; - case 'stylus': - write(path + '/public/stylesheets/style.styl', stylus); - break; - default: - write(path + '/public/stylesheets/style.css', css); - } - }); - - mkdir(path + '/routes', function(){ - write(path + '/routes/index.js', index); - write(path + '/routes/user.js', users); - }); - - mkdir(path + '/views', function(){ - switch (program.template) { - case 'ejs': - write(path + '/views/index.ejs', ejsIndex); - break; - case 'jade': - write(path + '/views/layout.jade', jadeLayout); - write(path + '/views/index.jade', jadeIndex); - break; - case 'jshtml': - write(path + '/views/layout.jshtml', jshtmlLayout); - write(path + '/views/index.jshtml', jshtmlIndex); - break; - case 'hjs': - write(path + '/views/index.hjs', hoganIndex); - break; - - } - }); - - // CSS Engine support - switch (program.css) { - case 'less': - app = app.replace('{css}', eol + 'app.use(require(\'less-middleware\')({ src: path.join(__dirname, \'public\') }));'); - break; - case 'stylus': - app = app.replace('{css}', eol + 'app.use(require(\'stylus\').middleware(path.join(__dirname, \'public\')));'); - break; - default: - app = app.replace('{css}', ''); - } - - // Session support - app = app.replace('{sess}', program.sessions - ? eol + 'app.use(express.cookieParser(\'your secret here\'));' + eol + 'app.use(express.session());' - : ''); - - // Template support - app = app.replace(':TEMPLATE', program.template); - - // package.json - var pkg = { - name: 'application-name' - , version: '0.0.1' - , private: true - , scripts: { start: 'node app.js' } - , dependencies: { - express: version - } - } - - if (program.template) pkg.dependencies[program.template] = '*'; - - // CSS Engine support - switch (program.css) { - case 'less': - pkg.dependencies['less-middleware'] = '*'; - break; - default: - if (program.css) { - pkg.dependencies[program.css] = '*'; - } - } - - write(path + '/package.json', JSON.stringify(pkg, null, 2)); - write(path + '/app.js', app); - }); -} - -/** - * Check if the given directory `path` is empty. - * - * @param {String} path - * @param {Function} fn - */ - -function emptyDirectory(path, fn) { - fs.readdir(path, function(err, files){ - if (err && 'ENOENT' != err.code) throw err; - fn(!files || !files.length); - }); -} - -/** - * echo str > path. - * - * @param {String} path - * @param {String} str - */ - -function write(path, str) { - fs.writeFile(path, str); - console.log(' \x1b[36mcreate\x1b[0m : ' + path); -} - -/** - * Mkdir -p. - * - * @param {String} path - * @param {Function} fn - */ - -function mkdir(path, fn) { - mkdirp(path, 0755, function(err){ - if (err) throw err; - console.log(' \033[36mcreate\033[0m : ' + path); - fn && fn(); - }); -} - -/** - * Exit with the given `str`. - * - * @param {String} str - */ - -function abort(str) { - console.error(str); - process.exit(1); -} diff --git a/node_modules/express/index.js b/node_modules/express/index.js deleted file mode 100644 index bfe99345b..000000000 --- a/node_modules/express/index.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = process.env.EXPRESS_COV - ? require('./lib-cov/express') - : require('./lib/express'); \ No newline at end of file diff --git a/node_modules/express/lib/application.js b/node_modules/express/lib/application.js deleted file mode 100644 index 865e1e02b..000000000 --- a/node_modules/express/lib/application.js +++ /dev/null @@ -1,534 +0,0 @@ -/** - * Module dependencies. - */ - -var connect = require('connect') - , Router = require('./router') - , methods = require('methods') - , middleware = require('./middleware') - , debug = require('debug')('express:application') - , locals = require('./utils').locals - , View = require('./view') - , utils = connect.utils - , http = require('http'); - -/** - * Application prototype. - */ - -var app = exports = module.exports = {}; - -/** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - * - * @api private - */ - -app.init = function(){ - this.cache = {}; - this.settings = {}; - this.engines = {}; - this.defaultConfiguration(); -}; - -/** - * Initialize application configuration. - * - * @api private - */ - -app.defaultConfiguration = function(){ - // default settings - this.enable('x-powered-by'); - this.enable('etag'); - this.set('env', process.env.NODE_ENV || 'development'); - this.set('subdomain offset', 2); - debug('booting in %s mode', this.get('env')); - - // implicit middleware - this.use(connect.query()); - this.use(middleware.init(this)); - - // inherit protos - this.on('mount', function(parent){ - this.request.__proto__ = parent.request; - this.response.__proto__ = parent.response; - this.engines.__proto__ = parent.engines; - this.settings.__proto__ = parent.settings; - }); - - // router - this._router = new Router(this); - this.routes = this._router.map; - this.__defineGetter__('router', function(){ - this._usedRouter = true; - this._router.caseSensitive = this.enabled('case sensitive routing'); - this._router.strict = this.enabled('strict routing'); - return this._router.middleware; - }); - - // setup locals - this.locals = locals(this); - - // default locals - this.locals.settings = this.settings; - - // default configuration - this.set('view', View); - this.set('views', process.cwd() + '/views'); - this.set('jsonp callback name', 'callback'); - - this.configure('development', function(){ - this.set('json spaces', 2); - }); - - this.configure('production', function(){ - this.enable('view cache'); - }); -}; - -/** - * Proxy `connect#use()` to apply settings to - * mounted applications. - * - * @param {String|Function|Server} route - * @param {Function|Server} fn - * @return {app} for chaining - * @api public - */ - -app.use = function(route, fn){ - var app; - - // default route to '/' - if ('string' != typeof route) fn = route, route = '/'; - - // express app - if (fn.handle && fn.set) app = fn; - - // restore .app property on req and res - if (app) { - app.route = route; - fn = function(req, res, next) { - var orig = req.app; - app.handle(req, res, function(err){ - req.__proto__ = orig.request; - res.__proto__ = orig.response; - next(err); - }); - }; - } - - connect.proto.use.call(this, route, fn); - - // mounted an app - if (app) { - app.parent = this; - app.emit('mount', this); - } - - return this; -}; - -/** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.jade" file Express will invoke the following internally: - * - * app.engine('jade', require('jade').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/visionmedia/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - * - * @param {String} ext - * @param {Function} fn - * @return {app} for chaining - * @api public - */ - -app.engine = function(ext, fn){ - if ('function' != typeof fn) throw new Error('callback function required'); - if ('.' != ext[0]) ext = '.' + ext; - this.engines[ext] = fn; - return this; -}; - -/** - * Map the given param placeholder `name`(s) to the given callback(s). - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the same signature as middleware, the only difference - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. - * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * next(err); - * } else if (user) { - * req.user = user; - * next(); - * } else { - * next(new Error('failed to load user')); - * } - * }); - * }); - * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining - * @api public - */ - -app.param = function(name, fn){ - var self = this - , fns = [].slice.call(arguments, 1); - - // array - if (Array.isArray(name)) { - name.forEach(function(name){ - fns.forEach(function(fn){ - self.param(name, fn); - }); - }); - // param logic - } else if ('function' == typeof name) { - this._router.param(name); - // single - } else { - if (':' == name[0]) name = name.substr(1); - fns.forEach(function(fn){ - self._router.param(name, fn); - }); - } - - return this; -}; - -/** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.get('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param {String} setting - * @param {String} val - * @return {Server} for chaining - * @api public - */ - -app.set = function(setting, val){ - if (1 == arguments.length) { - return this.settings[setting]; - } else { - this.settings[setting] = val; - return this; - } -}; - -/** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - * - * @return {String} - * @api private - */ - -app.path = function(){ - return this.parent - ? this.parent.path() + this.route - : ''; -}; - -/** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true - * - * @param {String} setting - * @return {Boolean} - * @api public - */ - -app.enabled = function(setting){ - return !!this.set(setting); -}; - -/** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param {String} setting - * @return {Boolean} - * @api public - */ - -app.disabled = function(setting){ - return !this.set(setting); -}; - -/** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @api public - */ - -app.enable = function(setting){ - return this.set(setting, true); -}; - -/** - * Disable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @api public - */ - -app.disable = function(setting){ - return this.set(setting, false); -}; - -/** - * Configure callback for zero or more envs, - * when no `env` is specified that callback will - * be invoked for all environments. Any combination - * can be used multiple times, in any order desired. - * - * Examples: - * - * app.configure(function(){ - * // executed for all envs - * }); - * - * app.configure('stage', function(){ - * // executed staging env - * }); - * - * app.configure('stage', 'production', function(){ - * // executed for stage and production - * }); - * - * Note: - * - * These callbacks are invoked immediately, and - * are effectively sugar for the following: - * - * var env = process.env.NODE_ENV || 'development'; - * - * switch (env) { - * case 'development': - * ... - * break; - * case 'stage': - * ... - * break; - * case 'production': - * ... - * break; - * } - * - * @param {String} env... - * @param {Function} fn - * @return {app} for chaining - * @api public - */ - -app.configure = function(env, fn){ - var envs = 'all' - , args = [].slice.call(arguments); - fn = args.pop(); - if (args.length) envs = args; - if ('all' == envs || ~envs.indexOf(this.settings.env)) fn.call(this); - return this; -}; - -/** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. - */ - -methods.forEach(function(method){ - app[method] = function(path){ - if ('get' == method && 1 == arguments.length) return this.set(path); - - // deprecated - if (Array.isArray(path)) { - console.trace('passing an array to app.VERB() is deprecated and will be removed in 4.0'); - } - - // if no router attached yet, attach the router - if (!this._usedRouter) this.use(this.router); - - // setup route - this._router[method].apply(this._router, arguments); - return this; - }; -}); - -/** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param {String} path - * @param {Function} ... - * @return {app} for chaining - * @api public - */ - -app.all = function(path){ - var args = arguments; - methods.forEach(function(method){ - app[method].apply(this, args); - }, this); - return this; -}; - -// del -> delete alias - -app.del = app.delete; - -/** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: - * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param {String} name - * @param {String|Function} options or fn - * @param {Function} fn - * @api public - */ - -app.render = function(name, options, fn){ - var opts = {} - , cache = this.cache - , engines = this.engines - , view; - - // support callback function as second arg - if ('function' == typeof options) { - fn = options, options = {}; - } - - // merge app.locals - utils.merge(opts, this.locals); - - // merge options._locals - if (options._locals) utils.merge(opts, options._locals); - - // merge options - utils.merge(opts, options); - - // set .cache unless explicitly provided - opts.cache = null == opts.cache - ? this.enabled('view cache') - : opts.cache; - - // primed cache - if (opts.cache) view = cache[name]; - - // view - if (!view) { - view = new (this.get('view'))(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); - - if (!view.path) { - var err = new Error('Failed to lookup view "' + name + '" in views directory "' + view.root + '"'); - err.view = view; - return fn(err); - } - - // prime the cache - if (opts.cache) cache[name] = view; - } - - // render - try { - view.render(opts, fn); - } catch (err) { - fn(err); - } -}; - -/** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - * - * @return {http.Server} - * @api public - */ - -app.listen = function(){ - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; diff --git a/node_modules/express/lib/express.js b/node_modules/express/lib/express.js deleted file mode 100644 index 4f61cdbd4..000000000 --- a/node_modules/express/lib/express.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Module dependencies. - */ - -var merge = require('merge-descriptors'); -var connect = require('connect') - , proto = require('./application') - , Route = require('./router/route') - , Router = require('./router') - , req = require('./request') - , res = require('./response') - , utils = connect.utils; - -/** - * Expose `createApplication()`. - */ - -exports = module.exports = createApplication; - -/** - * Expose mime. - */ - -exports.mime = connect.mime; - -/** - * Create an express application. - * - * @return {Function} - * @api public - */ - -function createApplication() { - var app = connect(); - utils.merge(app, proto); - app.request = { __proto__: req, app: app }; - app.response = { __proto__: res, app: app }; - app.init(); - return app; -} - -/** - * Expose connect.middleware as express.* - * for example `express.logger` etc. - */ - -merge(exports, connect.middleware); - -/** - * Error on createServer(). - */ - -exports.createServer = function(){ - console.warn('Warning: express.createServer() is deprecated, express'); - console.warn('applications no longer inherit from http.Server,'); - console.warn('please use:'); - console.warn(''); - console.warn(' var express = require("express");'); - console.warn(' var app = express();'); - console.warn(''); - return createApplication(); -}; - -/** - * Expose the prototypes. - */ - -exports.application = proto; -exports.request = req; -exports.response = res; - -/** - * Expose constructors. - */ - -exports.Route = Route; -exports.Router = Router; - -// Error handler title - -exports.errorHandler.title = 'Express'; - diff --git a/node_modules/express/lib/middleware.js b/node_modules/express/lib/middleware.js deleted file mode 100644 index e07dd4cd5..000000000 --- a/node_modules/express/lib/middleware.js +++ /dev/null @@ -1,32 +0,0 @@ - -/** - * Module dependencies. - */ - -var utils = require('./utils'); - -/** - * Initialization middleware, exposing the - * request and response to eachother, as well - * as defaulting the X-Powered-By header field. - * - * @param {Function} app - * @return {Function} - * @api private - */ - -exports.init = function(app){ - return function expressInit(req, res, next){ - if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); - req.res = res; - res.req = req; - req.next = next; - - req.__proto__ = app.request; - res.__proto__ = app.response; - - res.locals = res.locals || utils.locals(res); - - next(); - } -}; diff --git a/node_modules/express/lib/request.js b/node_modules/express/lib/request.js deleted file mode 100644 index 3d41617eb..000000000 --- a/node_modules/express/lib/request.js +++ /dev/null @@ -1,529 +0,0 @@ - -/** - * Module dependencies. - */ - -var http = require('http') - , utils = require('./utils') - , connect = require('connect') - , fresh = require('fresh') - , parseRange = require('range-parser') - , parse = connect.utils.parseUrl - , mime = connect.mime; - -/** - * Request prototype. - */ - -var req = exports = module.exports = { - __proto__: http.IncomingMessage.prototype -}; - -/** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param {String} name - * @return {String} - * @api public - */ - -req.get = -req.header = function(name){ - switch (name = name.toLowerCase()) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[name]; - } -}; - -/** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json", a comma-delimted list such as "json, html, text/plain", - * an argument list such as `"json", "html", "text/plain"`, - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html', 'json'); - * req.accepts('html, json'); - * // => "json" - * - * @param {String|Array} type(s) - * @return {String} - * @api public - */ - -req.accepts = function(type){ - var args = arguments.length > 1 ? [].slice.apply(arguments) : type; - return utils.accepts(args, this.get('Accept')); -}; - -/** - * Check if the given `encoding` is accepted. - * - * @param {String} encoding - * @return {Boolean} - * @api public - */ - -req.acceptsEncoding = function(encoding){ - return !! ~this.acceptedEncodings.indexOf(encoding); -}; - -/** - * Check if the given `charset` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} charset - * @return {Boolean} - * @api public - */ - -req.acceptsCharset = function(charset){ - var accepted = this.acceptedCharsets; - return accepted.length - ? !! ~accepted.indexOf(charset) - : true; -}; - -/** - * Check if the given `lang` is acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} lang - * @return {Boolean} - * @api public - */ - -req.acceptsLanguage = function(lang){ - var accepted = this.acceptedLanguages; - return accepted.length - ? !! ~accepted.indexOf(lang) - : true; -}; - -/** - * Parse Range header field, - * capping to the given `size`. - * - * Unspecified ranges such as "0-" require - * knowledge of your resource length. In - * the case of a byte range this is of course - * the total number of bytes. If the Range - * header field is not given `null` is returned, - * `-1` when unsatisfiable, `-2` when syntactically invalid. - * - * NOTE: remember that ranges are inclusive, so - * for example "Range: users=0-3" should respond - * with 4 users when available, not 3. - * - * @param {Number} size - * @return {Array} - * @api public - */ - -req.range = function(size){ - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range); -}; - -/** - * Return an array of encodings. - * - * Examples: - * - * ['gzip', 'deflate'] - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('acceptedEncodings', function(){ - var accept = this.get('Accept-Encoding'); - return accept - ? accept.trim().split(/ *, */) - : []; -}); - -/** - * Return an array of Accepted media types - * ordered from highest quality to lowest. - * - * Examples: - * - * [ { value: 'application/json', - * quality: 1, - * type: 'application', - * subtype: 'json' }, - * { value: 'text/html', - * quality: 0.5, - * type: 'text', - * subtype: 'html' } ] - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('accepted', function(){ - var accept = this.get('Accept'); - return accept - ? utils.parseAccept(accept) - : []; -}); - -/** - * Return an array of Accepted languages - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Language: en;q=.5, en-us - * ['en-us', 'en'] - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('acceptedLanguages', function(){ - var accept = this.get('Accept-Language'); - return accept - ? utils - .parseParams(accept) - .map(function(obj){ - return obj.value; - }) - : []; -}); - -/** - * Return an array of Accepted charsets - * ordered from highest quality to lowest. - * - * Examples: - * - * Accept-Charset: iso-8859-5;q=.2, unicode-1-1;q=0.8 - * ['unicode-1-1', 'iso-8859-5'] - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('acceptedCharsets', function(){ - var accept = this.get('Accept-Charset'); - return accept - ? utils - .parseParams(accept) - .map(function(obj){ - return obj.value; - }) - : []; -}); - -/** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `connect.bodyParser()` middleware. - * - * @param {String} name - * @param {Mixed} [defaultValue] - * @return {String} - * @api public - */ - -req.param = function(name, defaultValue){ - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; - if (null != params[name] && params.hasOwnProperty(name)) return params[name]; - if (null != body[name]) return body[name]; - if (null != query[name]) return query[name]; - return defaultValue; -}; - -/** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param {String} type - * @return {Boolean} - * @api public - */ - -req.is = function(type){ - var ct = this.get('Content-Type'); - if (!ct) return false; - ct = ct.split(';')[0]; - if (!~type.indexOf('/')) type = mime.lookup(type); - if (~type.indexOf('*')) { - type = type.split('/'); - ct = ct.split('/'); - if ('*' == type[0] && type[1] == ct[1]) return true; - if ('*' == type[1] && type[0] == ct[0]) return true; - return false; - } - return !! ~ct.indexOf(type); -}; - -/** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting is enabled the "X-Forwarded-Proto" header - * field will be trusted. If you're running behind - * a reverse proxy that supplies https for you this - * may be enabled. - * - * @return {String} - * @api public - */ - -req.__defineGetter__('protocol', function(){ - var trustProxy = this.app.get('trust proxy'); - if (this.connection.encrypted) return 'https'; - if (!trustProxy) return 'http'; - var proto = this.get('X-Forwarded-Proto') || 'http'; - return proto.split(/\s*,\s*/)[0]; -}); - -/** - * Short-hand for: - * - * req.protocol == 'https' - * - * @return {Boolean} - * @api public - */ - -req.__defineGetter__('secure', function(){ - return 'https' == this.protocol; -}); - -/** - * Return the remote address, or when - * "trust proxy" is `true` return - * the upstream addr. - * - * @return {String} - * @api public - */ - -req.__defineGetter__('ip', function(){ - return this.ips[0] || this.connection.remoteAddress; -}); - -/** - * When "trust proxy" is `true`, parse - * the "X-Forwarded-For" ip address list. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream. - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('ips', function(){ - var trustProxy = this.app.get('trust proxy'); - var val = this.get('X-Forwarded-For'); - return trustProxy && val - ? val.split(/ *, */) - : []; -}); - -/** - * Return basic auth credentials. - * - * Examples: - * - * // http://tobi:hello@example.com - * req.auth - * // => { username: 'tobi', password: 'hello' } - * - * @return {Object} or undefined - * @api public - */ - -req.__defineGetter__('auth', function(){ - // missing - var auth = this.get('Authorization'); - if (!auth) return; - - // malformed - var parts = auth.split(' '); - if ('basic' != parts[0].toLowerCase()) return; - if (!parts[1]) return; - auth = parts[1]; - - // credentials - auth = new Buffer(auth, 'base64').toString().match(/^([^:]*):(.*)$/); - if (!auth) return; - return { username: auth[1], password: auth[2] }; -}); - -/** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - * - * @return {Array} - * @api public - */ - -req.__defineGetter__('subdomains', function(){ - var offset = this.app.get('subdomain offset'); - return (this.host || '') - .split('.') - .reverse() - .slice(offset); -}); - -/** - * Short-hand for `url.parse(req.url).pathname`. - * - * @return {String} - * @api public - */ - -req.__defineGetter__('path', function(){ - return parse(this).pathname; -}); - -/** - * Parse the "Host" header field hostname. - * - * @return {String} - * @api public - */ - -req.__defineGetter__('host', function(){ - var trustProxy = this.app.get('trust proxy'); - var host = trustProxy && this.get('X-Forwarded-Host'); - host = host || this.get('Host'); - if (!host) return; - return host.split(':')[0]; -}); - -/** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - * - * @return {Boolean} - * @api public - */ - -req.__defineGetter__('fresh', function(){ - var method = this.method; - var s = this.res.statusCode; - - // GET or HEAD for weak freshness validation only - if ('GET' != method && 'HEAD' != method) return false; - - // 2xx or 304 as per rfc2616 14.26 - if ((s >= 200 && s < 300) || 304 == s) { - return fresh(this.headers, this.res._headers); - } - - return false; -}); - -/** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - * - * @return {Boolean} - * @api public - */ - -req.__defineGetter__('stale', function(){ - return !this.fresh; -}); - -/** - * Check if the request was an _XMLHttpRequest_. - * - * @return {Boolean} - * @api public - */ - -req.__defineGetter__('xhr', function(){ - var val = this.get('X-Requested-With') || ''; - return 'xmlhttprequest' == val.toLowerCase(); -}); diff --git a/node_modules/express/lib/response.js b/node_modules/express/lib/response.js deleted file mode 100644 index 31c79c0d5..000000000 --- a/node_modules/express/lib/response.js +++ /dev/null @@ -1,799 +0,0 @@ -/** - * Module dependencies. - */ - -var http = require('http') - , path = require('path') - , connect = require('connect') - , utils = connect.utils - , sign = require('cookie-signature').sign - , normalizeType = require('./utils').normalizeType - , normalizeTypes = require('./utils').normalizeTypes - , etag = require('./utils').etag - , statusCodes = http.STATUS_CODES - , cookie = require('cookie') - , send = require('send') - , mime = connect.mime - , resolve = require('url').resolve - , basename = path.basename - , extname = path.extname; - -/** - * Response prototype. - */ - -var res = module.exports = { - __proto__: http.ServerResponse.prototype -}; - -/** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @api public - */ - -res.status = function(code){ - this.statusCode = code; - return this; -}; - -/** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param {Object} links - * @return {ServerResponse} - * @api public - */ - -res.links = function(links){ - var link = this.get('Link') || ''; - if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel){ - return '<' + links[rel] + '>; rel="' + rel + '"'; - }).join(', ')); -}; - -/** - * Send a response. - * - * Examples: - * - * res.send(new Buffer('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); - * - * @param {Mixed} body or status - * @param {Mixed} body - * @return {ServerResponse} - * @api public - */ - -res.send = function(body){ - var req = this.req; - var head = 'HEAD' == req.method; - var len; - - // settings - var app = this.app; - - // allow status / body - if (2 == arguments.length) { - // res.send(body, status) backwards compat - if ('number' != typeof body && 'number' == typeof arguments[1]) { - this.statusCode = arguments[1]; - } else { - this.statusCode = body; - body = arguments[1]; - } - } - - switch (typeof body) { - // response status - case 'number': - this.get('Content-Type') || this.type('txt'); - this.statusCode = body; - body = http.STATUS_CODES[body]; - break; - // string defaulting to html - case 'string': - if (!this.get('Content-Type')) { - this.charset = this.charset || 'utf-8'; - this.type('html'); - } - break; - case 'boolean': - case 'object': - if (null == body) { - body = ''; - } else if (Buffer.isBuffer(body)) { - this.get('Content-Type') || this.type('bin'); - } else { - return this.json(body); - } - break; - } - - // populate Content-Length - if (undefined !== body && !this.get('Content-Length')) { - this.set('Content-Length', len = Buffer.isBuffer(body) - ? body.length - : Buffer.byteLength(body)); - } - - // ETag support - // TODO: W/ support - if (app.settings.etag && len && 'GET' == req.method) { - if (!this.get('ETag')) { - this.set('ETag', etag(body)); - } - } - - // freshness - if (req.fresh) this.statusCode = 304; - - // strip irrelevant headers - if (204 == this.statusCode || 304 == this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - body = ''; - } - - // respond - this.end(head ? null : body); - return this; -}; - -/** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); - * - * @param {Mixed} obj or status - * @param {Mixed} obj - * @return {ServerResponse} - * @api public - */ - -res.json = function(obj){ - // allow status / body - if (2 == arguments.length) { - // res.json(body, status) backwards compat - if ('number' == typeof arguments[1]) { - this.statusCode = arguments[1]; - } else { - this.statusCode = obj; - obj = arguments[1]; - } - } - - // settings - var app = this.app; - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = JSON.stringify(obj, replacer, spaces); - - // content-type - this.charset = this.charset || 'utf-8'; - this.get('Content-Type') || this.set('Content-Type', 'application/json'); - - return this.send(body); -}; - -/** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); - * - * @param {Mixed} obj or status - * @param {Mixed} obj - * @return {ServerResponse} - * @api public - */ - -res.jsonp = function(obj){ - // allow status / body - if (2 == arguments.length) { - // res.json(body, status) backwards compat - if ('number' == typeof arguments[1]) { - this.statusCode = arguments[1]; - } else { - this.statusCode = obj; - obj = arguments[1]; - } - } - - // settings - var app = this.app; - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = JSON.stringify(obj, replacer, spaces) - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029'); - var callback = this.req.query[app.get('jsonp callback name')]; - - // content-type - this.charset = this.charset || 'utf-8'; - this.set('Content-Type', 'application/json'); - - // jsonp - if (callback) { - if (Array.isArray(callback)) callback = callback[0]; - this.set('Content-Type', 'text/javascript'); - var cb = callback.replace(/[^\[\]\w$.]/g, ''); - body = 'typeof ' + cb + ' === \'function\' && ' + cb + '(' + body + ');'; - } - - return this.send(body); -}; - -/** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `fn(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 - * - `root` root directory for relative filenames - * - * Examples: - * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @param {String} path - * @param {Object|Function} options or fn - * @param {Function} fn - * @api public - */ - -res.sendfile = function(path, options, fn){ - var self = this - , req = self.req - , next = this.req.next - , options = options || {} - , done; - - // support function as second arg - if ('function' == typeof options) { - fn = options; - options = {}; - } - - // socket errors - req.socket.on('error', error); - - // errors - function error(err) { - if (done) return; - done = true; - - // clean up - cleanup(); - if (!self.headerSent) self.removeHeader('Content-Disposition'); - - // callback available - if (fn) return fn(err); - - // list in limbo if there's no callback - if (self.headerSent) return; - - // delegate - next(err); - } - - // streaming - function stream(stream) { - if (done) return; - cleanup(); - if (fn) stream.on('end', fn); - } - - // cleanup - function cleanup() { - req.socket.removeListener('error', error); - } - - // transfer - var file = send(req, path); - if (options.root) file.root(options.root); - file.maxage(options.maxAge || 0); - file.on('error', error); - file.on('directory', next); - file.on('stream', stream); - file.pipe(this); - this.on('finish', cleanup); -}; - -/** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `fn(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headerSent` if you plan to respond. - * - * This method uses `res.sendfile()`. - * - * @param {String} path - * @param {String|Function} filename or fn - * @param {Function} fn - * @api public - */ - -res.download = function(path, filename, fn){ - // support function as second arg - if ('function' == typeof filename) { - fn = filename; - filename = null; - } - - filename = filename || path; - this.set('Content-Disposition', 'attachment; filename="' + basename(filename) + '"'); - return this.sendfile(path, fn); -}; - -/** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param {String} type - * @return {ServerResponse} for chaining - * @api public - */ - -res.contentType = -res.type = function(type){ - return this.set('Content-Type', ~type.indexOf('/') - ? type - : mime.lookup(type)); -}; - -/** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param {Object} obj - * @return {ServerResponse} for chaining - * @api public - */ - -res.format = function(obj){ - var req = this.req - , next = req.next; - - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); - - var key = req.accepts(keys); - - this.vary("Accept"); - - if (key) { - var type = normalizeType(key).value; - var charset = mime.charsets.lookup(type); - if (charset) type += '; charset=' + charset; - this.set('Content-Type', type); - obj[key](req, this, next); - } else if (fn) { - fn(); - } else { - var err = new Error('Not Acceptable'); - err.status = 406; - err.types = normalizeTypes(keys).map(function(o){ return o.value }); - next(err); - } - - return this; -}; - -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @api public - */ - -res.attachment = function(filename){ - if (filename) this.type(extname(filename)); - this.set('Content-Disposition', filename - ? 'attachment; filename="' + basename(filename) + '"' - : 'attachment'); - return this; -}; - -/** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - * - * @param {String|Object|Array} field - * @param {String} val - * @return {ServerResponse} for chaining - * @api public - */ - -res.set = -res.header = function(field, val){ - if (2 == arguments.length) { - if (Array.isArray(val)) val = val.map(String); - else val = String(val); - this.setHeader(field, val); - } else { - for (var key in field) { - this.set(key, field[key]); - } - } - return this; -}; - -/** - * Get value for header `field`. - * - * @param {String} field - * @return {String} - * @api public - */ - -res.get = function(field){ - return this.getHeader(field); -}; - -/** - * Clear cookie `name`. - * - * @param {String} name - * @param {Object} options - * @param {ServerResponse} for chaining - * @api public - */ - -res.clearCookie = function(name, options){ - var opts = { expires: new Date(1), path: '/' }; - return this.cookie(name, '', options - ? utils.merge(opts, options) - : opts); -}; - -/** - * Set cookie `name` to `val`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // save as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - * - * @param {String} name - * @param {String|Object} val - * @param {Options} options - * @api public - */ - -res.cookie = function(name, val, options){ - options = utils.merge({}, options); - var secret = this.req.secret; - var signed = options.signed; - if (signed && !secret) throw new Error('connect.cookieParser("secret") required for signed cookies'); - if ('number' == typeof val) val = val.toString(); - if ('object' == typeof val) val = 'j:' + JSON.stringify(val); - if (signed) val = 's:' + sign(val, secret); - if ('maxAge' in options) { - options.expires = new Date(Date.now() + options.maxAge); - options.maxAge /= 1000; - } - if (null == options.path) options.path = '/'; - this.set('Set-Cookie', cookie.serialize(name, String(val), options)); - return this; -}; - - -/** - * Set the location header to `url`. - * - * The given `url` can also be "back", which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); // /blog/post/1 -> /blog/login - * - * Mounting: - * - * When an application is mounted and `res.location()` - * is given a path that does _not_ lead with "/" it becomes - * relative to the mount-point. For example if the application - * is mounted at "/blog", the following would become "/blog/login". - * - * res.location('login'); - * - * While the leading slash would result in a location of "/login": - * - * res.location('/login'); - * - * @param {String} url - * @api public - */ - -res.location = function(url){ - var app = this.app - , req = this.req - , path; - - // "back" is an alias for the referrer - if ('back' == url) url = req.get('Referrer') || '/'; - - // relative - if (!~url.indexOf('://') && 0 != url.indexOf('//')) { - // relative to path - if ('.' == url[0]) { - path = req.originalUrl.split('?')[0]; - path = path + ('/' == path[path.length - 1] ? '' : '/'); - url = resolve(path, url); - // relative to mount-point - } else if ('/' != url[0]) { - path = app.path(); - url = path + '/' + url; - } - } - - // Respond - this.set('Location', url); - return this; -}; - -/** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('http://example.com', 301); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - * - * @param {String} url - * @param {Number} code - * @api public - */ - -res.redirect = function(url){ - var head = 'HEAD' == this.req.method - , status = 302 - , body; - - // allow status / url - if (2 == arguments.length) { - if ('number' == typeof url) { - status = url; - url = arguments[1]; - } else { - status = arguments[1]; - } - } - - // Set location header - this.location(url); - url = this.get('Location'); - - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statusCodes[status] + '. Redirecting to ' + encodeURI(url); - }, - - html: function(){ - var u = utils.escape(url); - body = '

' + statusCodes[status] + '. Redirecting to ' + u + '

'; - }, - - default: function(){ - body = ''; - } - }); - - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); - this.end(head ? null : body); -}; - -/** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. - * - * @param {Array|String} field - * @param {ServerResponse} for chaining - * @api public - */ - -res.vary = function(field){ - var self = this; - - // nothing - if (!field) return this; - - // array - if (Array.isArray(field)) { - field.forEach(function(field){ - self.vary(field); - }); - return; - } - - var vary = this.get('Vary'); - - // append - if (vary) { - vary = vary.split(/ *, */); - if (!~vary.indexOf(field)) vary.push(field); - this.set('Vary', vary.join(', ')); - return this; - } - - // set - this.set('Vary', field); - return this; -}; - -/** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - * - * @param {String} view - * @param {Object|Function} options or callback function - * @param {Function} fn - * @api public - */ - -res.render = function(view, options, fn){ - var self = this - , options = options || {} - , req = this.req - , app = req.app; - - // support callback function as second arg - if ('function' == typeof options) { - fn = options, options = {}; - } - - // merge res.locals - options._locals = self.locals; - - // default callback to respond - fn = fn || function(err, str){ - if (err) return req.next(err); - self.send(str); - }; - - // render - app.render(view, options, fn); -}; diff --git a/node_modules/express/lib/router/index.js b/node_modules/express/lib/router/index.js deleted file mode 100644 index cd2f26937..000000000 --- a/node_modules/express/lib/router/index.js +++ /dev/null @@ -1,321 +0,0 @@ -/** - * Module dependencies. - */ - -var Route = require('./route') - , utils = require('../utils') - , methods = require('methods') - , debug = require('debug')('express:router') - , parse = require('connect').utils.parseUrl; - -/** - * Expose `Router` constructor. - */ - -exports = module.exports = Router; - -/** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} options - * @api private - */ - -function Router(options) { - options = options || {}; - var self = this; - this.map = {}; - this.params = {}; - this._params = []; - this.caseSensitive = options.caseSensitive; - this.strict = options.strict; - this.middleware = function router(req, res, next){ - self._dispatch(req, res, next); - }; -} - -/** - * Register a param callback `fn` for the given `name`. - * - * @param {String|Function} name - * @param {Function} fn - * @return {Router} for chaining - * @api public - */ - -Router.prototype.param = function(name, fn){ - // param logic - if ('function' == typeof name) { - this._params.push(name); - return; - } - - // apply param functions - var params = this._params - , len = params.length - , ret; - - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } - } - - // ensure we end up with a - // middleware function - if ('function' != typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); - } - - (this.params[name] = this.params[name] || []).push(fn); - return this; -}; - -/** - * Route dispatcher aka the route "middleware". - * - * @param {IncomingMessage} req - * @param {ServerResponse} res - * @param {Function} next - * @api private - */ - -Router.prototype._dispatch = function(req, res, next){ - var params = this.params - , self = this; - - debug('dispatching %s %s (%s)', req.method, req.url, req.originalUrl); - - // route dispatch - (function pass(i, err){ - var paramCallbacks - , paramIndex = 0 - , paramVal - , route - , keys - , key; - - // match next route - function nextRoute(err) { - pass(req._route_index + 1, err); - } - - // match route - req.route = route = self.matchRequest(req, i); - - // implied OPTIONS - if (!route && 'OPTIONS' == req.method) return self._options(req, res, next); - - // no route - if (!route) return next(err); - debug('matched %s %s', route.method, route.path); - - // we have a route - // start at param 0 - req.params = route.params; - keys = route.keys; - i = 0; - - // param callbacks - function param(err) { - paramIndex = 0; - key = keys[i++]; - paramVal = key && req.params[key.name]; - paramCallbacks = key && params[key.name]; - - try { - if ('route' == err) { - nextRoute(); - } else if (err) { - i = 0; - callbacks(err); - } else if (paramCallbacks && undefined !== paramVal) { - paramCallback(); - } else if (key) { - param(); - } else { - i = 0; - callbacks(); - } - } catch (err) { - param(err); - } - }; - - param(err); - - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - if (err || !fn) return param(err); - fn(req, res, paramCallback, paramVal, key.name); - } - - // invoke route callbacks - function callbacks(err) { - var fn = route.callbacks[i++]; - try { - if ('route' == err) { - nextRoute(); - } else if (err && fn) { - if (fn.length < 4) return callbacks(err); - fn(err, req, res, callbacks); - } else if (fn) { - if (fn.length < 4) return fn(req, res, callbacks); - callbacks(); - } else { - nextRoute(err); - } - } catch (err) { - callbacks(err); - } - } - })(0); -}; - -/** - * Respond to __OPTIONS__ method. - * - * @param {IncomingMessage} req - * @param {ServerResponse} res - * @api private - */ - -Router.prototype._options = function(req, res, next){ - var path = parse(req).pathname - , body = this._optionsFor(path).join(','); - if (!body) return next(); - res.set('Allow', body).send(body); -}; - -/** - * Return an array of HTTP verbs or "options" for `path`. - * - * @param {String} path - * @return {Array} - * @api private - */ - -Router.prototype._optionsFor = function(path){ - var self = this; - return methods.filter(function(method){ - var routes = self.map[method]; - if (!routes || 'options' == method) return; - for (var i = 0, len = routes.length; i < len; ++i) { - if (routes[i].match(path)) return true; - } - }).map(function(method){ - return method.toUpperCase(); - }); -}; - -/** - * Attempt to match a route for `req` - * with optional starting index of `i` - * defaulting to 0. - * - * @param {IncomingMessage} req - * @param {Number} i - * @return {Route} - * @api private - */ - -Router.prototype.matchRequest = function(req, i, head){ - var method = req.method.toLowerCase() - , url = parse(req) - , path = url.pathname - , routes = this.map - , i = i || 0 - , route; - - // HEAD support - if (!head && 'head' == method) { - route = this.matchRequest(req, i, true); - if (route) return route; - method = 'get'; - } - - // routes for this method - if (routes = routes[method]) { - - // matching routes - for (var len = routes.length; i < len; ++i) { - route = routes[i]; - if (route.match(path)) { - req._route_index = i; - return route; - } - } - } -}; - -/** - * Attempt to match a route for `method` - * and `url` with optional starting - * index of `i` defaulting to 0. - * - * @param {String} method - * @param {String} url - * @param {Number} i - * @return {Route} - * @api private - */ - -Router.prototype.match = function(method, url, i, head){ - var req = { method: method, url: url }; - return this.matchRequest(req, i, head); -}; - -/** - * Route `method`, `path`, and one or more callbacks. - * - * @param {String} method - * @param {String} path - * @param {Function} callback... - * @return {Router} for chaining - * @api private - */ - -Router.prototype.route = function(method, path, callbacks){ - var method = method.toLowerCase() - , callbacks = utils.flatten([].slice.call(arguments, 2)); - - // ensure path was given - if (!path) throw new Error('Router#' + method + '() requires a path'); - - // ensure all callbacks are functions - callbacks.forEach(function(fn){ - if ('function' == typeof fn) return; - var type = {}.toString.call(fn); - var msg = '.' + method + '() requires callback functions but got a ' + type; - throw new Error(msg); - }); - - // create the route - debug('defined %s %s', method, path); - var route = new Route(method, path, callbacks, { - sensitive: this.caseSensitive, - strict: this.strict - }); - - // add it - (this.map[method] = this.map[method] || []).push(route); - return this; -}; - -Router.prototype.all = function(path) { - var self = this; - var args = [].slice.call(arguments); - methods.forEach(function(method){ - self.route.apply(self, [method].concat(args)); - }); - return this; -}; - -methods.forEach(function(method){ - Router.prototype[method] = function(path){ - var args = [method].concat([].slice.call(arguments)); - this.route.apply(this, args); - return this; - }; -}); diff --git a/node_modules/express/lib/router/route.js b/node_modules/express/lib/router/route.js deleted file mode 100644 index d7ec88d2e..000000000 --- a/node_modules/express/lib/router/route.js +++ /dev/null @@ -1,78 +0,0 @@ - -/** - * Module dependencies. - */ - -var utils = require('../utils'); - -/** - * Expose `Route`. - */ - -module.exports = Route; - -/** - * Initialize `Route` with the given HTTP `method`, `path`, - * and an array of `callbacks` and `options`. - * - * Options: - * - * - `sensitive` enable case-sensitive routes - * - `strict` enable strict matching for trailing slashes - * - * @param {String} method - * @param {String} path - * @param {Array} callbacks - * @param {Object} options. - * @api private - */ - -function Route(method, path, callbacks, options) { - options = options || {}; - this.path = path; - this.method = method; - this.callbacks = callbacks; - this.regexp = utils.pathRegexp(path - , this.keys = [] - , options.sensitive - , options.strict); -} - -/** - * Check if this route matches `path`, if so - * populate `.params`. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -Route.prototype.match = function(path){ - var keys = this.keys - , params = this.params = [] - , m = this.regexp.exec(path); - - if (!m) return false; - - for (var i = 1, len = m.length; i < len; ++i) { - var key = keys[i - 1]; - - try { - var val = 'string' == typeof m[i] - ? decodeURIComponent(m[i]) - : m[i]; - } catch(e) { - var err = new Error("Failed to decode param '" + m[i] + "'"); - err.status = 400; - throw err; - } - - if (key) { - params[key.name] = val; - } else { - params.push(val); - } - } - - return true; -}; diff --git a/node_modules/express/lib/utils.js b/node_modules/express/lib/utils.js deleted file mode 100644 index b30873a8a..000000000 --- a/node_modules/express/lib/utils.js +++ /dev/null @@ -1,314 +0,0 @@ - -/** - * Module dependencies. - */ - -var mime = require('connect').mime - , crc32 = require('buffer-crc32'); - -/** - * toString ref. - */ - -var toString = {}.toString; - -/** - * Return ETag for `body`. - * - * @param {String|Buffer} body - * @return {String} - * @api private - */ - -exports.etag = function(body){ - return '"' + crc32.signed(body) + '"'; -}; - -/** - * Make `locals()` bound to the given `obj`. - * - * This is used for `app.locals` and `res.locals`. - * - * @param {Object} obj - * @return {Function} - * @api private - */ - -exports.locals = function(){ - function locals(obj){ - for (var key in obj) locals[key] = obj[key]; - return obj; - }; - - return locals; -}; - -/** - * Check if `path` looks absolute. - * - * @param {String} path - * @return {Boolean} - * @api private - */ - -exports.isAbsolute = function(path){ - if ('/' == path[0]) return true; - if (':' == path[1] && '\\' == path[2]) return true; - if ('\\\\' == path.substring(0, 2)) return true; // Microsoft Azure absolute path -}; - -/** - * Flatten the given `arr`. - * - * @param {Array} arr - * @return {Array} - * @api private - */ - -exports.flatten = function(arr, ret){ - var ret = ret || [] - , len = arr.length; - for (var i = 0; i < len; ++i) { - if (Array.isArray(arr[i])) { - exports.flatten(arr[i], ret); - } else { - ret.push(arr[i]); - } - } - return ret; -}; - -/** - * Normalize the given `type`, for example "html" becomes "text/html". - * - * @param {String} type - * @return {Object} - * @api private - */ - -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; -}; - -/** - * Normalize `types`, for example "html" becomes "text/html". - * - * @param {Array} types - * @return {Array} - * @api private - */ - -exports.normalizeTypes = function(types){ - var ret = []; - - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); - } - - return ret; -}; - -/** - * Return the acceptable type in `types`, if any. - * - * @param {Array} types - * @param {String} str - * @return {String} - * @api private - */ - -exports.acceptsArray = function(types, str){ - // accept anything when Accept is not present - if (!str) return types[0]; - - // parse - var accepted = exports.parseAccept(str) - , normalized = exports.normalizeTypes(types) - , len = accepted.length; - - for (var i = 0; i < len; ++i) { - for (var j = 0, jlen = types.length; j < jlen; ++j) { - if (exports.accept(normalized[j], accepted[i])) { - return types[j]; - } - } - } -}; - -/** - * Check if `type(s)` are acceptable based on - * the given `str`. - * - * @param {String|Array} type(s) - * @param {String} str - * @return {Boolean|String} - * @api private - */ - -exports.accepts = function(type, str){ - if ('string' == typeof type) type = type.split(/ *, */); - return exports.acceptsArray(type, str); -}; - -/** - * Check if `type` array is acceptable for `other`. - * - * @param {Object} type - * @param {Object} other - * @return {Boolean} - * @api private - */ - -exports.accept = function(type, other){ - var t = type.value.split('/'); - return (t[0] == other.type || '*' == other.type) - && (t[1] == other.subtype || '*' == other.subtype) - && paramsEqual(type.params, other.params); -}; - -/** - * Check if accept params are equal. - * - * @param {Object} a - * @param {Object} b - * @return {Boolean} - * @api private - */ - -function paramsEqual(a, b){ - return !Object.keys(a).some(function(k) { - return a[k] != b[k]; - }); -} - -/** - * Parse accept `str`, returning - * an array objects containing - * `.type` and `.subtype` along - * with the values provided by - * `parseQuality()`. - * - * @param {Type} name - * @return {Type} - * @api private - */ - -exports.parseAccept = function(str){ - return exports - .parseParams(str) - .map(function(obj){ - var parts = obj.value.split('/'); - obj.type = parts[0]; - obj.subtype = parts[1]; - return obj; - }); -}; - -/** - * Parse quality `str`, returning an - * array of objects with `.value`, - * `.quality` and optional `.params` - * - * @param {String} str - * @return {Array} - * @api private - */ - -exports.parseParams = function(str){ - return str - .split(/ *, */) - .map(acceptParams) - .filter(function(obj){ - return obj.quality; - }) - .sort(function(a, b){ - if (a.quality === b.quality) { - return a.originalIndex - b.originalIndex; - } else { - return b.quality - a.quality; - } - }); -}; - -/** - * Parse accept params `str` returning an - * object with `.value`, `.quality` and `.params`. - * also includes `.originalIndex` for stable sorting - * - * @param {String} str - * @return {Object} - * @api private - */ - -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; - - for (var i = 1; i < parts.length; ++i) { - var pms = parts[i].split(/ *= */); - if ('q' == pms[0]) { - ret.quality = parseFloat(pms[1]); - } else { - ret.params[pms[0]] = pms[1]; - } - } - - return ret; -} - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html) { - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Normalize the given path string, - * returning a regular expression. - * - * An empty array should be passed, - * which will contain the placeholder - * key names. For example "/user/:id" will - * then contain ["id"]. - * - * @param {String|RegExp|Array} path - * @param {Array} keys - * @param {Boolean} sensitive - * @param {Boolean} strict - * @return {RegExp} - * @api private - */ - -exports.pathRegexp = function(path, keys, sensitive, strict) { - if (toString.call(path) == '[object RegExp]') return path; - if (Array.isArray(path)) path = '(' + path.join('|') + ')'; - path = path - .concat(strict ? '' : '/?') - .replace(/\/\(/g, '(?:/') - .replace(/(\/)?(\.)?:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g, function(_, slash, format, key, capture, optional, star){ - keys.push({ name: key, optional: !! optional }); - slash = slash || ''; - return '' - + (optional ? '' : slash) - + '(?:' - + (optional ? slash : '') - + (format || '') + (capture || (format && '([^/.]+?)' || '([^/]+?)')) + ')' - + (optional || '') - + (star ? '(/*)?' : ''); - }) - .replace(/([\/.])/g, '\\$1') - .replace(/\*/g, '(.*)'); - return new RegExp('^' + path + '$', sensitive ? '' : 'i'); -} diff --git a/node_modules/express/lib/view.js b/node_modules/express/lib/view.js deleted file mode 100644 index b9dc69e0e..000000000 --- a/node_modules/express/lib/view.js +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Module dependencies. - */ - -var path = require('path') - , fs = require('fs') - , utils = require('./utils') - , dirname = path.dirname - , basename = path.basename - , extname = path.extname - , exists = fs.existsSync || path.existsSync - , join = path.join; - -/** - * Expose `View`. - */ - -module.exports = View; - -/** - * Initialize a new `View` with the given `name`. - * - * Options: - * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup - * - * @param {String} name - * @param {Object} options - * @api private - */ - -function View(name, options) { - options = options || {}; - this.name = name; - this.root = options.root; - var engines = options.engines; - this.defaultEngine = options.defaultEngine; - var ext = this.ext = extname(name); - if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.'); - if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine); - this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express); - this.path = this.lookup(name); -} - -/** - * Lookup view by the given `path` - * - * @param {String} path - * @return {String} - * @api private - */ - -View.prototype.lookup = function(path){ - var ext = this.ext; - - // . - if (!utils.isAbsolute(path)) path = join(this.root, path); - if (exists(path)) return path; - - // /index. - path = join(dirname(path), basename(path, ext), 'index' + ext); - if (exists(path)) return path; -}; - -/** - * Render with the given `options` and callback `fn(err, str)`. - * - * @param {Object} options - * @param {Function} fn - * @api private - */ - -View.prototype.render = function(options, fn){ - this.engine(this.path, options, fn); -}; diff --git a/node_modules/express/node_modules/buffer-crc32/.npmignore b/node_modules/express/node_modules/buffer-crc32/.npmignore deleted file mode 100644 index b512c09d4..000000000 --- a/node_modules/express/node_modules/buffer-crc32/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules \ No newline at end of file diff --git a/node_modules/express/node_modules/buffer-crc32/.travis.yml b/node_modules/express/node_modules/buffer-crc32/.travis.yml deleted file mode 100644 index 7a902e8c8..000000000 --- a/node_modules/express/node_modules/buffer-crc32/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 -notifications: - email: - recipients: - - brianloveswords@gmail.com \ No newline at end of file diff --git a/node_modules/express/node_modules/buffer-crc32/README.md b/node_modules/express/node_modules/buffer-crc32/README.md deleted file mode 100644 index 0d9d8b835..000000000 --- a/node_modules/express/node_modules/buffer-crc32/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# buffer-crc32 - -[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32) - -crc32 that works with binary data and fancy character sets, outputs -buffer, signed or unsigned data and has tests. - -Derived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix - -# install -``` -npm install buffer-crc32 -``` - -# example -```js -var crc32 = require('buffer-crc32'); -// works with buffers -var buf = Buffer([0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00]) -crc32(buf) // -> - -// has convenience methods for getting signed or unsigned ints -crc32.signed(buf) // -> -1805997238 -crc32.unsigned(buf) // -> 2488970058 - -// will cast to buffer if given a string, so you can -// directly use foreign characters safely -crc32('自動販売機') // -> - -// and works in append mode too -var partialCrc = crc32('hey'); -var partialCrc = crc32(' ', partialCrc); -var partialCrc = crc32('sup', partialCrc); -var partialCrc = crc32(' ', partialCrc); -var finalCrc = crc32('bros', partialCrc); // -> -``` - -# tests -This was tested against the output of zlib's crc32 method. You can run -the tests with`npm test` (requires tap) - -# see also -https://github.com/alexgorbatchev/node-crc, `crc.buffer.crc32` also -supports buffer inputs and return unsigned ints (thanks @tjholowaychuk). - -# license -MIT/X11 diff --git a/node_modules/express/node_modules/buffer-crc32/index.js b/node_modules/express/node_modules/buffer-crc32/index.js deleted file mode 100644 index e29ce3ebc..000000000 --- a/node_modules/express/node_modules/buffer-crc32/index.js +++ /dev/null @@ -1,88 +0,0 @@ -var Buffer = require('buffer').Buffer; - -var CRC_TABLE = [ - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, - 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, - 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, - 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, - 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, - 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, - 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, - 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, - 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, - 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, - 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, - 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, - 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, - 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, - 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, - 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, - 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, - 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, - 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, - 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, - 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, - 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, - 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, - 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, - 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, - 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, - 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, - 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, - 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, - 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, - 0x2d02ef8d -]; - -function bufferizeInt(num) { - var tmp = Buffer(4); - tmp.writeInt32BE(num, 0); - return tmp; -} - -function _crc32(buf, previous) { - if (!Buffer.isBuffer(buf)) { - buf = Buffer(buf); - } - if (Buffer.isBuffer(previous)) { - previous = previous.readUInt32BE(0); - } - var crc = ~~previous ^ -1; - for (var n = 0; n < buf.length; n++) { - crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); - } - return (crc ^ -1); -} - -function crc32() { - return bufferizeInt(_crc32.apply(null, arguments)); -} -crc32.signed = function () { - return _crc32.apply(null, arguments); -}; -crc32.unsigned = function () { - return _crc32.apply(null, arguments) >>> 0; -}; - -module.exports = crc32; diff --git a/node_modules/express/node_modules/buffer-crc32/package.json b/node_modules/express/node_modules/buffer-crc32/package.json deleted file mode 100644 index ed9618bc8..000000000 --- a/node_modules/express/node_modules/buffer-crc32/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "author": { - "name": "Brian J. Brennan", - "email": "brianloveswords@gmail.com", - "url": "http://bjb.io" - }, - "name": "buffer-crc32", - "description": "A pure javascript CRC32 algorithm that plays nice with binary data", - "version": "0.2.1", - "contributors": [ - { - "name": "Vladimir Kuznetsov" - } - ], - "homepage": "https://github.com/brianloveswords/buffer-crc32", - "repository": { - "type": "git", - "url": "git://github.com/brianloveswords/buffer-crc32.git" - }, - "main": "index.js", - "scripts": { - "test": "./node_modules/.bin/tap tests/*.test.js" - }, - "dependencies": {}, - "devDependencies": { - "tap": "~0.2.5" - }, - "optionalDependencies": {}, - "engines": { - "node": "*" - }, - "readme": "# buffer-crc32\n\n[![Build Status](https://secure.travis-ci.org/brianloveswords/buffer-crc32.png?branch=master)](http://travis-ci.org/brianloveswords/buffer-crc32)\n\ncrc32 that works with binary data and fancy character sets, outputs\nbuffer, signed or unsigned data and has tests.\n\nDerived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix\n\n# install\n```\nnpm install buffer-crc32\n```\n\n# example\n```js\nvar crc32 = require('buffer-crc32');\n// works with buffers\nvar buf = Buffer([0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00])\ncrc32(buf) // -> \n\n// has convenience methods for getting signed or unsigned ints\ncrc32.signed(buf) // -> -1805997238\ncrc32.unsigned(buf) // -> 2488970058\n\n// will cast to buffer if given a string, so you can\n// directly use foreign characters safely\ncrc32('自動販売機') // -> \n\n// and works in append mode too\nvar partialCrc = crc32('hey');\nvar partialCrc = crc32(' ', partialCrc);\nvar partialCrc = crc32('sup', partialCrc);\nvar partialCrc = crc32(' ', partialCrc);\nvar finalCrc = crc32('bros', partialCrc); // -> \n```\n\n# tests\nThis was tested against the output of zlib's crc32 method. You can run\nthe tests with`npm test` (requires tap)\n\n# see also\nhttps://github.com/alexgorbatchev/node-crc, `crc.buffer.crc32` also\nsupports buffer inputs and return unsigned ints (thanks @tjholowaychuk).\n\n# license\nMIT/X11\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/brianloveswords/buffer-crc32/issues" - }, - "_id": "buffer-crc32@0.2.1", - "dist": { - "shasum": "69c3a8d64a2371a06465b1766786725de5896116" - }, - "_from": "buffer-crc32@0.2.1", - "_resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.1.tgz" -} diff --git a/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js b/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js deleted file mode 100644 index bb0f9efcc..000000000 --- a/node_modules/express/node_modules/buffer-crc32/tests/crc.test.js +++ /dev/null @@ -1,89 +0,0 @@ -var crc32 = require('..'); -var test = require('tap').test; - -test('simple crc32 is no problem', function (t) { - var input = Buffer('hey sup bros'); - var expected = Buffer([0x47, 0xfa, 0x55, 0x70]); - t.same(crc32(input), expected); - t.end(); -}); - -test('another simple one', function (t) { - var input = Buffer('IEND'); - var expected = Buffer([0xae, 0x42, 0x60, 0x82]); - t.same(crc32(input), expected); - t.end(); -}); - -test('slightly more complex', function (t) { - var input = Buffer([0x00, 0x00, 0x00]); - var expected = Buffer([0xff, 0x41, 0xd9, 0x12]); - t.same(crc32(input), expected); - t.end(); -}); - -test('complex crc32 gets calculated like a champ', function (t) { - var input = Buffer('शीर्षक'); - var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]); - t.same(crc32(input), expected); - t.end(); -}); - -test('casts to buffer if necessary', function (t) { - var input = 'शीर्षक'; - var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]); - t.same(crc32(input), expected); - t.end(); -}); - -test('can do signed', function (t) { - var input = 'ham sandwich'; - var expected = -1891873021; - t.same(crc32.signed(input), expected); - t.end(); -}); - -test('can do unsigned', function (t) { - var input = 'bear sandwich'; - var expected = 3711466352; - t.same(crc32.unsigned(input), expected); - t.end(); -}); - - -test('simple crc32 in append mode', function (t) { - var input = [Buffer('hey'), Buffer(' '), Buffer('sup'), Buffer(' '), Buffer('bros')]; - var expected = Buffer([0x47, 0xfa, 0x55, 0x70]); - for (var crc = 0, i = 0; i < input.length; i++) { - crc = crc32(input[i], crc); - } - t.same(crc, expected); - t.end(); -}); - - -test('can do signed in append mode', function (t) { - var input1 = 'ham'; - var input2 = ' '; - var input3 = 'sandwich'; - var expected = -1891873021; - - var crc = crc32.signed(input1); - crc = crc32.signed(input2, crc); - crc = crc32.signed(input3, crc); - - t.same(crc, expected); - t.end(); -}); - -test('can do unsigned in append mode', function (t) { - var input1 = 'bear san'; - var input2 = 'dwich'; - var expected = 3711466352; - - var crc = crc32.unsigned(input1); - crc = crc32.unsigned(input2, crc); - t.same(crc, expected); - t.end(); -}); - diff --git a/node_modules/express/node_modules/commander/History.md b/node_modules/express/node_modules/commander/History.md deleted file mode 100644 index ce046f6f6..000000000 --- a/node_modules/express/node_modules/commander/History.md +++ /dev/null @@ -1,174 +0,0 @@ - -1.3.2 / 2013-07-18 -================== - - * add support for sub-commands to co-exist with the original command - -1.3.1 / 2013-07-18 -================== - - * add quick .runningCommand hack so you can opt-out of other logic when running a sub command - -1.3.0 / 2013-07-09 -================== - - * add EACCES error handling - * fix sub-command --help - -1.2.0 / 2013-06-13 -================== - - * allow "-" hyphen as an option argument - * support for RegExp coercion - -1.1.1 / 2012-11-20 -================== - - * add more sub-command padding - * fix .usage() when args are present. Closes #106 - -1.1.0 / 2012-11-16 -================== - - * add git-style executable subcommand support. Closes #94 - -1.0.5 / 2012-10-09 -================== - - * fix `--name` clobbering. Closes #92 - * fix examples/help. Closes #89 - -1.0.4 / 2012-09-03 -================== - - * add `outputHelp()` method. - -1.0.3 / 2012-08-30 -================== - - * remove invalid .version() defaulting - -1.0.2 / 2012-08-24 -================== - - * add `--foo=bar` support [arv] - * fix password on node 0.8.8. Make backward compatible with 0.6 [focusaurus] - -1.0.1 / 2012-08-03 -================== - - * fix issue #56 - * fix tty.setRawMode(mode) was moved to tty.ReadStream#setRawMode() (i.e. process.stdin.setRawMode()) - -1.0.0 / 2012-07-05 -================== - - * add support for optional option descriptions - * add defaulting of `.version()` to package.json's version - -0.6.1 / 2012-06-01 -================== - - * Added: append (yes or no) on confirmation - * Added: allow node.js v0.7.x - -0.6.0 / 2012-04-10 -================== - - * Added `.prompt(obj, callback)` support. Closes #49 - * Added default support to .choose(). Closes #41 - * Fixed the choice example - -0.5.1 / 2011-12-20 -================== - - * Fixed `password()` for recent nodes. Closes #36 - -0.5.0 / 2011-12-04 -================== - - * Added sub-command option support [itay] - -0.4.3 / 2011-12-04 -================== - - * Fixed custom help ordering. Closes #32 - -0.4.2 / 2011-11-24 -================== - - * Added travis support - * Fixed: line-buffered input automatically trimmed. Closes #31 - -0.4.1 / 2011-11-18 -================== - - * Removed listening for "close" on --help - -0.4.0 / 2011-11-15 -================== - - * Added support for `--`. Closes #24 - -0.3.3 / 2011-11-14 -================== - - * Fixed: wait for close event when writing help info [Jerry Hamlet] - -0.3.2 / 2011-11-01 -================== - - * Fixed long flag definitions with values [felixge] - -0.3.1 / 2011-10-31 -================== - - * Changed `--version` short flag to `-V` from `-v` - * Changed `.version()` so it's configurable [felixge] - -0.3.0 / 2011-10-31 -================== - - * Added support for long flags only. Closes #18 - -0.2.1 / 2011-10-24 -================== - - * "node": ">= 0.4.x < 0.7.0". Closes #20 - -0.2.0 / 2011-09-26 -================== - - * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] - -0.1.0 / 2011-08-24 -================== - - * Added support for custom `--help` output - -0.0.5 / 2011-08-18 -================== - - * Changed: when the user enters nothing prompt for password again - * Fixed issue with passwords beginning with numbers [NuckChorris] - -0.0.4 / 2011-08-15 -================== - - * Fixed `Commander#args` - -0.0.3 / 2011-08-15 -================== - - * Added default option value support - -0.0.2 / 2011-08-15 -================== - - * Added mask support to `Command#password(str[, mask], fn)` - * Added `Command#password(str, fn)` - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/node_modules/commander/Readme.md b/node_modules/express/node_modules/commander/Readme.md deleted file mode 100644 index ed0aeb2cb..000000000 --- a/node_modules/express/node_modules/commander/Readme.md +++ /dev/null @@ -1,276 +0,0 @@ -# Commander.js - - The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). - - [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js) - -## Installation - - $ npm install commander - -## Option parsing - - Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander'); - -program - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineapple'); -if (program.bbq) console.log(' - bbq'); -console.log(' - %s cheese', program.cheese); -``` - - Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. - -## Automated --help - - The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: - -``` - $ ./examples/pizza --help - - Usage: pizza [options] - - Options: - - -V, --version output the version number - -p, --peppers Add peppers - -P, --pineapple Add pineapple - -b, --bbq Add bbq sauce - -c, --cheese Add the specified type of cheese [marble] - -h, --help output usage information - -``` - -## Coercion - -```js -function range(val) { - return val.split('..').map(Number); -} - -function list(val) { - return val.split(','); -} - -program - .version('0.0.1') - .usage('[options] ') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .parse(process.argv); - -console.log(' int: %j', program.integer); -console.log(' float: %j', program.float); -console.log(' optional: %j', program.optional); -program.range = program.range || []; -console.log(' range: %j..%j', program.range[0], program.range[1]); -console.log(' list: %j', program.list); -console.log(' args: %j', program.args); -``` - -## Custom help - - You can display arbitrary `-h, --help` information - by listening for "--help". Commander will automatically - exit once you are done so that the remainder of your program - does not execute causing undesired behaviours, for example - in the following executable "stuff" will not output when - `--help` is used. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('../'); - -function list(val) { - return val.split(',').map(Number); -} - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program.parse(process.argv); - -console.log('stuff'); -``` - -yielding the following help output: - -``` - -Usage: custom-help [options] - -Options: - - -h, --help output usage information - -V, --version output the version number - -f, --foo enable some foo - -b, --bar enable some bar - -B, --baz enable some baz - -Examples: - - $ custom-help --help - $ custom-help -h - -``` - -## .prompt(msg, fn) - - Single-line prompt: - -```js -program.prompt('name: ', function(name){ - console.log('hi %s', name); -}); -``` - - Multi-line prompt: - -```js -program.prompt('description:', function(name){ - console.log('hi %s', name); -}); -``` - - Coercion: - -```js -program.prompt('Age: ', Number, function(age){ - console.log('age: %j', age); -}); -``` - -```js -program.prompt('Birthdate: ', Date, function(date){ - console.log('date: %s', date); -}); -``` - -```js -program.prompt('Email: ', /^.+@.+\..+$/, function(email){ - console.log('email: %j', email); -}); -``` - -## .password(msg[, mask], fn) - -Prompt for password without echoing: - -```js -program.password('Password: ', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -Prompt for password with mask char "*": - -```js -program.password('Password: ', '*', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -## .confirm(msg, fn) - - Confirm with the given `msg`: - -```js -program.confirm('continue? ', function(ok){ - console.log(' got %j', ok); -}); -``` - -## .choose(list, fn) - - Let the user choose from a `list`: - -```js -var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - -console.log('Choose the coolest pet:'); -program.choose(list, function(i){ - console.log('you chose %d "%s"', i, list[i]); -}); -``` - -## .outputHelp() - - Output help information without exiting. - -## .help() - - Output help information and exit immediately. - -## Links - - - [API documentation](http://visionmedia.github.com/commander.js/) - - [ascii tables](https://github.com/LearnBoost/cli-table) - - [progress bars](https://github.com/visionmedia/node-progress) - - [more progress bars](https://github.com/substack/node-multimeter) - - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/commander/index.js b/node_modules/express/node_modules/commander/index.js deleted file mode 100644 index d9634e341..000000000 --- a/node_modules/express/node_modules/commander/index.js +++ /dev/null @@ -1,1160 +0,0 @@ -/*! - * commander - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , spawn = require('child_process').spawn - , keypress = require('keypress') - , fs = require('fs') - , exists = fs.existsSync - , path = require('path') - , tty = require('tty') - , dirname = path.dirname - , basename = path.basename; - -/** - * Expose the root command. - */ - -exports = module.exports = new Command; - -/** - * Expose `Command`. - */ - -exports.Command = Command; - -/** - * Expose `Option`. - */ - -exports.Option = Option; - -/** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {String} flags - * @param {String} description - * @api public - */ - -function Option(flags, description) { - this.flags = flags; - this.required = ~flags.indexOf('<'); - this.optional = ~flags.indexOf('['); - this.bool = !~flags.indexOf('-no-'); - flags = flags.split(/[ ,|]+/); - if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); - this.long = flags.shift(); - this.description = description || ''; -} - -/** - * Return option name. - * - * @return {String} - * @api private - */ - -Option.prototype.name = function(){ - return this.long - .replace('--', '') - .replace('no-', ''); -}; - -/** - * Check if `arg` matches the short or long flag. - * - * @param {String} arg - * @return {Boolean} - * @api private - */ - -Option.prototype.is = function(arg){ - return arg == this.short - || arg == this.long; -}; - -/** - * Initialize a new `Command`. - * - * @param {String} name - * @api public - */ - -function Command(name) { - this.commands = []; - this.options = []; - this._execs = []; - this._args = []; - this._name = name; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Command.prototype.__proto__ = EventEmitter.prototype; - -/** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * Examples: - * - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function(){ - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd){ - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env){ - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {String} name - * @param {String} [desc] - * @return {Command} the new command - * @api public - */ - -Command.prototype.command = function(name, desc){ - var args = name.split(/ +/); - var cmd = new Command(args.shift()); - if (desc) cmd.description(desc); - if (desc) this.executables = true; - if (desc) this._execs[cmd._name] = true; - this.commands.push(cmd); - cmd.parseExpectedArgs(args); - cmd.parent = this; - if (desc) return this; - return cmd; -}; - -/** - * Add an implicit `help [cmd]` subcommand - * which invokes `--help` for the given command. - * - * @api private - */ - -Command.prototype.addImplicitHelpCommand = function() { - this.command('help [cmd]', 'display help for [cmd]'); -}; - -/** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parseExpectedArgs = function(args){ - if (!args.length) return; - var self = this; - args.forEach(function(arg){ - switch (arg[0]) { - case '<': - self._args.push({ required: true, name: arg.slice(1, -1) }); - break; - case '[': - self._args.push({ required: false, name: arg.slice(1, -1) }); - break; - } - }); - return this; -}; - -/** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function(){ - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} for chaining - * @api public - */ - -Command.prototype.action = function(fn){ - var self = this; - this.parent.on(this._name, function(args, unknown){ - // Parse any so-far unknown options - unknown = unknown || []; - var parsed = self.parseOptions(unknown); - - // Output help if necessary - outputHelpIfNecessary(self, parsed.unknown); - - // If there are still any unknown options, then we simply - // die, unless someone asked for help, in which case we give it - // to them, and then we die. - if (parsed.unknown.length > 0) { - self.unknownOption(parsed.unknown[0]); - } - - // Leftover arguments need to be pushed back. Fixes issue #56 - if (parsed.args.length) args = parsed.args.concat(args); - - self._args.forEach(function(arg, i){ - if (arg.required && null == args[i]) { - self.missingArgument(arg.name); - } - }); - - // Always append ourselves to the end of the arguments, - // to make sure we match the number of arguments the user - // expects - if (self._args.length) { - args[self._args.length] = self; - } else { - args.push(self); - } - - fn.apply(this, args); - }); - return this; -}; - -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to false - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => true - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {String} flags - * @param {String} description - * @param {Function|Mixed} fn or default - * @param {Mixed} defaultValue - * @return {Command} for chaining - * @api public - */ - -Command.prototype.option = function(flags, description, fn, defaultValue){ - var self = this - , option = new Option(flags, description) - , oname = option.name() - , name = camelcase(oname); - - // default as 3rd arg - if ('function' != typeof fn) defaultValue = fn, fn = null; - - // preassign default value only for --no-*, [optional], or - if (false == option.bool || option.optional || option.required) { - // when --no-* we make sure default is true - if (false == option.bool) defaultValue = true; - // preassign only if we have a default - if (undefined !== defaultValue) self[name] = defaultValue; - } - - // register the option - this.options.push(option); - - // when it's passed assign the value - // and conditionally invoke the callback - this.on(oname, function(val){ - // coercion - if (null != val && fn) val = fn(val); - - // unassigned or bool - if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { - // if no value, bool true, and we have a default, then use it! - if (null == val) { - self[name] = option.bool - ? defaultValue || true - : false; - } else { - self[name] = val; - } - } else if (null !== val) { - // reassign - self[name] = val; - } - }); - - return this; -}; - -/** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {Array} argv - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parse = function(argv){ - // implicit help - if (this.executables) this.addImplicitHelpCommand(); - - // store raw args - this.rawArgs = argv; - - // guess name - this._name = this._name || basename(argv[1]); - - // process argv - var parsed = this.parseOptions(this.normalize(argv.slice(2))); - var args = this.args = parsed.args; - - var result = this.parseArgs(this.args, parsed.unknown); - - // executable sub-commands - var name = result.args[0]; - if (this._execs[name]) return this.executeSubCommand(argv, args, parsed.unknown); - - return result; -}; - -/** - * Execute a sub-command executable. - * - * @param {Array} argv - * @param {Array} args - * @param {Array} unknown - * @api private - */ - -Command.prototype.executeSubCommand = function(argv, args, unknown) { - args = args.concat(unknown); - - if (!args.length) this.help(); - if ('help' == args[0] && 1 == args.length) this.help(); - - // --help - if ('help' == args[0]) { - args[0] = args[1]; - args[1] = '--help'; - } - - // executable - var dir = dirname(argv[1]); - var bin = basename(argv[1]) + '-' + args[0]; - - // check for ./ first - var local = path.join(dir, bin); - - // run it - args = args.slice(1); - var proc = spawn(local, args, { stdio: 'inherit', customFds: [0, 1, 2] }); - proc.on('error', function(err){ - if (err.code == "ENOENT") { - console.error('\n %s(1) does not exist, try --help\n', bin); - } else if (err.code == "EACCES") { - console.error('\n %s(1) not executable. try chmod or run with root\n', bin); - } - }); - - this.runningCommand = proc; -}; - -/** - * Normalize `args`, splitting joined short flags. For example - * the arg "-abc" is equivalent to "-a -b -c". - * This also normalizes equal sign and splits "--abc=def" into "--abc def". - * - * @param {Array} args - * @return {Array} - * @api private - */ - -Command.prototype.normalize = function(args){ - var ret = [] - , arg - , index; - - for (var i = 0, len = args.length; i < len; ++i) { - arg = args[i]; - if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { - arg.slice(1).split('').forEach(function(c){ - ret.push('-' + c); - }); - } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { - ret.push(arg.slice(0, index), arg.slice(index + 1)); - } else { - ret.push(arg); - } - } - - return ret; -}; - -/** - * Parse command `args`. - * - * When listener(s) are available those - * callbacks are invoked, otherwise the "*" - * event is emitted and those actions are invoked. - * - * @param {Array} args - * @return {Command} for chaining - * @api private - */ - -Command.prototype.parseArgs = function(args, unknown){ - var cmds = this.commands - , len = cmds.length - , name; - - if (args.length) { - name = args[0]; - if (this.listeners(name).length) { - this.emit(args.shift(), args, unknown); - } else { - this.emit('*', args); - } - } else { - outputHelpIfNecessary(this, unknown); - - // If there were no args and we have unknown options, - // then they are extraneous and we need to error. - if (unknown.length > 0) { - this.unknownOption(unknown[0]); - } - } - - return this; -}; - -/** - * Return an option matching `arg` if any. - * - * @param {String} arg - * @return {Option} - * @api private - */ - -Command.prototype.optionFor = function(arg){ - for (var i = 0, len = this.options.length; i < len; ++i) { - if (this.options[i].is(arg)) { - return this.options[i]; - } - } -}; - -/** - * Parse options from `argv` returning `argv` - * void of these options. - * - * @param {Array} argv - * @return {Array} - * @api public - */ - -Command.prototype.parseOptions = function(argv){ - var args = [] - , len = argv.length - , literal - , option - , arg; - - var unknownOptions = []; - - // parse options - for (var i = 0; i < len; ++i) { - arg = argv[i]; - - // literal args after -- - if ('--' == arg) { - literal = true; - continue; - } - - if (literal) { - args.push(arg); - continue; - } - - // find matching Option - option = this.optionFor(arg); - - // option is defined - if (option) { - // requires arg - if (option.required) { - arg = argv[++i]; - if (null == arg) return this.optionMissingArgument(option); - if ('-' == arg[0] && '-' != arg) return this.optionMissingArgument(option, arg); - this.emit(option.name(), arg); - // optional arg - } else if (option.optional) { - arg = argv[i+1]; - if (null == arg || ('-' == arg[0] && '-' != arg)) { - arg = null; - } else { - ++i; - } - this.emit(option.name(), arg); - // bool - } else { - this.emit(option.name()); - } - continue; - } - - // looks like an option - if (arg.length > 1 && '-' == arg[0]) { - unknownOptions.push(arg); - - // If the next argument looks like it might be - // an argument for this option, we pass it on. - // If it isn't, then it'll simply be ignored - if (argv[i+1] && '-' != argv[i+1][0]) { - unknownOptions.push(argv[++i]); - } - continue; - } - - // arg - args.push(arg); - } - - return { args: args, unknown: unknownOptions }; -}; - -/** - * Argument `name` is missing. - * - * @param {String} name - * @api private - */ - -Command.prototype.missingArgument = function(name){ - console.error(); - console.error(" error: missing required argument `%s'", name); - console.error(); - process.exit(1); -}; - -/** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {String} option - * @param {String} flag - * @api private - */ - -Command.prototype.optionMissingArgument = function(option, flag){ - console.error(); - if (flag) { - console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); - } else { - console.error(" error: option `%s' argument missing", option.flags); - } - console.error(); - process.exit(1); -}; - -/** - * Unknown option `flag`. - * - * @param {String} flag - * @api private - */ - -Command.prototype.unknownOption = function(flag){ - console.error(); - console.error(" error: unknown option `%s'", flag); - console.error(); - process.exit(1); -}; - - -/** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {String} str - * @param {String} flags - * @return {Command} for chaining - * @api public - */ - -Command.prototype.version = function(str, flags){ - if (0 == arguments.length) return this._version; - this._version = str; - flags = flags || '-V, --version'; - this.option(flags, 'output the version number'); - this.on('version', function(){ - console.log(str); - process.exit(0); - }); - return this; -}; - -/** - * Set the description `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.description = function(str){ - if (0 == arguments.length) return this._description; - this._description = str; - return this; -}; - -/** - * Set / get the command usage `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.usage = function(str){ - var args = this._args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }); - - var usage = '[options' - + (this.commands.length ? '] [command' : '') - + ']' - + (this._args.length ? ' ' + args : ''); - - if (0 == arguments.length) return this._usage || usage; - this._usage = str; - - return this; -}; - -/** - * Return the largest option length. - * - * @return {Number} - * @api private - */ - -Command.prototype.largestOptionLength = function(){ - return this.options.reduce(function(max, option){ - return Math.max(max, option.flags.length); - }, 0); -}; - -/** - * Return help for options. - * - * @return {String} - * @api private - */ - -Command.prototype.optionHelp = function(){ - var width = this.largestOptionLength(); - - // Prepend the help information - return [pad('-h, --help', width) + ' ' + 'output usage information'] - .concat(this.options.map(function(option){ - return pad(option.flags, width) - + ' ' + option.description; - })) - .join('\n'); -}; - -/** - * Return command help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.commandHelp = function(){ - if (!this.commands.length) return ''; - return [ - '' - , ' Commands:' - , '' - , this.commands.map(function(cmd){ - var args = cmd._args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }).join(' '); - - return pad(cmd._name - + (cmd.options.length - ? ' [options]' - : '') + ' ' + args, 22) - + (cmd.description() - ? ' ' + cmd.description() - : ''); - }).join('\n').replace(/^/gm, ' ') - , '' - ].join('\n'); -}; - -/** - * Return program help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.helpInformation = function(){ - return [ - '' - , ' Usage: ' + this._name + ' ' + this.usage() - , '' + this.commandHelp() - , ' Options:' - , '' - , '' + this.optionHelp().replace(/^/gm, ' ') - , '' - , '' - ].join('\n'); -}; - -/** - * Prompt for a `Number`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForNumber = function(str, fn){ - var self = this; - this.promptSingleLine(str, function parseNumber(val){ - val = Number(val); - if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber); - fn(val); - }); -}; - -/** - * Prompt for a `Date`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForDate = function(str, fn){ - var self = this; - this.promptSingleLine(str, function parseDate(val){ - val = new Date(val); - if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate); - fn(val); - }); -}; - - -/** - * Prompt for a `Regular Expression`. - * - * @param {String} str - * @param {Object} pattern regular expression object to test - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForRegexp = function(str, pattern, fn){ - var self = this; - this.promptSingleLine(str, function parseRegexp(val){ - if(!pattern.test(val)) return self.promptSingleLine(str + '(regular expression mismatch) ', parseRegexp); - fn(val); - }); -}; - - -/** - * Single-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptSingleLine = function(str, fn){ - // determine if the 2nd argument is a regular expression - if (arguments[1].global !== undefined && arguments[1].multiline !== undefined) { - return this.promptForRegexp(str, arguments[1], arguments[2]); - } else if ('function' == typeof arguments[2]) { - return this['promptFor' + (fn.name || fn)](str, arguments[2]); - } - - process.stdout.write(str); - process.stdin.setEncoding('utf8'); - process.stdin.once('data', function(val){ - fn(val.trim()); - }).resume(); -}; - -/** - * Multi-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptMultiLine = function(str, fn){ - var buf = []; - console.log(str); - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(val){ - if ('\n' == val || '\r\n' == val) { - process.stdin.removeAllListeners('data'); - fn(buf.join('\n')); - } else { - buf.push(val.trimRight()); - } - }).resume(); -}; - -/** - * Prompt `str` and callback `fn(val)` - * - * Commander supports single-line and multi-line prompts. - * To issue a single-line prompt simply add white-space - * to the end of `str`, something like "name: ", whereas - * for a multi-line prompt omit this "description:". - * - * - * Examples: - * - * program.prompt('Username: ', function(name){ - * console.log('hi %s', name); - * }); - * - * program.prompt('Description:', function(desc){ - * console.log('description was "%s"', desc.trim()); - * }); - * - * @param {String|Object} str - * @param {Function} fn - * @api public - */ - -Command.prototype.prompt = function(str, fn){ - var self = this; - if ('string' == typeof str) { - if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); - this.promptMultiLine(str, fn); - } else { - var keys = Object.keys(str) - , obj = {}; - - function next() { - var key = keys.shift() - , label = str[key]; - - if (!key) return fn(obj); - self.prompt(label, function(val){ - obj[key] = val; - next(); - }); - } - - next(); - } -}; - -/** - * Prompt for password with `str`, `mask` char and callback `fn(val)`. - * - * The mask string defaults to '', aka no output is - * written while typing, you may want to use "*" etc. - * - * Examples: - * - * program.password('Password: ', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * program.password('Password: ', '*', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {String} mask - * @param {Function} fn - * @api public - */ - -Command.prototype.password = function(str, mask, fn){ - var self = this - , buf = ''; - - // default mask - if ('function' == typeof mask) { - fn = mask; - mask = ''; - } - - keypress(process.stdin); - - function setRawMode(mode) { - if (process.stdin.setRawMode) { - process.stdin.setRawMode(mode); - } else { - tty.setRawMode(mode); - } - }; - setRawMode(true); - process.stdout.write(str); - - // keypress - process.stdin.on('keypress', function(c, key){ - if (key && 'enter' == key.name) { - console.log(); - process.stdin.pause(); - process.stdin.removeAllListeners('keypress'); - setRawMode(false); - if (!buf.trim().length) return self.password(str, mask, fn); - fn(buf); - return; - } - - if (key && key.ctrl && 'c' == key.name) { - console.log('%s', buf); - process.exit(); - } - - process.stdout.write(mask); - buf += c; - }).resume(); -}; - -/** - * Confirmation prompt with `str` and callback `fn(bool)` - * - * Examples: - * - * program.confirm('continue? ', function(ok){ - * console.log(' got %j', ok); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {Function} fn - * @api public - */ - - -Command.prototype.confirm = function(str, fn, verbose){ - var self = this; - this.prompt(str, function(ok){ - if (!ok.trim()) { - if (!verbose) str += '(yes or no) '; - return self.confirm(str, fn, true); - } - fn(parseBool(ok)); - }); -}; - -/** - * Choice prompt with `list` of items and callback `fn(index, item)` - * - * Examples: - * - * var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - * - * console.log('Choose the coolest pet:'); - * program.choose(list, function(i){ - * console.log('you chose %d "%s"', i, list[i]); - * process.stdin.destroy(); - * }); - * - * @param {Array} list - * @param {Number|Function} index or fn - * @param {Function} fn - * @api public - */ - -Command.prototype.choose = function(list, index, fn){ - var self = this - , hasDefault = 'number' == typeof index; - - if (!hasDefault) { - fn = index; - index = null; - } - - list.forEach(function(item, i){ - if (hasDefault && i == index) { - console.log('* %d) %s', i + 1, item); - } else { - console.log(' %d) %s', i + 1, item); - } - }); - - function again() { - self.prompt(' : ', function(val){ - val = parseInt(val, 10) - 1; - if (hasDefault && isNaN(val)) val = index; - - if (null == list[val]) { - again(); - } else { - fn(val, list[val]); - } - }); - } - - again(); -}; - - -/** - * Output help information for this command - * - * @api public - */ - -Command.prototype.outputHelp = function(){ - process.stdout.write(this.helpInformation()); - this.emit('--help'); -}; - -/** - * Output help information and exit. - * - * @api public - */ - -Command.prototype.help = function(){ - this.outputHelp(); - process.exit(); -}; - -/** - * Camel-case the given `flag` - * - * @param {String} flag - * @return {String} - * @api private - */ - -function camelcase(flag) { - return flag.split('-').reduce(function(str, word){ - return str + word[0].toUpperCase() + word.slice(1); - }); -} - -/** - * Parse a boolean `str`. - * - * @param {String} str - * @return {Boolean} - * @api private - */ - -function parseBool(str) { - return /^y|yes|ok|true$/i.test(str); -} - -/** - * Pad `str` to `width`. - * - * @param {String} str - * @param {Number} width - * @return {String} - * @api private - */ - -function pad(str, width) { - var len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} - -/** - * Output help information if necessary - * - * @param {Command} command to output help for - * @param {Array} array of options to search for -h or --help - * @api private - */ - -function outputHelpIfNecessary(cmd, options) { - options = options || []; - for (var i = 0; i < options.length; i++) { - if (options[i] == '--help' || options[i] == '-h') { - cmd.outputHelp(); - process.exit(0); - } - } -} diff --git a/node_modules/express/node_modules/commander/node_modules/keypress/README.md b/node_modules/express/node_modules/commander/node_modules/keypress/README.md deleted file mode 100644 index a768e8f59..000000000 --- a/node_modules/express/node_modules/commander/node_modules/keypress/README.md +++ /dev/null @@ -1,101 +0,0 @@ -keypress -======== -### Make any Node ReadableStream emit "keypress" events - - -Previous to Node `v0.8.x`, there was an undocumented `"keypress"` event that -`process.stdin` would emit when it was a TTY. Some people discovered this hidden -gem, and started using it in their own code. - -Now in Node `v0.8.x`, this `"keypress"` event does not get emitted by default, -but rather only when it is being used in conjuction with the `readline` (or by -extension, the `repl`) module. - -This module is the exact logic from the node `v0.8.x` releases ripped out into its -own module. - -__Bonus:__ Now with mouse support! - -Installation ------------- - -Install with `npm`: - -``` bash -$ npm install keypress -``` - -Or add it to the `"dependencies"` section of your _package.json_ file. - - -Example -------- - -#### Listening for "keypress" events - -``` js -var keypress = require('keypress'); - -// make `process.stdin` begin emitting "keypress" events -keypress(process.stdin); - -// listen for the "keypress" event -process.stdin.on('keypress', function (ch, key) { - console.log('got "keypress"', key); - if (key && key.ctrl && key.name == 'c') { - process.stdin.pause(); - } -}); - -process.stdin.setRawMode(true); -process.stdin.resume(); -``` - -#### Listening for "mousepress" events - -``` js -var keypress = require('keypress'); - -// make `process.stdin` begin emitting "mousepress" (and "keypress") events -keypress(process.stdin); - -// you must enable the mouse events before they will begin firing -keypress.enableMouse(process.stdout); - -process.stdin.on('mousepress', function (info) { - console.log('got "mousepress" event at %d x %d', info.x, info.y); -}); - -process.on('exit', function () { - // disable mouse on exit, so that the state - // is back to normal for the terminal - keypress.disableMouse(process.stdout); -}); -``` - - -License -------- - -(The MIT License) - -Copyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/commander/node_modules/keypress/index.js b/node_modules/express/node_modules/commander/node_modules/keypress/index.js deleted file mode 100644 index c2ba488ba..000000000 --- a/node_modules/express/node_modules/commander/node_modules/keypress/index.js +++ /dev/null @@ -1,346 +0,0 @@ - -/** - * This module offers the internal "keypress" functionality from node-core's - * `readline` module, for your own programs and modules to use. - * - * Usage: - * - * require('keypress')(process.stdin); - * - * process.stdin.on('keypress', function (ch, key) { - * console.log(ch, key); - * if (key.ctrl && key.name == 'c') { - * process.stdin.pause(); - * } - * }); - * proces.stdin.resume(); - */ -var exports = module.exports = keypress; - -exports.enableMouse = function (stream) { - stream.write('\x1b' +'[?1000h') -} - -exports.disableMouse = function (stream) { - stream.write('\x1b' +'[?1000l') -} - - -/** - * accepts a readable Stream instance and makes it emit "keypress" events - */ - -function keypress(stream) { - if (isEmittingKeypress(stream)) return; - stream._emitKeypress = true; - - function onData(b) { - if (stream.listeners('keypress').length > 0) { - emitKey(stream, b); - } else { - // Nobody's watching anyway - stream.removeListener('data', onData); - stream.on('newListener', onNewListener); - } - } - - function onNewListener(event) { - if (event == 'keypress') { - stream.on('data', onData); - stream.removeListener('newListener', onNewListener); - } - } - - if (stream.listeners('keypress').length > 0) { - stream.on('data', onData); - } else { - stream.on('newListener', onNewListener); - } -} - -/** - * Returns `true` if the stream is already emitting "keypress" events. - * `false` otherwise. - */ - -function isEmittingKeypress(stream) { - var rtn = stream._emitKeypress; - if (!rtn) { - // hack: check for the v0.6.x "data" event - stream.listeners('data').forEach(function (l) { - if (l.name == 'onData' && /emitKey/.test(l.toString())) { - rtn = true; - stream._emitKeypress = true; - } - }); - } - if (!rtn) { - // hack: check for the v0.6.x "newListener" event - stream.listeners('newListener').forEach(function (l) { - if (l.name == 'onNewListener' && /keypress/.test(l.toString())) { - rtn = true; - stream._emitKeypress = true; - } - }); - } - return rtn; -} - - -/* - Some patterns seen in terminal key escape codes, derived from combos seen - at http://www.midnight-commander.org/browser/lib/tty/key.c - - ESC letter - ESC [ letter - ESC [ modifier letter - ESC [ 1 ; modifier letter - ESC [ num char - ESC [ num ; modifier char - ESC O letter - ESC O modifier letter - ESC O 1 ; modifier letter - ESC N letter - ESC [ [ num ; modifier char - ESC [ [ 1 ; modifier letter - ESC ESC [ num char - ESC ESC O letter - - - char is usually ~ but $ and ^ also happen with rxvt - - modifier is 1 + - (shift * 1) + - (left_alt * 2) + - (ctrl * 4) + - (right_alt * 8) - - two leading ESCs apparently mean the same as one leading ESC -*/ - -// Regexes used for ansi escape code splitting -var metaKeyCodeRe = /^(?:\x1b)([a-zA-Z0-9])$/; -var functionKeyCodeRe = - /^(?:\x1b+)(O|N|\[|\[\[)(?:(\d+)(?:;(\d+))?([~^$])|(?:1;)?(\d+)?([a-zA-Z]))/; - -function emitKey(stream, s) { - var ch, - key = { - name: undefined, - ctrl: false, - meta: false, - shift: false - }, - parts; - - if (Buffer.isBuffer(s)) { - if (s[0] > 127 && s[1] === undefined) { - s[0] -= 128; - s = '\x1b' + s.toString(stream.encoding || 'utf-8'); - } else { - s = s.toString(stream.encoding || 'utf-8'); - } - } - - key.sequence = s; - - if (s === '\r' || s === '\n') { - // enter - key.name = 'enter'; - - } else if (s === '\t') { - // tab - key.name = 'tab'; - - } else if (s === '\b' || s === '\x7f' || - s === '\x1b\x7f' || s === '\x1b\b') { - // backspace or ctrl+h - key.name = 'backspace'; - key.meta = (s.charAt(0) === '\x1b'); - - } else if (s === '\x1b' || s === '\x1b\x1b') { - // escape key - key.name = 'escape'; - key.meta = (s.length === 2); - - } else if (s === ' ' || s === '\x1b ') { - key.name = 'space'; - key.meta = (s.length === 2); - - } else if (s <= '\x1a') { - // ctrl+letter - key.name = String.fromCharCode(s.charCodeAt(0) + 'a'.charCodeAt(0) - 1); - key.ctrl = true; - - } else if (s.length === 1 && s >= 'a' && s <= 'z') { - // lowercase letter - key.name = s; - - } else if (s.length === 1 && s >= 'A' && s <= 'Z') { - // shift+letter - key.name = s.toLowerCase(); - key.shift = true; - - } else if (parts = metaKeyCodeRe.exec(s)) { - // meta+character key - key.name = parts[1].toLowerCase(); - key.meta = true; - key.shift = /^[A-Z]$/.test(parts[1]); - - } else if (parts = functionKeyCodeRe.exec(s)) { - // ansi escape sequence - - // reassemble the key code leaving out leading \x1b's, - // the modifier key bitflag and any meaningless "1;" sequence - var code = (parts[1] || '') + (parts[2] || '') + - (parts[4] || '') + (parts[6] || ''), - modifier = (parts[3] || parts[5] || 1) - 1; - - // Parse the key modifier - key.ctrl = !!(modifier & 4); - key.meta = !!(modifier & 10); - key.shift = !!(modifier & 1); - key.code = code; - - // Parse the key itself - switch (code) { - /* xterm/gnome ESC O letter */ - case 'OP': key.name = 'f1'; break; - case 'OQ': key.name = 'f2'; break; - case 'OR': key.name = 'f3'; break; - case 'OS': key.name = 'f4'; break; - - /* xterm/rxvt ESC [ number ~ */ - case '[11~': key.name = 'f1'; break; - case '[12~': key.name = 'f2'; break; - case '[13~': key.name = 'f3'; break; - case '[14~': key.name = 'f4'; break; - - /* from Cygwin and used in libuv */ - case '[[A': key.name = 'f1'; break; - case '[[B': key.name = 'f2'; break; - case '[[C': key.name = 'f3'; break; - case '[[D': key.name = 'f4'; break; - case '[[E': key.name = 'f5'; break; - - /* common */ - case '[15~': key.name = 'f5'; break; - case '[17~': key.name = 'f6'; break; - case '[18~': key.name = 'f7'; break; - case '[19~': key.name = 'f8'; break; - case '[20~': key.name = 'f9'; break; - case '[21~': key.name = 'f10'; break; - case '[23~': key.name = 'f11'; break; - case '[24~': key.name = 'f12'; break; - - /* xterm ESC [ letter */ - case '[A': key.name = 'up'; break; - case '[B': key.name = 'down'; break; - case '[C': key.name = 'right'; break; - case '[D': key.name = 'left'; break; - case '[E': key.name = 'clear'; break; - case '[F': key.name = 'end'; break; - case '[H': key.name = 'home'; break; - - /* xterm/gnome ESC O letter */ - case 'OA': key.name = 'up'; break; - case 'OB': key.name = 'down'; break; - case 'OC': key.name = 'right'; break; - case 'OD': key.name = 'left'; break; - case 'OE': key.name = 'clear'; break; - case 'OF': key.name = 'end'; break; - case 'OH': key.name = 'home'; break; - - /* xterm/rxvt ESC [ number ~ */ - case '[1~': key.name = 'home'; break; - case '[2~': key.name = 'insert'; break; - case '[3~': key.name = 'delete'; break; - case '[4~': key.name = 'end'; break; - case '[5~': key.name = 'pageup'; break; - case '[6~': key.name = 'pagedown'; break; - - /* putty */ - case '[[5~': key.name = 'pageup'; break; - case '[[6~': key.name = 'pagedown'; break; - - /* rxvt */ - case '[7~': key.name = 'home'; break; - case '[8~': key.name = 'end'; break; - - /* rxvt keys with modifiers */ - case '[a': key.name = 'up'; key.shift = true; break; - case '[b': key.name = 'down'; key.shift = true; break; - case '[c': key.name = 'right'; key.shift = true; break; - case '[d': key.name = 'left'; key.shift = true; break; - case '[e': key.name = 'clear'; key.shift = true; break; - - case '[2$': key.name = 'insert'; key.shift = true; break; - case '[3$': key.name = 'delete'; key.shift = true; break; - case '[5$': key.name = 'pageup'; key.shift = true; break; - case '[6$': key.name = 'pagedown'; key.shift = true; break; - case '[7$': key.name = 'home'; key.shift = true; break; - case '[8$': key.name = 'end'; key.shift = true; break; - - case 'Oa': key.name = 'up'; key.ctrl = true; break; - case 'Ob': key.name = 'down'; key.ctrl = true; break; - case 'Oc': key.name = 'right'; key.ctrl = true; break; - case 'Od': key.name = 'left'; key.ctrl = true; break; - case 'Oe': key.name = 'clear'; key.ctrl = true; break; - - case '[2^': key.name = 'insert'; key.ctrl = true; break; - case '[3^': key.name = 'delete'; key.ctrl = true; break; - case '[5^': key.name = 'pageup'; key.ctrl = true; break; - case '[6^': key.name = 'pagedown'; key.ctrl = true; break; - case '[7^': key.name = 'home'; key.ctrl = true; break; - case '[8^': key.name = 'end'; key.ctrl = true; break; - - /* misc. */ - case '[Z': key.name = 'tab'; key.shift = true; break; - default: key.name = 'undefined'; break; - - } - } else if (s.length > 1 && s[0] !== '\x1b') { - // Got a longer-than-one string of characters. - // Probably a paste, since it wasn't a control sequence. - Array.prototype.forEach.call(s, function(c) { - emitKey(stream, c); - }); - return; - } - - if (key.code == '[M') { - key.name = 'mouse'; - var s = key.sequence; - var b = s.charCodeAt(3); - key.x = s.charCodeAt(4) - 040; - key.y = s.charCodeAt(5) - 040; - - key.scroll = 0; - - key.ctrl = !!(1<<4 & b); - key.meta = !!(1<<3 & b); - key.shift = !!(1<<2 & b); - - key.release = (3 & b) === 3; - - if (1<<6 & b) { //scroll - key.scroll = 1 & b ? 1 : -1; - } - - if (!key.release && !key.scroll) { - key.button = b & 3; - } - } - - // Don't emit a key if no name was found - if (key.name === undefined) { - key = undefined; - } - - if (s.length === 1) { - ch = s; - } - - if (key && key.name == 'mouse') { - stream.emit('mousepress', key) - } else if (key || ch) { - stream.emit('keypress', ch, key); - } -} diff --git a/node_modules/express/node_modules/commander/node_modules/keypress/package.json b/node_modules/express/node_modules/commander/node_modules/keypress/package.json deleted file mode 100644 index c5462052c..000000000 --- a/node_modules/express/node_modules/commander/node_modules/keypress/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "keypress", - "version": "0.1.0", - "description": "Make any Node ReadableStream emit \"keypress\" events", - "author": { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "http://tootallnate.net" - }, - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "git://github.com/TooTallNate/keypress.git" - }, - "keywords": [ - "keypress", - "readline", - "core" - ], - "license": "MIT", - "readme": "keypress\n========\n### Make any Node ReadableStream emit \"keypress\" events\n\n\nPrevious to Node `v0.8.x`, there was an undocumented `\"keypress\"` event that\n`process.stdin` would emit when it was a TTY. Some people discovered this hidden\ngem, and started using it in their own code.\n\nNow in Node `v0.8.x`, this `\"keypress\"` event does not get emitted by default,\nbut rather only when it is being used in conjuction with the `readline` (or by\nextension, the `repl`) module.\n\nThis module is the exact logic from the node `v0.8.x` releases ripped out into its\nown module.\n\n__Bonus:__ Now with mouse support!\n\nInstallation\n------------\n\nInstall with `npm`:\n\n``` bash\n$ npm install keypress\n```\n\nOr add it to the `\"dependencies\"` section of your _package.json_ file.\n\n\nExample\n-------\n\n#### Listening for \"keypress\" events\n\n``` js\nvar keypress = require('keypress');\n\n// make `process.stdin` begin emitting \"keypress\" events\nkeypress(process.stdin);\n\n// listen for the \"keypress\" event\nprocess.stdin.on('keypress', function (ch, key) {\n console.log('got \"keypress\"', key);\n if (key && key.ctrl && key.name == 'c') {\n process.stdin.pause();\n }\n});\n\nprocess.stdin.setRawMode(true);\nprocess.stdin.resume();\n```\n\n#### Listening for \"mousepress\" events\n\n``` js\nvar keypress = require('keypress');\n\n// make `process.stdin` begin emitting \"mousepress\" (and \"keypress\") events\nkeypress(process.stdin);\n\n// you must enable the mouse events before they will begin firing\nkeypress.enableMouse(process.stdout);\n\nprocess.stdin.on('mousepress', function (info) {\n console.log('got \"mousepress\" event at %d x %d', info.x, info.y);\n});\n\nprocess.on('exit', function () {\n // disable mouse on exit, so that the state\n // is back to normal for the terminal\n keypress.disableMouse(process.stdout);\n});\n```\n\n\nLicense\n-------\n\n(The MIT License)\n\nCopyright (c) 2012 Nathan Rajlich <nathan@tootallnate.net>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/TooTallNate/keypress/issues" - }, - "homepage": "https://github.com/TooTallNate/keypress", - "_id": "keypress@0.1.0", - "_from": "keypress@0.1.x" -} diff --git a/node_modules/express/node_modules/commander/node_modules/keypress/test.js b/node_modules/express/node_modules/commander/node_modules/keypress/test.js deleted file mode 100644 index c3f61d79d..000000000 --- a/node_modules/express/node_modules/commander/node_modules/keypress/test.js +++ /dev/null @@ -1,28 +0,0 @@ - -var keypress = require('./') -keypress(process.stdin) - -if (process.stdin.setRawMode) - process.stdin.setRawMode(true) -else - require('tty').setRawMode(true) - -process.stdin.on('keypress', function (c, key) { - console.log(0, c, key) - if (key && key.ctrl && key.name == 'c') { - process.stdin.pause() - } -}) -process.stdin.on('mousepress', function (mouse) { - console.log(mouse) -}) - -keypress.enableMouse(process.stdout) -process.on('exit', function () { - //disable mouse on exit, so that the state is back to normal - //for the terminal. - keypress.disableMouse(process.stdout) -}) - -process.stdin.resume() - diff --git a/node_modules/express/node_modules/commander/package.json b/node_modules/express/node_modules/commander/package.json deleted file mode 100644 index e156bc171..000000000 --- a/node_modules/express/node_modules/commander/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "commander", - "version": "1.3.2", - "description": "the complete solution for node.js command-line programs", - "keywords": [ - "command", - "option", - "parser", - "prompt", - "stdin" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "repository": { - "type": "git", - "url": "https://github.com/visionmedia/commander.js.git" - }, - "dependencies": { - "keypress": "0.1.x" - }, - "devDependencies": { - "should": ">= 0.0.1" - }, - "scripts": { - "test": "make test" - }, - "main": "index", - "engines": { - "node": ">= 0.6.x" - }, - "readme": "# Commander.js\n\n The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander).\n\n [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js)\n\n## Installation\n\n $ npm install commander\n\n## Option parsing\n\n Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('commander');\n\nprogram\n .version('0.0.1')\n .option('-p, --peppers', 'Add peppers')\n .option('-P, --pineapple', 'Add pineapple')\n .option('-b, --bbq', 'Add bbq sauce')\n .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')\n .parse(process.argv);\n\nconsole.log('you ordered a pizza with:');\nif (program.peppers) console.log(' - peppers');\nif (program.pineapple) console.log(' - pineapple');\nif (program.bbq) console.log(' - bbq');\nconsole.log(' - %s cheese', program.cheese);\n```\n\n Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as \"--template-engine\" are camel-cased, becoming `program.templateEngine` etc.\n\n## Automated --help\n\n The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:\n\n``` \n $ ./examples/pizza --help\n\n Usage: pizza [options]\n\n Options:\n\n -V, --version output the version number\n -p, --peppers Add peppers\n -P, --pineapple Add pineapple\n -b, --bbq Add bbq sauce\n -c, --cheese Add the specified type of cheese [marble]\n -h, --help output usage information\n\n```\n\n## Coercion\n\n```js\nfunction range(val) {\n return val.split('..').map(Number);\n}\n\nfunction list(val) {\n return val.split(',');\n}\n\nprogram\n .version('0.0.1')\n .usage('[options] ')\n .option('-i, --integer ', 'An integer argument', parseInt)\n .option('-f, --float ', 'A float argument', parseFloat)\n .option('-r, --range ..', 'A range', range)\n .option('-l, --list ', 'A list', list)\n .option('-o, --optional [value]', 'An optional value')\n .parse(process.argv);\n\nconsole.log(' int: %j', program.integer);\nconsole.log(' float: %j', program.float);\nconsole.log(' optional: %j', program.optional);\nprogram.range = program.range || [];\nconsole.log(' range: %j..%j', program.range[0], program.range[1]);\nconsole.log(' list: %j', program.list);\nconsole.log(' args: %j', program.args);\n```\n\n## Custom help\n\n You can display arbitrary `-h, --help` information\n by listening for \"--help\". Commander will automatically\n exit once you are done so that the remainder of your program\n does not execute causing undesired behaviours, for example\n in the following executable \"stuff\" will not output when\n `--help` is used.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('../');\n\nfunction list(val) {\n return val.split(',').map(Number);\n}\n\nprogram\n .version('0.0.1')\n .option('-f, --foo', 'enable some foo')\n .option('-b, --bar', 'enable some bar')\n .option('-B, --baz', 'enable some baz');\n\n// must be before .parse() since\n// node's emit() is immediate\n\nprogram.on('--help', function(){\n console.log(' Examples:');\n console.log('');\n console.log(' $ custom-help --help');\n console.log(' $ custom-help -h');\n console.log('');\n});\n\nprogram.parse(process.argv);\n\nconsole.log('stuff');\n```\n\nyielding the following help output:\n\n```\n\nUsage: custom-help [options]\n\nOptions:\n\n -h, --help output usage information\n -V, --version output the version number\n -f, --foo enable some foo\n -b, --bar enable some bar\n -B, --baz enable some baz\n\nExamples:\n\n $ custom-help --help\n $ custom-help -h\n\n```\n\n## .prompt(msg, fn)\n\n Single-line prompt:\n\n```js\nprogram.prompt('name: ', function(name){\n console.log('hi %s', name);\n});\n```\n\n Multi-line prompt:\n\n```js\nprogram.prompt('description:', function(name){\n console.log('hi %s', name);\n});\n```\n\n Coercion:\n\n```js\nprogram.prompt('Age: ', Number, function(age){\n console.log('age: %j', age);\n});\n```\n\n```js\nprogram.prompt('Birthdate: ', Date, function(date){\n console.log('date: %s', date);\n});\n```\n\n```js\nprogram.prompt('Email: ', /^.+@.+\\..+$/, function(email){\n console.log('email: %j', email);\n});\n```\n\n## .password(msg[, mask], fn)\n\nPrompt for password without echoing:\n\n```js\nprogram.password('Password: ', function(pass){\n console.log('got \"%s\"', pass);\n process.stdin.destroy();\n});\n```\n\nPrompt for password with mask char \"*\":\n\n```js\nprogram.password('Password: ', '*', function(pass){\n console.log('got \"%s\"', pass);\n process.stdin.destroy();\n});\n```\n\n## .confirm(msg, fn)\n\n Confirm with the given `msg`:\n\n```js\nprogram.confirm('continue? ', function(ok){\n console.log(' got %j', ok);\n});\n```\n\n## .choose(list, fn)\n\n Let the user choose from a `list`:\n\n```js\nvar list = ['tobi', 'loki', 'jane', 'manny', 'luna'];\n\nconsole.log('Choose the coolest pet:');\nprogram.choose(list, function(i){\n console.log('you chose %d \"%s\"', i, list[i]);\n});\n```\n\n## .outputHelp()\n\n Output help information without exiting.\n\n## .help()\n\n Output help information and exit immediately.\n\n## Links\n\n - [API documentation](http://visionmedia.github.com/commander.js/)\n - [ascii tables](https://github.com/LearnBoost/cli-table)\n - [progress bars](https://github.com/visionmedia/node-progress)\n - [more progress bars](https://github.com/substack/node-multimeter)\n - [examples](https://github.com/visionmedia/commander.js/tree/master/examples)\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/commander.js/issues" - }, - "homepage": "https://github.com/visionmedia/commander.js", - "_id": "commander@1.3.2", - "dist": { - "shasum": "a90f55ff9e0fa77d38694e2f5e906655da13a655" - }, - "_from": "commander@1.3.2", - "_resolved": "https://registry.npmjs.org/commander/-/commander-1.3.2.tgz" -} diff --git a/node_modules/express/node_modules/connect/.npmignore b/node_modules/express/node_modules/connect/.npmignore deleted file mode 100644 index 9046dde51..000000000 --- a/node_modules/express/node_modules/connect/.npmignore +++ /dev/null @@ -1,12 +0,0 @@ -*.markdown -*.md -.git* -Makefile -benchmarks/ -docs/ -examples/ -install.sh -support/ -test/ -.DS_Store -coverage.html diff --git a/node_modules/express/node_modules/connect/.travis.yml b/node_modules/express/node_modules/connect/.travis.yml deleted file mode 100644 index a12e3f0fd..000000000 --- a/node_modules/express/node_modules/connect/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/LICENSE b/node_modules/express/node_modules/connect/LICENSE deleted file mode 100644 index 0c5d22d96..000000000 --- a/node_modules/express/node_modules/connect/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -(The MIT License) - -Copyright (c) 2010 Sencha Inc. -Copyright (c) 2011 LearnBoost -Copyright (c) 2011 TJ Holowaychuk - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/Readme.md b/node_modules/express/node_modules/connect/Readme.md deleted file mode 100644 index e38a3263f..000000000 --- a/node_modules/express/node_modules/connect/Readme.md +++ /dev/null @@ -1,84 +0,0 @@ -# Connect [![build status](https://secure.travis-ci.org/senchalabs/connect.png)](http://travis-ci.org/senchalabs/connect) - - Connect is an extensible HTTP server framework for [node](http://nodejs.org), providing high performance "plugins" known as _middleware_. - - Connect is bundled with over _20_ commonly used middleware, including - a logger, session support, cookie parser, and [more](http://senchalabs.github.com/connect). Be sure to view the 2.x [documentation](http://senchalabs.github.com/connect/). - -```js -var connect = require('connect') - , http = require('http'); - -var app = connect() - .use(connect.favicon()) - .use(connect.logger('dev')) - .use(connect.static('public')) - .use(connect.directory('public')) - .use(connect.cookieParser()) - .use(connect.session({ secret: 'my secret here' })) - .use(function(req, res){ - res.end('Hello from Connect!\n'); - }); - -http.createServer(app).listen(3000); -``` - -## Middleware - - - [basicAuth](http://www.senchalabs.org/connect/basicAuth.html) - - [bodyParser](http://www.senchalabs.org/connect/bodyParser.html) - - [compress](http://www.senchalabs.org/connect/compress.html) - - [cookieParser](http://www.senchalabs.org/connect/cookieParser.html) - - [cookieSession](http://www.senchalabs.org/connect/cookieSession.html) - - [csrf](http://www.senchalabs.org/connect/csrf.html) - - [directory](http://www.senchalabs.org/connect/directory.html) - - [errorHandler](http://www.senchalabs.org/connect/errorHandler.html) - - [favicon](http://www.senchalabs.org/connect/favicon.html) - - [json](http://www.senchalabs.org/connect/json.html) - - [limit](http://www.senchalabs.org/connect/limit.html) - - [logger](http://www.senchalabs.org/connect/logger.html) - - [methodOverride](http://www.senchalabs.org/connect/methodOverride.html) - - [multipart](http://www.senchalabs.org/connect/multipart.html) - - [urlencoded](http://www.senchalabs.org/connect/urlencoded.html) - - [query](http://www.senchalabs.org/connect/query.html) - - [responseTime](http://www.senchalabs.org/connect/responseTime.html) - - [session](http://www.senchalabs.org/connect/session.html) - - [static](http://www.senchalabs.org/connect/static.html) - - [staticCache](http://www.senchalabs.org/connect/staticCache.html) - - [subdomains](http://www.senchalabs.org/connect/subdomains.html) - - [vhost](http://www.senchalabs.org/connect/vhost.html) - -## Running Tests - -first: - - $ npm install -d - -then: - - $ make test - -## Contributors - - https://github.com/senchalabs/connect/graphs/contributors - -## Node Compatibility - - Connect `< 1.x` is compatible with node 0.2.x - - - Connect `1.x` is compatible with node 0.4.x - - - Connect `2.x` is compatible with node 0.6.x - - - Connect (_master_) is compatible with node 0.8.x - -## CLA - - [http://sencha.com/cla](http://sencha.com/cla) - -## License - -View the [LICENSE](https://github.com/senchalabs/connect/blob/master/LICENSE) file. The [Silk](http://www.famfamfam.com/lab/icons/silk/) icons used by the `directory` middleware created by/copyright of [FAMFAMFAM](http://www.famfamfam.com/). diff --git a/node_modules/express/node_modules/connect/index.js b/node_modules/express/node_modules/connect/index.js deleted file mode 100644 index 23240eeda..000000000 --- a/node_modules/express/node_modules/connect/index.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = process.env.CONNECT_COV - ? require('./lib-cov/connect') - : require('./lib/connect'); \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/cache.js b/node_modules/express/node_modules/connect/lib/cache.js deleted file mode 100644 index 052fcdb3d..000000000 --- a/node_modules/express/node_modules/connect/lib/cache.js +++ /dev/null @@ -1,81 +0,0 @@ - -/*! - * Connect - Cache - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Expose `Cache`. - */ - -module.exports = Cache; - -/** - * LRU cache store. - * - * @param {Number} limit - * @api private - */ - -function Cache(limit) { - this.store = {}; - this.keys = []; - this.limit = limit; -} - -/** - * Touch `key`, promoting the object. - * - * @param {String} key - * @param {Number} i - * @api private - */ - -Cache.prototype.touch = function(key, i){ - this.keys.splice(i,1); - this.keys.push(key); -}; - -/** - * Remove `key`. - * - * @param {String} key - * @api private - */ - -Cache.prototype.remove = function(key){ - delete this.store[key]; -}; - -/** - * Get the object stored for `key`. - * - * @param {String} key - * @return {Array} - * @api private - */ - -Cache.prototype.get = function(key){ - return this.store[key]; -}; - -/** - * Add a cache `key`. - * - * @param {String} key - * @return {Array} - * @api private - */ - -Cache.prototype.add = function(key){ - // initialize store - var len = this.keys.push(key); - - // limit reached, invalidate LRU - if (len > this.limit) this.remove(this.keys.shift()); - - var arr = this.store[key] = []; - arr.createdAt = new Date; - return arr; -}; diff --git a/node_modules/express/node_modules/connect/lib/connect.js b/node_modules/express/node_modules/connect/lib/connect.js deleted file mode 100644 index 72961dca7..000000000 --- a/node_modules/express/node_modules/connect/lib/connect.js +++ /dev/null @@ -1,92 +0,0 @@ -/*! - * Connect - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , proto = require('./proto') - , utils = require('./utils') - , path = require('path') - , basename = path.basename - , fs = require('fs'); - -// node patches - -require('./patch'); - -// expose createServer() as the module - -exports = module.exports = createServer; - -/** - * Framework version. - */ - -exports.version = '2.7.11'; - -/** - * Expose mime module. - */ - -exports.mime = require('./middleware/static').mime; - -/** - * Expose the prototype. - */ - -exports.proto = proto; - -/** - * Auto-load middleware getters. - */ - -exports.middleware = {}; - -/** - * Expose utilities. - */ - -exports.utils = utils; - -/** - * Create a new connect server. - * - * @return {Function} - * @api public - */ - -function createServer() { - function app(req, res, next){ app.handle(req, res, next); } - utils.merge(app, proto); - utils.merge(app, EventEmitter.prototype); - app.route = '/'; - app.stack = []; - for (var i = 0; i < arguments.length; ++i) { - app.use(arguments[i]); - } - return app; -}; - -/** - * Support old `.createServer()` method. - */ - -createServer.createServer = createServer; - -/** - * Auto-load bundled middleware with getters. - */ - -fs.readdirSync(__dirname + '/middleware').forEach(function(filename){ - if (!/\.js$/.test(filename)) return; - var name = basename(filename, '.js'); - function load(){ return require('./middleware/' + name); } - exports.middleware.__defineGetter__(name, load); - exports.__defineGetter__(name, load); -}); diff --git a/node_modules/express/node_modules/connect/lib/index.js b/node_modules/express/node_modules/connect/lib/index.js deleted file mode 100644 index 5938c7533..000000000 --- a/node_modules/express/node_modules/connect/lib/index.js +++ /dev/null @@ -1,50 +0,0 @@ - -/** - * Connect is a middleware framework for node, - * shipping with over 18 bundled middleware and a rich selection of - * 3rd-party middleware. - * - * var app = connect() - * .use(connect.logger('dev')) - * .use(connect.static('public')) - * .use(function(req, res){ - * res.end('hello world\n'); - * }) - * - * http.createServer(app).listen(3000); - * - * Installation: - * - * $ npm install connect - * - * Middleware: - * - * - [logger](logger.html) request logger with custom format support - * - [csrf](csrf.html) Cross-site request forgery protection - * - [compress](compress.html) Gzip compression middleware - * - [basicAuth](basicAuth.html) basic http authentication - * - [bodyParser](bodyParser.html) extensible request body parser - * - [json](json.html) application/json parser - * - [urlencoded](urlencoded.html) application/x-www-form-urlencoded parser - * - [multipart](multipart.html) multipart/form-data parser - * - [timeout](timeout.html) request timeouts - * - [cookieParser](cookieParser.html) cookie parser - * - [session](session.html) session management support with bundled MemoryStore - * - [cookieSession](cookieSession.html) cookie-based session support - * - [methodOverride](methodOverride.html) faux HTTP method support - * - [responseTime](responseTime.html) calculates response-time and exposes via X-Response-Time - * - [staticCache](staticCache.html) memory cache layer for the static() middleware - * - [static](static.html) streaming static file server supporting `Range` and more - * - [directory](directory.html) directory listing middleware - * - [vhost](vhost.html) virtual host sub-domain mapping middleware - * - [favicon](favicon.html) efficient favicon server (with default icon) - * - [limit](limit.html) limit the bytesize of request bodies - * - [query](query.html) automatic querystring parser, populating `req.query` - * - [errorHandler](errorHandler.html) flexible error handler - * - * Links: - * - * - list of [3rd-party](https://github.com/senchalabs/connect/wiki) middleware - * - GitHub [repository](http://github.com/senchalabs/connect) - * - */ \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js b/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js deleted file mode 100644 index 8af07ca0a..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/basicAuth.js +++ /dev/null @@ -1,106 +0,0 @@ -/*! - * Connect - basicAuth - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , unauthorized = utils.unauthorized; - -/** - * Basic Auth: - * - * Status: Deprecated. No bug reports or pull requests are welcomed - * for this middleware. However, this middleware will not be removed. - * Instead, you should use [basic-auth](https://github.com/visionmedia/node-basic-auth). - * - * Enfore basic authentication by providing a `callback(user, pass)`, - * which must return `true` in order to gain access. Alternatively an async - * method is provided as well, invoking `callback(user, pass, callback)`. Populates - * `req.user`. The final alternative is simply passing username / password - * strings. - * - * Simple username and password - * - * connect(connect.basicAuth('username', 'password')); - * - * Callback verification - * - * connect() - * .use(connect.basicAuth(function(user, pass){ - * return 'tj' == user && 'wahoo' == pass; - * })) - * - * Async callback verification, accepting `fn(err, user)`. - * - * connect() - * .use(connect.basicAuth(function(user, pass, fn){ - * User.authenticate({ user: user, pass: pass }, fn); - * })) - * - * @param {Function|String} callback or username - * @param {String} realm - * @api public - */ - -module.exports = function basicAuth(callback, realm) { - var username, password; - - // user / pass strings - if ('string' == typeof callback) { - username = callback; - password = realm; - if ('string' != typeof password) throw new Error('password argument required'); - realm = arguments[2]; - callback = function(user, pass){ - return user == username && pass == password; - } - } - - realm = realm || 'Authorization Required'; - - return function(req, res, next) { - var authorization = req.headers.authorization; - - if (req.user) return next(); - if (!authorization) return unauthorized(res, realm); - - var parts = authorization.split(' '); - - if (parts.length !== 2) return next(utils.error(400)); - - var scheme = parts[0] - , credentials = new Buffer(parts[1], 'base64').toString() - , index = credentials.indexOf(':'); - - if ('Basic' != scheme || index < 0) return next(utils.error(400)); - - var user = credentials.slice(0, index) - , pass = credentials.slice(index + 1); - - // async - if (callback.length >= 3) { - var pause = utils.pause(req); - callback(user, pass, function(err, user){ - if (err || !user) return unauthorized(res, realm); - req.user = req.remoteUser = user; - next(); - pause.resume(); - }); - // sync - } else { - if (callback(user, pass)) { - req.user = req.remoteUser = user; - next(); - } else { - unauthorized(res, realm); - } - } - } -}; - diff --git a/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js b/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js deleted file mode 100644 index 14481f56a..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js +++ /dev/null @@ -1,68 +0,0 @@ - -/*! - * Connect - bodyParser - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var multipart = require('./multipart') - , urlencoded = require('./urlencoded') - , json = require('./json'); - -/** - * Body parser: - * - * Status: the multipart body parser will be removed in Connect 3. - * - * Parse request bodies, supports _application/json_, - * _application/x-www-form-urlencoded_, and _multipart/form-data_. - * - * This is equivalent to: - * - * app.use(connect.json()); - * app.use(connect.urlencoded()); - * app.use(connect.multipart()); - * - * Examples: - * - * connect() - * .use(connect.bodyParser()) - * .use(function(req, res) { - * res.end('viewing user ' + req.body.user.name); - * }); - * - * $ curl -d 'user[name]=tj' http://local/ - * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://local/ - * - * View [json](json.html), [urlencoded](urlencoded.html), and [multipart](multipart.html) for more info. - * - * If you wish to create your own body parser, you may be interested in: - * - * - [raw-body](https://github.com/stream-utils/raw-body) - * - [body](https://github.com/raynos/body) - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function bodyParser(options){ - var _urlencoded = urlencoded(options) - , _multipart = multipart(options) - , _json = json(options); - - return function bodyParser(req, res, next) { - _json(req, res, function(err){ - if (err) return next(err); - _urlencoded(req, res, function(err){ - if (err) return next(err); - _multipart(req, res, next); - }); - }); - } -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/compress.js b/node_modules/express/node_modules/connect/lib/middleware/compress.js deleted file mode 100644 index a300e5300..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/compress.js +++ /dev/null @@ -1,192 +0,0 @@ -/*! - * Connect - compress - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var zlib = require('zlib'); -var utils = require('../utils'); -var Negotiator = require('negotiator'); - -/** - * Supported content-encoding methods. - */ - -exports.methods = { - gzip: zlib.createGzip - , deflate: zlib.createDeflate -}; - -/** - * Default filter function. - */ - -exports.filter = function(req, res){ - return /json|text|javascript|dart|image\/svg\+xml|application\/x-font-ttf|application\/vnd\.ms-opentype|application\/vnd\.ms-fontobject/.test(res.getHeader('Content-Type')); -}; - -/** - * Compress: - * - * Compress response data with gzip/deflate. - * - * Filter: - * - * A `filter` callback function may be passed to - * replace the default logic of: - * - * exports.filter = function(req, res){ - * return /json|text|javascript/.test(res.getHeader('Content-Type')); - * }; - * - * Threshold: - * - * Only compress the response if the byte size is at or above a threshold. - * Always compress while streaming. - * - * - `threshold` - string representation of size or bytes as an integer. - * - * Options: - * - * All remaining options are passed to the gzip/deflate - * creation functions. Consult node's docs for additional details. - * - * - `chunkSize` (default: 16*1024) - * - `windowBits` - * - `level`: 0-9 where 0 is no compression, and 9 is slow but best compression - * - `memLevel`: 1-9 low is slower but uses less memory, high is fast but uses more - * - `strategy`: compression strategy - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function compress(options) { - options = options || {}; - var filter = options.filter || exports.filter; - var threshold; - - if (false === options.threshold || 0 === options.threshold) { - threshold = 0 - } else if ('string' === typeof options.threshold) { - threshold = utils.parseBytes(options.threshold) - } else { - threshold = options.threshold || 1024 - } - - return function compress(req, res, next){ - var accept = req.headers['accept-encoding'] - , write = res.write - , end = res.end - , compress = true - , stream; - - // see #724 - req.on('close', function(){ - res.write = res.end = function(){}; - }); - - // flush is noop by default - res.flush = noop; - - // proxy - - res.write = function(chunk, encoding){ - if (!this.headerSent) { - // if content-length is set and is lower - // than the threshold, don't compress - var length = res.getHeader('content-length'); - if (!isNaN(length) && length < threshold) compress = false; - this._implicitHeader(); - } - return stream - ? stream.write(new Buffer(chunk, encoding)) - : write.call(res, chunk, encoding); - }; - - res.end = function(chunk, encoding){ - if (chunk) { - if (!this.headerSent && getSize(chunk) < threshold) compress = false; - this.write(chunk, encoding); - } else if (!this.headerSent) { - // response size === 0 - compress = false; - } - return stream - ? stream.end() - : end.call(res); - }; - - res.on('header', function(){ - // default request filter - if (!filter(req, res)) return; - - // vary - var vary = res.getHeader('Vary'); - if (!vary) { - res.setHeader('Vary', 'Accept-Encoding'); - } else if (!~vary.indexOf('Accept-Encoding')) { - res.setHeader('Vary', vary + ', Accept-Encoding'); - } - - if (!compress) return; - - var encoding = res.getHeader('Content-Encoding') || 'identity'; - - // already encoded - if ('identity' != encoding) return; - - // SHOULD use identity - if (!accept) return; - - // head - if ('HEAD' == req.method) return; - - // compression method - var method = new Negotiator(req).preferredEncoding(['gzip', 'deflate', 'identity']); - // negotiation failed - if (method === 'identity') return; - - // compression stream - stream = exports.methods[method](options); - - // overwrite the flush method - res.flush = function(){ - stream.flush(); - } - - // header fields - res.setHeader('Content-Encoding', method); - res.removeHeader('Content-Length'); - - // compression - stream.on('data', function(chunk){ - write.call(res, chunk); - }); - - stream.on('end', function(){ - end.call(res); - }); - - stream.on('drain', function() { - res.emit('drain'); - }); - }); - - next(); - }; -}; - -function getSize(chunk) { - return Buffer.isBuffer(chunk) - ? chunk.length - : Buffer.byteLength(chunk); -} - -function noop(){} diff --git a/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js b/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js deleted file mode 100644 index 665226c47..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js +++ /dev/null @@ -1,67 +0,0 @@ - -/*! - * Connect - cookieParser - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./../utils') - , cookie = require('cookie'); - -/** - * Cookie parser: - * - * Status: Deprecated. This middleware will be removed in - * Connect 3.0 and will be replaced by a `cookies` middleware, - * which will use [cookies](http://github.com/jed/cookies) - * and [keygrip](https://github.com/jed/keygrip). - * - * Parse _Cookie_ header and populate `req.cookies` - * with an object keyed by the cookie names. Optionally - * you may enabled signed cookie support by passing - * a `secret` string, which assigns `req.secret` so - * it may be used by other middleware. - * - * Examples: - * - * connect() - * .use(connect.cookieParser('optional secret string')) - * .use(function(req, res, next){ - * res.end(JSON.stringify(req.cookies)); - * }) - * - * @param {String} secret - * @return {Function} - * @api public - */ - -module.exports = function cookieParser(secret, opt){ - return function cookieParser(req, res, next) { - if (req.cookies) return next(); - var cookies = req.headers.cookie; - - req.secret = secret; - req.cookies = {}; - req.signedCookies = {}; - - if (cookies) { - try { - req.cookies = cookie.parse(cookies, opt); - if (secret) { - req.signedCookies = utils.parseSignedCookies(req.cookies, secret); - req.signedCookies = utils.parseJSONCookies(req.signedCookies); - } - req.cookies = utils.parseJSONCookies(req.cookies); - } catch (err) { - err.status = 400; - return next(err); - } - } - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/cookieSession.js b/node_modules/express/node_modules/connect/lib/middleware/cookieSession.js deleted file mode 100644 index 663f2b97c..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/cookieSession.js +++ /dev/null @@ -1,122 +0,0 @@ -/*! - * Connect - cookieSession - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./../utils') - , Cookie = require('./session/cookie') - , debug = require('debug')('connect:cookieSession') - , signature = require('cookie-signature') - , crc32 = require('buffer-crc32') - , url = require('url'); - -/** - * Cookie Session: - * - * Cookie session middleware. - * - * var app = connect(); - * app.use(connect.cookieParser()); - * app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }})); - * - * Options: - * - * - `key` cookie name defaulting to `connect.sess` - * - `secret` prevents cookie tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Clearing sessions: - * - * To clear the session simply set its value to `null`, - * `cookieSession()` will then respond with a 1970 Set-Cookie. - * - * req.session = null; - * - * If you are interested in more sophisticated solutions, - * you may be interested in: - * - * - [client-sessions](https://github.com/mozilla/node-client-sessions) - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function cookieSession(options){ - // TODO: utilize Session/Cookie to unify API - options = options || {}; - var key = options.key || 'connect.sess' - , trustProxy = options.proxy; - - return function cookieSession(req, res, next) { - - // req.secret is for backwards compatibility - var secret = options.secret || req.secret; - if (!secret) throw new Error('`secret` option required for cookie sessions'); - - // default session - req.session = {}; - var cookie = req.session.cookie = new Cookie(options.cookie); - - // pathname mismatch - var originalPath = url.parse(req.originalUrl).pathname; - if (0 != originalPath.indexOf(cookie.path)) return next(); - - // cookieParser secret - if (!options.secret && req.secret) { - req.session = req.signedCookies[key] || {}; - req.session.cookie = cookie; - } else { - // TODO: refactor - var rawCookie = req.cookies[key]; - if (rawCookie) { - var unsigned = utils.parseSignedCookie(rawCookie, secret); - if (unsigned) { - var originalHash = crc32.signed(unsigned); - req.session = utils.parseJSONCookie(unsigned) || {}; - req.session.cookie = cookie; - } - } - } - - res.on('header', function(){ - // removed - if (!req.session) { - debug('clear session'); - cookie.expires = new Date(0); - res.setHeader('Set-Cookie', cookie.serialize(key, '')); - return; - } - - delete req.session.cookie; - - // check security - var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase() - , tls = req.connection.encrypted || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0]); - - // only send secure cookies via https - if (cookie.secure && !tls) return debug('not secured'); - - // serialize - debug('serializing %j', req.session); - var val = 'j:' + JSON.stringify(req.session); - - // compare hashes, no need to set-cookie if unchanged - if (originalHash == crc32.signed(val)) return debug('unmodified session'); - - // set-cookie - val = 's:' + signature.sign(val, secret); - val = cookie.serialize(key, val); - debug('set-cookie %j', cookie); - res.setHeader('Set-Cookie', val); - }); - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/csrf.js b/node_modules/express/node_modules/connect/lib/middleware/csrf.js deleted file mode 100644 index 1c3854b45..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/csrf.js +++ /dev/null @@ -1,163 +0,0 @@ -/*! - * Connect - csrf - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils'); -var uid = require('uid2'); -var crypto = require('crypto'); - -/** - * Anti CSRF: - * - * CSRF protection middleware. - * - * This middleware adds a `req.csrfToken()` function to make a token - * which should be added to requests which mutate - * state, within a hidden form field, query-string etc. This - * token is validated against the visitor's session. - * - * The default `value` function checks `req.body` generated - * by the `bodyParser()` middleware, `req.query` generated - * by `query()`, and the "X-CSRF-Token" header field. - * - * This middleware requires session support, thus should be added - * somewhere _below_ `session()` and `cookieParser()`. - * - * Options: - * - * - `value` a function accepting the request, returning the token - * - * @param {Object} options - * @api public - */ - -module.exports = function csrf(options) { - options = options || {}; - var value = options.value || defaultValue; - - return function(req, res, next){ - - // already have one - var secret = req.session._csrfSecret; - if (secret) return createToken(secret); - - // generate secret - uid(24, function(err, secret){ - if (err) return next(err); - req.session._csrfSecret = secret; - createToken(secret); - }); - - // generate the token - function createToken(secret) { - var token; - - // lazy-load token - req.csrfToken = function csrfToken() { - return token || (token = saltedToken(secret)); - }; - - // compatibility with old middleware - Object.defineProperty(req.session, '_csrf', { - configurable: true, - get: function() { - console.warn('req.session._csrf is deprecated, use req.csrfToken() instead'); - return req.csrfToken(); - } - }); - - // ignore these methods - if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next(); - - // determine user-submitted value - var val = value(req); - - // check - if (!checkToken(val, secret)) return next(utils.error(403)); - - next(); - } - } -}; - -/** - * Default value function, checking the `req.body` - * and `req.query` for the CSRF token. - * - * @param {IncomingMessage} req - * @return {String} - * @api private - */ - -function defaultValue(req) { - return (req.body && req.body._csrf) - || (req.query && req.query._csrf) - || (req.headers['x-csrf-token']) - || (req.headers['x-xsrf-token']); -} - -/** - * Return salted token. - * - * @param {String} secret - * @return {String} - * @api private - */ - -function saltedToken(secret) { - return createToken(generateSalt(10), secret); -} - -/** - * Creates a CSRF token from a given salt and secret. - * - * @param {String} salt (should be 10 characters) - * @param {String} secret - * @return {String} - * @api private - */ - -function createToken(salt, secret) { - return salt + crypto - .createHash('sha1') - .update(salt + secret) - .digest('base64'); -} - -/** - * Checks if a given CSRF token matches the given secret. - * - * @param {String} token - * @param {String} secret - * @return {Boolean} - * @api private - */ - -function checkToken(token, secret) { - if ('string' != typeof token) return false; - return token === createToken(token.slice(0, 10), secret); -} - -/** - * Generates a random salt, using a fast non-blocking PRNG (Math.random()). - * - * @param {Number} length - * @return {String} - * @api private - */ - -function generateSalt(length) { - var i, r = []; - for (i = 0; i < length; ++i) { - r.push(SALTCHARS[Math.floor(Math.random() * SALTCHARS.length)]); - } - return r.join(''); -} - -var SALTCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; diff --git a/node_modules/express/node_modules/connect/lib/middleware/directory.js b/node_modules/express/node_modules/connect/lib/middleware/directory.js deleted file mode 100644 index ac8ea7a5c..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/directory.js +++ /dev/null @@ -1,330 +0,0 @@ - -/*! - * Connect - directory - * Copyright(c) 2011 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -// TODO: arrow key navigation -// TODO: make icons extensible - -/** - * Module dependencies. - */ - -var fs = require('fs') - , parse = require('url').parse - , utils = require('../utils') - , path = require('path') - , normalize = path.normalize - , sep = path.sep - , extname = path.extname - , join = path.join; -var Batch = require('batch'); -var Negotiator = require('negotiator'); - -/*! - * Icon cache. - */ - -var cache = {}; - -/** - * Media types and the map for content negotiation. - */ - -var mediaTypes = [ - 'text/html', - 'text/plain', - 'application/json' -]; - -var mediaType = { - 'text/html': 'html', - 'text/plain': 'plain', - 'application/json': 'json' -}; - -/** - * Directory: - * - * Serve directory listings with the given `root` path. - * - * Options: - * - * - `hidden` display hidden (dot) files. Defaults to false. - * - `icons` display icons. Defaults to false. - * - `filter` Apply this filter function to files. Defaults to false. - * - * @param {String} root - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function directory(root, options){ - options = options || {}; - - // root required - if (!root) throw new Error('directory() root path required'); - var hidden = options.hidden - , icons = options.icons - , view = options.view || 'tiles' - , filter = options.filter - , root = normalize(root + sep); - - return function directory(req, res, next) { - if ('GET' != req.method && 'HEAD' != req.method) return next(); - - var url = parse(req.url) - , dir = decodeURIComponent(url.pathname) - , path = normalize(join(root, dir)) - , originalUrl = parse(req.originalUrl) - , originalDir = decodeURIComponent(originalUrl.pathname) - , showUp = path != root; - - // null byte(s), bad request - if (~path.indexOf('\0')) return next(utils.error(400)); - - // malicious path, forbidden - if (0 != path.indexOf(root)) return next(utils.error(403)); - - // check if we have a directory - fs.stat(path, function(err, stat){ - if (err) return 'ENOENT' == err.code - ? next() - : next(err); - - if (!stat.isDirectory()) return next(); - - // fetch files - fs.readdir(path, function(err, files){ - if (err) return next(err); - if (!hidden) files = removeHidden(files); - if (filter) files = files.filter(filter); - files.sort(); - - // content-negotiation - var type = new Negotiator(req).preferredMediaType(mediaTypes); - - // not acceptable - if (!type) return next(utils.error(406)); - exports[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view); - }); - }); - }; -}; - -/** - * Respond with text/html. - */ - -exports.html = function(req, res, files, next, dir, showUp, icons, path, view){ - fs.readFile(__dirname + '/../public/directory.html', 'utf8', function(err, str){ - if (err) return next(err); - fs.readFile(__dirname + '/../public/style.css', 'utf8', function(err, style){ - if (err) return next(err); - stat(path, files, function(err, stats){ - if (err) return next(err); - files = files.map(function(file, i){ return { name: file, stat: stats[i] }; }); - files.sort(fileSort); - if (showUp) files.unshift({ name: '..' }); - str = str - .replace('{style}', style.concat(iconStyle(files, icons))) - .replace('{files}', html(files, dir, icons, view)) - .replace('{directory}', dir) - .replace('{linked-path}', htmlPath(dir)); - res.setHeader('Content-Type', 'text/html'); - res.setHeader('Content-Length', str.length); - res.end(str); - }); - }); - }); -}; - -/** - * Respond with application/json. - */ - -exports.json = function(req, res, files){ - files = JSON.stringify(files); - res.setHeader('Content-Type', 'application/json'); - res.setHeader('Content-Length', files.length); - res.end(files); -}; - -/** - * Respond with text/plain. - */ - -exports.plain = function(req, res, files){ - files = files.join('\n') + '\n'; - res.setHeader('Content-Type', 'text/plain'); - res.setHeader('Content-Length', files.length); - res.end(files); -}; - -/** - * Sort function for with directories first. - */ - -function fileSort(a, b) { - return Number(b.stat && b.stat.isDirectory()) - Number(a.stat && a.stat.isDirectory()) || - String(a.name).toLocaleLowerCase().localeCompare(String(b.name).toLocaleLowerCase()); -} - -/** - * Map html `dir`, returning a linked path. - */ - -function htmlPath(dir) { - var curr = []; - return dir.split('/').map(function(part){ - curr.push(encodeURIComponent(part)); - return part ? '' + part + '' : ''; - }).join(' / '); -} - -/** - * Load icon images, return css string. - */ - -function iconStyle (files, useIcons) { - if (!useIcons) return ''; - var data = {}; - var views = { tiles: [], details: [], mobile: [] }; - - for (var i=0; i < files.length; i++) { - var file = files[i]; - if (file.name == '..') continue; - - var isDir = '..' == file.name || (file.stat && file.stat.isDirectory()); - var icon = isDir ? icons.folder : icons[extname(file.name)] || icons.default; - - var ext = extname(file.name); - ext = isDir ? '.directory' : (icons[ext] ? ext : '.default'); - - if (data[icon]) continue; - data[icon] = ext + ' .name{background-image: url(data:image/png;base64,' + load(icon)+');}'; - views.tiles.push('.view-tiles ' + data[icon]); - views.details.push('.view-details ' + data[icon]); - views.mobile.push('#files ' + data[icon]); - } - - var style = views.tiles.join('\n') - + '\n'+views.details.join('\n') - + '\n@media (max-width: 768px) {\n\t' - + views.mobile.join('\n\t') - + '\n}'; - return style; -} - -/** - * Map html `files`, returning an html unordered list. - */ - -function html(files, dir, useIcons, view) { - return '
    ' - + (view == 'details' ? ( - '
  • ' - + 'Name' - + 'Size' - + 'Modified' - + '
  • ') : '') - + files.map(function(file){ - var isDir - , classes = [] - , path = dir.split('/').map(function (c) { return encodeURIComponent(c); }); - - if (useIcons) { - var ext = extname(file.name); - isDir = '..' == file.name || (file.stat && file.stat.isDirectory()); - ext = isDir ? '.directory' : (icons[ext] ? ext : '.default'); - classes.push('icon'); - classes.push(ext.replace('.','')); - } - - path.push(encodeURIComponent(file.name)); - - var date = file.name == '..' ? '' - : file.stat.mtime.toDateString()+' '+file.stat.mtime.toLocaleTimeString(); - var size = file.name == '..' ? '' : file.stat.size; - - return '
  • ' - + ''+file.name+'' - + ''+size+'' - + ''+date+'' - + '
  • '; - - }).join('\n') + '
'; -} - -/** - * Load and cache the given `icon`. - * - * @param {String} icon - * @return {String} - * @api private - */ - -function load(icon) { - if (cache[icon]) return cache[icon]; - return cache[icon] = fs.readFileSync(__dirname + '/../public/icons/' + icon, 'base64'); -} - -/** - * Filter "hidden" `files`, aka files - * beginning with a `.`. - * - * @param {Array} files - * @return {Array} - * @api private - */ - -function removeHidden(files) { - return files.filter(function(file){ - return '.' != file[0]; - }); -} - -/** - * Stat all files and return array of stat - * in same order. - */ - -function stat(dir, files, cb) { - var batch = new Batch(); - - batch.concurrency(10); - - files.forEach(function(file, i){ - batch.push(function(done){ - fs.stat(join(dir, file), done); - }); - }); - - batch.end(cb); -} - -/** - * Icon map. - */ - -var icons = { - '.js': 'page_white_code_red.png' - , '.c': 'page_white_c.png' - , '.h': 'page_white_h.png' - , '.cc': 'page_white_cplusplus.png' - , '.php': 'page_white_php.png' - , '.rb': 'page_white_ruby.png' - , '.cpp': 'page_white_cplusplus.png' - , '.swf': 'page_white_flash.png' - , '.pdf': 'page_white_acrobat.png' - , 'folder': 'folder.png' - , 'default': 'page_white.png' -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js b/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js deleted file mode 100644 index 56e96830c..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/errorHandler.js +++ /dev/null @@ -1,86 +0,0 @@ -/*! - * Connect - errorHandler - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , fs = require('fs'); - -// environment - -var env = process.env.NODE_ENV || 'development'; - -/** - * Error handler: - * - * Development error handler, providing stack traces - * and error message responses for requests accepting text, html, - * or json. - * - * Text: - * - * By default, and when _text/plain_ is accepted a simple stack trace - * or error message will be returned. - * - * JSON: - * - * When _application/json_ is accepted, connect will respond with - * an object in the form of `{ "error": error }`. - * - * HTML: - * - * When accepted connect will output a nice html stack trace. - * - * @return {Function} - * @api public - */ - -exports = module.exports = function errorHandler(){ - return function errorHandler(err, req, res, next){ - if (err.status) res.statusCode = err.status; - if (res.statusCode < 400) res.statusCode = 500; - if ('test' != env) console.error(err.stack); - var accept = req.headers.accept || ''; - // html - if (~accept.indexOf('html')) { - fs.readFile(__dirname + '/../public/style.css', 'utf8', function(e, style){ - fs.readFile(__dirname + '/../public/error.html', 'utf8', function(e, html){ - var stack = (err.stack || '') - .split('\n').slice(1) - .map(function(v){ return '
  • ' + v + '
  • '; }).join(''); - html = html - .replace('{style}', style) - .replace('{stack}', stack) - .replace('{title}', exports.title) - .replace('{statusCode}', res.statusCode) - .replace(/\{error\}/g, utils.escape(err.toString().replace(/\n/g, '
    '))); - res.setHeader('Content-Type', 'text/html; charset=utf-8'); - res.end(html); - }); - }); - // json - } else if (~accept.indexOf('json')) { - var error = { message: err.message, stack: err.stack }; - for (var prop in err) error[prop] = err[prop]; - var json = JSON.stringify({ error: error }); - res.setHeader('Content-Type', 'application/json'); - res.end(json); - // plain text - } else { - res.setHeader('Content-Type', 'text/plain'); - res.end(err.stack); - } - }; -}; - -/** - * Template title, framework authors may override this value. - */ - -exports.title = 'Connect'; diff --git a/node_modules/express/node_modules/connect/lib/middleware/favicon.js b/node_modules/express/node_modules/connect/lib/middleware/favicon.js deleted file mode 100644 index ef543544c..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/favicon.js +++ /dev/null @@ -1,80 +0,0 @@ -/*! - * Connect - favicon - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var fs = require('fs') - , utils = require('../utils'); - -/** - * Favicon: - * - * By default serves the connect favicon, or the favicon - * located by the given `path`. - * - * Options: - * - * - `maxAge` cache-control max-age directive, defaulting to 1 day - * - * Examples: - * - * Serve default favicon: - * - * connect() - * .use(connect.favicon()) - * - * Serve favicon before logging for brevity: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger('dev')) - * - * Serve custom favicon: - * - * connect() - * .use(connect.favicon('public/favicon.ico')) - * - * @param {String} path - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function favicon(path, options){ - var options = options || {} - , path = path || __dirname + '/../public/favicon.ico' - , maxAge = options.maxAge || 86400000 - , icon; // favicon cache - - return function favicon(req, res, next){ - if ('/favicon.ico' == req.url) { - if (icon) { - res.writeHead(200, icon.headers); - res.end(icon.body); - } else { - fs.readFile(path, function(err, buf){ - if (err) return next(err); - icon = { - headers: { - 'Content-Type': 'image/x-icon' - , 'Content-Length': buf.length - , 'ETag': '"' + utils.md5(buf) + '"' - , 'Cache-Control': 'public, max-age=' + (maxAge / 1000) - }, - body: buf - }; - res.writeHead(200, icon.headers); - res.end(icon.body); - }); - } - } else { - next(); - } - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/json.js b/node_modules/express/node_modules/connect/lib/middleware/json.js deleted file mode 100644 index ef4898520..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/json.js +++ /dev/null @@ -1,87 +0,0 @@ - -/*! - * Connect - json - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils'); -var getBody = require('raw-body'); - -/** - * JSON: - * - * Parse JSON request bodies, providing the - * parsed object as `req.body`. - * - * Options: - * - * - `strict` when `false` anything `JSON.parse()` accepts will be parsed - * - `reviver` used as the second "reviver" argument for JSON.parse - * - `limit` byte limit [1mb] - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - options = options || {}; - var strict = options.strict !== false; - var verify = typeof options.verify === 'function' && options.verify; - - return function json(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - - if (!utils.hasBody(req)) return next(); - - // check Content-Type - if (!exports.regexp.test(utils.mime(req))) return next(); - - // flag as parsed - req._body = true; - - // parse - getBody(req, { - limit: options.limit || '1mb', - length: req.headers['content-length'], - encoding: 'utf8' - }, function (err, buf) { - if (err) return next(err); - - if (verify) { - try { - verify(req, res, buf) - } catch (err) { - if (!err.status) err.status = 403; - return next(err); - } - } - - var first = buf.trim()[0]; - - if (0 == buf.length) { - return next(utils.error(400, 'invalid json, empty body')); - } - - if (strict && '{' != first && '[' != first) return next(utils.error(400, 'invalid json')); - try { - req.body = JSON.parse(buf, options.reviver); - } catch (err){ - err.body = buf; - err.status = 400; - return next(err); - } - next(); - }) - }; -}; - -exports.regexp = /^application\/([\w!#\$%&\*`\-\.\^~]*\+)?json$/i; - diff --git a/node_modules/express/node_modules/connect/lib/middleware/limit.js b/node_modules/express/node_modules/connect/lib/middleware/limit.js deleted file mode 100644 index 2b895f97b..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/limit.js +++ /dev/null @@ -1,89 +0,0 @@ - -/*! - * Connect - limit - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils'), - brokenPause = utils.brokenPause; - -/** - * Limit: - * - * Status: Deprecated. This middleware will be removed in Connect 3.0. - * If you still wish to use some type of limit middleware, - * you may be interested in: - * - * - [raw-body](https://github.com/stream-utils/raw-body) - * - * Limit request bodies to the given size in `bytes`. - * - * A string representation of the bytesize may also be passed, - * for example "5mb", "200kb", "1gb", etc. - * - * connect() - * .use(connect.limit('5.5mb')) - * .use(handleImageUpload) - * - * @param {Number|String} bytes - * @return {Function} - * @api public - */ - -module.exports = function limit(bytes){ - if ('string' == typeof bytes) bytes = utils.parseBytes(bytes); - if ('number' != typeof bytes) throw new Error('limit() bytes required'); - - if (process.env.NODE_ENV !== 'test') { - console.warn('connect.limit() will be removed in connect 3.0'); - } - - return function limit(req, res, next){ - var received = 0 - , len = req.headers['content-length'] - ? parseInt(req.headers['content-length'], 10) - : null; - - // self-awareness - if (req._limit) return next(); - req._limit = true; - - // limit by content-length - if (len && len > bytes) return next(utils.error(413)); - - // limit - if (brokenPause) { - listen(); - } else { - req.on('newListener', function handler(event) { - if (event !== 'data') return; - - req.removeListener('newListener', handler); - // Start listening at the end of the current loop - // otherwise the request will be consumed too early. - // Sideaffect is `limit` will miss the first chunk, - // but that's not a big deal. - // Unfortunately, the tests don't have large enough - // request bodies to test this. - process.nextTick(listen); - }); - }; - - next(); - - function listen() { - req.on('data', function(chunk) { - received += Buffer.isBuffer(chunk) - ? chunk.length : - Buffer.byteLength(chunk); - - if (received > bytes) req.destroy(); - }); - }; - }; -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/middleware/logger.js b/node_modules/express/node_modules/connect/lib/middleware/logger.js deleted file mode 100644 index fba43e411..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/logger.js +++ /dev/null @@ -1,342 +0,0 @@ -/*! - * Connect - logger - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var bytes = require('bytes'); - -/*! - * Log buffer. - */ - -var buf = []; - -/*! - * Default log buffer duration. - */ - -var defaultBufferDuration = 1000; - -/** - * Logger: - * - * Log requests with the given `options` or a `format` string. - * - * Options: - * - * - `format` Format string, see below for tokens - * - `stream` Output stream, defaults to _stdout_ - * - `buffer` Buffer duration, defaults to 1000ms when _true_ - * - `immediate` Write log line on request instead of response (for response times) - * - * Tokens: - * - * - `:req[header]` ex: `:req[Accept]` - * - `:res[header]` ex: `:res[Content-Length]` - * - `:http-version` - * - `:response-time` - * - `:remote-addr` - * - `:date` - * - `:method` - * - `:url` - * - `:referrer` - * - `:user-agent` - * - `:status` - * - * Formats: - * - * Pre-defined formats that ship with connect: - * - * - `default` ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"' - * - `short` ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms' - * - `tiny` ':method :url :status :res[content-length] - :response-time ms' - * - `dev` concise output colored by response status for development use - * - * Examples: - * - * connect.logger() // default - * connect.logger('short') - * connect.logger('tiny') - * connect.logger({ immediate: true, format: 'dev' }) - * connect.logger(':method :url - :referrer') - * connect.logger(':req[content-type] -> :res[content-type]') - * connect.logger(function(tokens, req, res){ return 'some format string' }) - * - * Defining Tokens: - * - * To define a token, simply invoke `connect.logger.token()` with the - * name and a callback function. The value returned is then available - * as ":type" in this case. - * - * connect.logger.token('type', function(req, res){ return req.headers['content-type']; }) - * - * Defining Formats: - * - * All default formats are defined this way, however it's public API as well: - * - * connect.logger.format('name', 'string or function') - * - * @param {String|Function|Object} format or options - * @return {Function} - * @api public - */ - -exports = module.exports = function logger(options) { - if ('object' == typeof options) { - options = options || {}; - } else if (options) { - options = { format: options }; - } else { - options = {}; - } - - // output on request instead of response - var immediate = options.immediate; - - // format name - var fmt = exports[options.format] || options.format || exports.default; - - // compile format - if ('function' != typeof fmt) fmt = compile(fmt); - - // options - var stream = options.stream || process.stdout - , buffer = options.buffer; - - // buffering support - if (buffer) { - var realStream = stream - , interval = 'number' == typeof buffer - ? buffer - : defaultBufferDuration; - - // flush interval - setInterval(function(){ - if (buf.length) { - realStream.write(buf.join('')); - buf.length = 0; - } - }, interval); - - // swap the stream - stream = { - write: function(str){ - buf.push(str); - } - }; - } - - return function logger(req, res, next) { - var sock = req.socket; - req._startTime = new Date; - req._remoteAddress = sock.socket ? sock.socket.remoteAddress : sock.remoteAddress; - - function logRequest(){ - res.removeListener('finish', logRequest); - res.removeListener('close', logRequest); - var line = fmt(exports, req, res); - if (null == line) return; - stream.write(line + '\n'); - }; - - // immediate - if (immediate) { - logRequest(); - // proxy end to output logging - } else { - res.on('finish', logRequest); - res.on('close', logRequest); - } - - - next(); - }; -}; - -/** - * Compile `fmt` into a function. - * - * @param {String} fmt - * @return {Function} - * @api private - */ - -function compile(fmt) { - fmt = fmt.replace(/"/g, '\\"'); - var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg){ - return '"\n + (tokens["' + name + '"](req, res, "' + arg + '") || "-") + "'; - }) + '";' - return new Function('tokens, req, res', js); -}; - -/** - * Define a token function with the given `name`, - * and callback `fn(req, res)`. - * - * @param {String} name - * @param {Function} fn - * @return {Object} exports for chaining - * @api public - */ - -exports.token = function(name, fn) { - exports[name] = fn; - return this; -}; - -/** - * Define a `fmt` with the given `name`. - * - * @param {String} name - * @param {String|Function} fmt - * @return {Object} exports for chaining - * @api public - */ - -exports.format = function(name, str){ - exports[name] = str; - return this; -}; - -/** - * Default format. - */ - -exports.format('default', ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'); - -/** - * Short format. - */ - -exports.format('short', ':remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'); - -/** - * Tiny format. - */ - -exports.format('tiny', ':method :url :status :res[content-length] - :response-time ms'); - -/** - * dev (colored) - */ - -exports.format('dev', function(tokens, req, res){ - var status = res.statusCode - , len = parseInt(res.getHeader('Content-Length'), 10) - , color = 32; - - if (status >= 500) color = 31 - else if (status >= 400) color = 33 - else if (status >= 300) color = 36; - - len = isNaN(len) - ? '' - : len = ' - ' + bytes(len); - - return '\x1b[90m' + req.method - + ' ' + req.originalUrl + ' ' - + '\x1b[' + color + 'm' + res.statusCode - + ' \x1b[90m' - + (new Date - req._startTime) - + 'ms' + len - + '\x1b[0m'; -}); - -/** - * request url - */ - -exports.token('url', function(req){ - return req.originalUrl || req.url; -}); - -/** - * request method - */ - -exports.token('method', function(req){ - return req.method; -}); - -/** - * response time in milliseconds - */ - -exports.token('response-time', function(req){ - return String(Date.now() - req._startTime); -}); - -/** - * UTC date - */ - -exports.token('date', function(){ - return new Date().toUTCString(); -}); - -/** - * response status code - */ - -exports.token('status', function(req, res){ - return res.headerSent ? res.statusCode : null; -}); - -/** - * normalized referrer - */ - -exports.token('referrer', function(req){ - return req.headers['referer'] || req.headers['referrer']; -}); - -/** - * remote address - */ - -exports.token('remote-addr', function(req){ - if (req.ip) return req.ip; - if (req._remoteAddress) return req._remoteAddress; - var sock = req.socket; - if (sock.socket) return sock.socket.remoteAddress; - return sock.remoteAddress; -}); - -/** - * HTTP version - */ - -exports.token('http-version', function(req){ - return req.httpVersionMajor + '.' + req.httpVersionMinor; -}); - -/** - * UA string - */ - -exports.token('user-agent', function(req){ - return req.headers['user-agent']; -}); - -/** - * request header - */ - -exports.token('req', function(req, res, field){ - return req.headers[field.toLowerCase()]; -}); - -/** - * response header - */ - -exports.token('res', function(req, res, field){ - return (res._headers || {})[field.toLowerCase()]; -}); - diff --git a/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js b/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js deleted file mode 100644 index a729d136c..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js +++ /dev/null @@ -1,58 +0,0 @@ -/*! - * Connect - methodOverride - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var methods = require('methods'); - -/** - * Method Override: - * - * Provides faux HTTP method support. - * - * Pass an optional `key` to use when checking for - * a method override, otherwise defaults to _\_method_. - * The original method is available via `req.originalMethod`. - * - * @param {String} key - * @return {Function} - * @api public - */ - -module.exports = function methodOverride(key){ - key = key || "_method"; - return function methodOverride(req, res, next) { - var method; - req.originalMethod = req.originalMethod || req.method; - - // req.body - if (req.body && typeof req.body === 'object' && key in req.body) { - method = req.body[key].toLowerCase(); - delete req.body[key]; - } - - // check X-HTTP-Method-Override - if (req.headers['x-http-method-override']) { - method = req.headers['x-http-method-override'].toLowerCase(); - } - - // replace - if (supports(method)) req.method = method.toUpperCase(); - - next(); - }; -}; - -/** - * Check if node supports `method`. - */ - -function supports(method) { - return ~methods.indexOf(method); -} diff --git a/node_modules/express/node_modules/connect/lib/middleware/multipart.js b/node_modules/express/node_modules/connect/lib/middleware/multipart.js deleted file mode 100644 index 8bf663892..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/multipart.js +++ /dev/null @@ -1,171 +0,0 @@ -/*! - * Connect - multipart - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var multiparty = require('multiparty') - , _limit = require('./limit') - , utils = require('../utils') - , qs = require('qs'); - -/** - * Multipart: - * - * Status: Deprecated. The multipart parser will be removed in Connect 3.0. - * Please use one of the following parsers/middleware directly: - * - * - [formidable](https://github.com/felixge/node-formidable) - * - [connect-multiparty](https://github.com/superjoe30/connect-multiparty) or [multiparty] - * - [connect-busboy](https://github.com/mscdex/connect-busboy) or [busboy](https://github.com/mscdex/busboy) - * - * Parse multipart/form-data request bodies, - * providing the parsed object as `req.body` - * and `req.files`. - * - * Configuration: - * - * The options passed are merged with [multiparty](https://github.com/superjoe30/node-multiparty)'s - * `Form` object, allowing you to configure the upload directory, - * size limits, etc. For example if you wish to change the upload dir do the following. - * - * app.use(connect.multipart({ uploadDir: path })); - * - * Options: - * - * - `limit` byte limit defaulting to [100mb] - * - `defer` defers processing and exposes the multiparty form object as `req.form`. - * `next()` is called without waiting for the form's "end" event. - * This option is useful if you need to bind to the "progress" or "part" events, for example. - * - * Temporary Files: - * - * By default temporary files are used, stored in `os.tmpDir()`. These - * are not automatically garbage collected, you are in charge of moving them - * or deleting them. When `defer` is not used and these files are created you - * may refernce them via the `req.files` object. - * - * req.files.images.forEach(function(file){ - * console.log(' uploaded : %s %skb : %s', file.originalFilename, file.size / 1024 | 0, file.path); - * }); - * - * It is highly recommended to monitor and clean up tempfiles in any production - * environment, you may use tools like [reap](https://github.com/visionmedia/reap) - * to do so. - * - * Streaming: - * - * When `defer` is used files are _not_ streamed to tmpfiles, you may - * access them via the "part" events and stream them accordingly: - * - * req.form.on('part', function(part){ - * // transfer to s3 etc - * console.log('upload %s %s', part.name, part.filename); - * var out = fs.createWriteStream('/tmp/' + part.filename); - * part.pipe(out); - * }); - * - * req.form.on('close', function(){ - * res.end('uploaded!'); - * }); - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - options = options || {}; - - if (process.env.NODE_ENV !== 'test') { - console.warn('connect.multipart() will be removed in connect 3.0'); - console.warn('visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives'); - } - - var limit = _limit(options.limit || '100mb'); - - return function multipart(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - req.files = req.files || {}; - - if (!utils.hasBody(req)) return next(); - - // ignore GET - if ('GET' == req.method || 'HEAD' == req.method) return next(); - - // check Content-Type - if ('multipart/form-data' != utils.mime(req)) return next(); - - // flag as parsed - req._body = true; - - // parse - limit(req, res, function(err){ - if (err) return next(err); - - var form = new multiparty.Form(options) - , data = {} - , files = {} - , done; - - Object.keys(options).forEach(function(key){ - form[key] = options[key]; - }); - - function ondata(name, val, data){ - if (Array.isArray(data[name])) { - data[name].push(val); - } else if (data[name]) { - data[name] = [data[name], val]; - } else { - data[name] = val; - } - } - - form.on('field', function(name, val){ - ondata(name, val, data); - }); - - if (!options.defer) { - form.on('file', function(name, val){ - val.name = val.originalFilename; - val.type = val.headers['content-type'] || null; - ondata(name, val, files); - }); - } - - form.on('error', function(err){ - if (!options.defer) { - err.status = 400; - next(err); - } - done = true; - }); - - form.on('close', function(){ - if (done) return; - try { - req.body = qs.parse(data); - req.files = qs.parse(files); - } catch (err) { - form.emit('error', err); - return; - } - if (!options.defer) next(); - }); - - form.parse(req); - - if (options.defer) { - req.form = form; - next(); - } - }); - } -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/query.js b/node_modules/express/node_modules/connect/lib/middleware/query.js deleted file mode 100644 index f0fb50fc5..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/query.js +++ /dev/null @@ -1,47 +0,0 @@ -/*! - * Connect - query - * Copyright(c) 2011 TJ Holowaychuk - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var qs = require('qs') - , parse = require('../utils').parseUrl; - -/** - * Query: - * - * Automatically parse the query-string when available, - * populating the `req.query` object using - * [qs](https://github.com/visionmedia/node-querystring). - * - * Examples: - * - * connect() - * .use(connect.query()) - * .use(function(req, res){ - * res.end(JSON.stringify(req.query)); - * }); - * - * The `options` passed are provided to qs.parse function. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function query(options){ - return function query(req, res, next){ - if (!req.query) { - req.query = ~req.url.indexOf('?') - ? qs.parse(parse(req).query, options) - : {}; - } - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/responseTime.js b/node_modules/express/node_modules/connect/lib/middleware/responseTime.js deleted file mode 100644 index 62abc0494..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/responseTime.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Connect - responseTime - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Reponse time: - * - * Adds the `X-Response-Time` header displaying the response - * duration in milliseconds. - * - * @return {Function} - * @api public - */ - -module.exports = function responseTime(){ - return function(req, res, next){ - var start = new Date; - - if (res._responseTime) return next(); - res._responseTime = true; - - res.on('header', function(){ - var duration = new Date - start; - res.setHeader('X-Response-Time', duration + 'ms'); - }); - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session.js b/node_modules/express/node_modules/connect/lib/middleware/session.js deleted file mode 100644 index 128bc5915..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session.js +++ /dev/null @@ -1,358 +0,0 @@ -/*! - * Connect - session - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Session = require('./session/session') - , debug = require('debug')('connect:session') - , MemoryStore = require('./session/memory') - , signature = require('cookie-signature') - , Cookie = require('./session/cookie') - , Store = require('./session/store') - , utils = require('./../utils') - , uid = require('uid2') - , crc32 = require('buffer-crc32') - , parse = require('url').parse; - -// environment - -var env = process.env.NODE_ENV; - -/** - * Expose the middleware. - */ - -exports = module.exports = session; - -/** - * Expose constructors. - */ - -exports.Store = Store; -exports.Cookie = Cookie; -exports.Session = Session; -exports.MemoryStore = MemoryStore; - -/** - * Warning message for `MemoryStore` usage in production. - */ - -var warning = 'Warning: connection.session() MemoryStore is not\n' - + 'designed for a production environment, as it will leak\n' - + 'memory, and will not scale past a single process.'; - -/** - * Session: - * - * Setup session store with the given `options`. - * - * Session data is _not_ saved in the cookie itself, however - * cookies are used, so we must use the [cookieParser()](cookieParser.html) - * middleware _before_ `session()`. - * - * Examples: - * - * connect() - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', key: 'sid', cookie: { secure: true }})) - * - * Options: - * - * - `key` cookie name defaulting to `connect.sid` - * - `store` session store instance - * - `secret` session cookie is signed with this secret to prevent tampering - * - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }` - * - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto") - * - * Cookie option: - * - * By default `cookie.maxAge` is `null`, meaning no "expires" parameter is set - * so the cookie becomes a browser-session cookie. When the user closes the - * browser the cookie (and session) will be removed. - * - * ## req.session - * - * To store or access session data, simply use the request property `req.session`, - * which is (generally) serialized as JSON by the store, so nested objects - * are typically fine. For example below is a user-specific view counter: - * - * connect() - * .use(connect.favicon()) - * .use(connect.cookieParser()) - * .use(connect.session({ secret: 'keyboard cat', cookie: { maxAge: 60000 }})) - * .use(function(req, res, next){ - * var sess = req.session; - * if (sess.views) { - * res.setHeader('Content-Type', 'text/html'); - * res.write('

    views: ' + sess.views + '

    '); - * res.write('

    expires in: ' + (sess.cookie.maxAge / 1000) + 's

    '); - * res.end(); - * sess.views++; - * } else { - * sess.views = 1; - * res.end('welcome to the session demo. refresh!'); - * } - * } - * )).listen(3000); - * - * ## Session#regenerate() - * - * To regenerate the session simply invoke the method, once complete - * a new SID and `Session` instance will be initialized at `req.session`. - * - * req.session.regenerate(function(err){ - * // will have a new session here - * }); - * - * ## Session#destroy() - * - * Destroys the session, removing `req.session`, will be re-generated next request. - * - * req.session.destroy(function(err){ - * // cannot access session here - * }); - * - * ## Session#reload() - * - * Reloads the session data. - * - * req.session.reload(function(err){ - * // session updated - * }); - * - * ## Session#save() - * - * Save the session. - * - * req.session.save(function(err){ - * // session saved - * }); - * - * ## Session#touch() - * - * Updates the `.maxAge` property. Typically this is - * not necessary to call, as the session middleware does this for you. - * - * ## Session#cookie - * - * Each session has a unique cookie object accompany it. This allows - * you to alter the session cookie per visitor. For example we can - * set `req.session.cookie.expires` to `false` to enable the cookie - * to remain for only the duration of the user-agent. - * - * ## Session#maxAge - * - * Alternatively `req.session.cookie.maxAge` will return the time - * remaining in milliseconds, which we may also re-assign a new value - * to adjust the `.expires` property appropriately. The following - * are essentially equivalent - * - * var hour = 3600000; - * req.session.cookie.expires = new Date(Date.now() + hour); - * req.session.cookie.maxAge = hour; - * - * For example when `maxAge` is set to `60000` (one minute), and 30 seconds - * has elapsed it will return `30000` until the current request has completed, - * at which time `req.session.touch()` is called to reset `req.session.maxAge` - * to its original value. - * - * req.session.cookie.maxAge; - * // => 30000 - * - * Session Store Implementation: - * - * Every session store _must_ implement the following methods - * - * - `.get(sid, callback)` - * - `.set(sid, session, callback)` - * - `.destroy(sid, callback)` - * - * Recommended methods include, but are not limited to: - * - * - `.length(callback)` - * - `.clear(callback)` - * - * For an example implementation view the [connect-redis](http://github.com/visionmedia/connect-redis) repo. - * - * @param {Object} options - * @return {Function} - * @api public - */ - -function session(options){ - var options = options || {} - , key = options.key || 'connect.sid' - , store = options.store || new MemoryStore - , cookie = options.cookie || {} - , trustProxy = options.proxy - , storeReady = true - , rollingSessions = options.rolling || false; - - // notify user that this store is not - // meant for a production environment - if ('production' == env && store instanceof MemoryStore) { - console.warn(warning); - } - - // generates the new session - store.generate = function(req){ - req.sessionID = uid(24); - req.session = new Session(req); - req.session.cookie = new Cookie(cookie); - }; - - store.on('disconnect', function(){ storeReady = false; }); - store.on('connect', function(){ storeReady = true; }); - - return function session(req, res, next) { - // self-awareness - if (req.session) return next(); - - // Handle connection as if there is no session if - // the store has temporarily disconnected etc - if (!storeReady) return debug('store is disconnected'), next(); - - // pathname mismatch - var originalPath = parse(req.originalUrl).pathname; - if (0 != originalPath.indexOf(cookie.path || '/')) return next(); - - // backwards compatibility for signed cookies - // req.secret is passed from the cookie parser middleware - var secret = options.secret || req.secret; - - // ensure secret is available or bail - if (!secret) throw new Error('`secret` option required for sessions'); - - var originalHash - , originalId; - - // expose store - req.sessionStore = store; - - // grab the session cookie value and check the signature - var rawCookie = req.cookies[key]; - - // get signedCookies for backwards compat with signed cookies - var unsignedCookie = req.signedCookies[key]; - - if (!unsignedCookie && rawCookie) { - unsignedCookie = utils.parseSignedCookie(rawCookie, secret); - } - - // set-cookie - res.on('header', function(){ - if (!req.session) return; - var cookie = req.session.cookie - , proto = (req.headers['x-forwarded-proto'] || '').split(',')[0].toLowerCase().trim() - , tls = req.connection.encrypted || (trustProxy && 'https' == proto) - , isNew = unsignedCookie != req.sessionID; - - // only send secure cookies via https - if (cookie.secure && !tls) return debug('not secured'); - - // in case of rolling session, always reset the cookie - if (!rollingSessions) { - - // browser-session length cookie - if (null == cookie.expires) { - if (!isNew) return debug('already set browser-session cookie'); - // compare hashes and ids - } else if (originalHash == hash(req.session) && originalId == req.session.id) { - return debug('unmodified session'); - } - - } - - var val = 's:' + signature.sign(req.sessionID, secret); - val = cookie.serialize(key, val); - debug('set-cookie %s', val); - res.setHeader('Set-Cookie', val); - }); - - // proxy end() to commit the session - var end = res.end; - res.end = function(data, encoding){ - res.end = end; - if (!req.session) return res.end(data, encoding); - debug('saving'); - req.session.resetMaxAge(); - req.session.save(function(err){ - if (err) console.error(err.stack); - debug('saved'); - res.end(data, encoding); - }); - }; - - // generate the session - function generate() { - store.generate(req); - } - - // get the sessionID from the cookie - req.sessionID = unsignedCookie; - - // generate a session if the browser doesn't send a sessionID - if (!req.sessionID) { - debug('no SID sent, generating session'); - generate(); - next(); - return; - } - - // generate the session object - var pause = utils.pause(req); - debug('fetching %s', req.sessionID); - store.get(req.sessionID, function(err, sess){ - // proxy to resume() events - var _next = next; - next = function(err){ - _next(err); - pause.resume(); - }; - - // error handling - if (err) { - debug('error %j', err); - if ('ENOENT' == err.code) { - generate(); - next(); - } else { - next(err); - } - // no session - } else if (!sess) { - debug('no session found'); - generate(); - next(); - // populate req.session - } else { - debug('session found'); - store.createSession(req, sess); - originalId = req.sessionID; - originalHash = hash(sess); - next(); - } - }); - }; -}; - -/** - * Hash the given `sess` object omitting changes - * to `.cookie`. - * - * @param {Object} sess - * @return {String} - * @api private - */ - -function hash(sess) { - return crc32.signed(JSON.stringify(sess, function(key, val){ - if ('cookie' != key) return val; - })); -} diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js b/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js deleted file mode 100644 index 3125410d8..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/cookie.js +++ /dev/null @@ -1,128 +0,0 @@ - -/*! - * Connect - session - Cookie - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../../utils') - , cookie = require('cookie'); - -/** - * Initialize a new `Cookie` with the given `options`. - * - * @param {IncomingMessage} req - * @param {Object} options - * @api private - */ - -var Cookie = module.exports = function Cookie(options) { - this.path = '/'; - this.maxAge = null; - this.httpOnly = true; - if (options) utils.merge(this, options); - this.originalMaxAge = undefined == this.originalMaxAge - ? this.maxAge - : this.originalMaxAge; -}; - -/*! - * Prototype. - */ - -Cookie.prototype = { - - /** - * Set expires `date`. - * - * @param {Date} date - * @api public - */ - - set expires(date) { - this._expires = date; - this.originalMaxAge = this.maxAge; - }, - - /** - * Get expires `date`. - * - * @return {Date} - * @api public - */ - - get expires() { - return this._expires; - }, - - /** - * Set expires via max-age in `ms`. - * - * @param {Number} ms - * @api public - */ - - set maxAge(ms) { - this.expires = 'number' == typeof ms - ? new Date(Date.now() + ms) - : ms; - }, - - /** - * Get expires max-age in `ms`. - * - * @return {Number} - * @api public - */ - - get maxAge() { - return this.expires instanceof Date - ? this.expires.valueOf() - Date.now() - : this.expires; - }, - - /** - * Return cookie data object. - * - * @return {Object} - * @api private - */ - - get data() { - return { - originalMaxAge: this.originalMaxAge - , expires: this._expires - , secure: this.secure - , httpOnly: this.httpOnly - , domain: this.domain - , path: this.path - } - }, - - /** - * Return a serialized cookie string. - * - * @return {String} - * @api public - */ - - serialize: function(name, val){ - return cookie.serialize(name, val, this.data); - }, - - /** - * Return JSON representation of this cookie. - * - * @return {Object} - * @api private - */ - - toJSON: function(){ - return this.data; - } -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/memory.js b/node_modules/express/node_modules/connect/lib/middleware/session/memory.js deleted file mode 100644 index fb9393928..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/memory.js +++ /dev/null @@ -1,129 +0,0 @@ - -/*! - * Connect - session - MemoryStore - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Store = require('./store'); - -/** - * Initialize a new `MemoryStore`. - * - * @api public - */ - -var MemoryStore = module.exports = function MemoryStore() { - this.sessions = {}; -}; - -/** - * Inherit from `Store.prototype`. - */ - -MemoryStore.prototype.__proto__ = Store.prototype; - -/** - * Attempt to fetch session by the given `sid`. - * - * @param {String} sid - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.get = function(sid, fn){ - var self = this; - process.nextTick(function(){ - var expires - , sess = self.sessions[sid]; - if (sess) { - sess = JSON.parse(sess); - expires = 'string' == typeof sess.cookie.expires - ? new Date(sess.cookie.expires) - : sess.cookie.expires; - if (!expires || new Date < expires) { - fn(null, sess); - } else { - self.destroy(sid, fn); - } - } else { - fn(); - } - }); -}; - -/** - * Commit the given `sess` object associated with the given `sid`. - * - * @param {String} sid - * @param {Session} sess - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.set = function(sid, sess, fn){ - var self = this; - process.nextTick(function(){ - self.sessions[sid] = JSON.stringify(sess); - fn && fn(); - }); -}; - -/** - * Destroy the session associated with the given `sid`. - * - * @param {String} sid - * @api public - */ - -MemoryStore.prototype.destroy = function(sid, fn){ - var self = this; - process.nextTick(function(){ - delete self.sessions[sid]; - fn && fn(); - }); -}; - -/** - * Invoke the given callback `fn` with all active sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.all = function(fn){ - var arr = [] - , keys = Object.keys(this.sessions); - for (var i = 0, len = keys.length; i < len; ++i) { - arr.push(this.sessions[keys[i]]); - } - fn(null, arr); -}; - -/** - * Clear all sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.clear = function(fn){ - this.sessions = {}; - fn && fn(); -}; - -/** - * Fetch number of sessions. - * - * @param {Function} fn - * @api public - */ - -MemoryStore.prototype.length = function(fn){ - fn(null, Object.keys(this.sessions).length); -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/session.js b/node_modules/express/node_modules/connect/lib/middleware/session/session.js deleted file mode 100644 index 0dd4b4007..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/session.js +++ /dev/null @@ -1,116 +0,0 @@ - -/*! - * Connect - session - Session - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../../utils'); - -/** - * Create a new `Session` with the given request and `data`. - * - * @param {IncomingRequest} req - * @param {Object} data - * @api private - */ - -var Session = module.exports = function Session(req, data) { - Object.defineProperty(this, 'req', { value: req }); - Object.defineProperty(this, 'id', { value: req.sessionID }); - if ('object' == typeof data) utils.merge(this, data); -}; - -/** - * Update reset `.cookie.maxAge` to prevent - * the cookie from expiring when the - * session is still active. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.touch = function(){ - return this.resetMaxAge(); -}; - -/** - * Reset `.maxAge` to `.originalMaxAge`. - * - * @return {Session} for chaining - * @api public - */ - -Session.prototype.resetMaxAge = function(){ - this.cookie.maxAge = this.cookie.originalMaxAge; - return this; -}; - -/** - * Save the session data with optional callback `fn(err)`. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.save = function(fn){ - this.req.sessionStore.set(this.id, this, fn || function(){}); - return this; -}; - -/** - * Re-loads the session data _without_ altering - * the maxAge properties. Invokes the callback `fn(err)`, - * after which time if no exception has occurred the - * `req.session` property will be a new `Session` object, - * although representing the same session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.reload = function(fn){ - var req = this.req - , store = this.req.sessionStore; - store.get(this.id, function(err, sess){ - if (err) return fn(err); - if (!sess) return fn(new Error('failed to load session')); - store.createSession(req, sess); - fn(); - }); - return this; -}; - -/** - * Destroy `this` session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.destroy = function(fn){ - delete this.req.session; - this.req.sessionStore.destroy(this.id, fn); - return this; -}; - -/** - * Regenerate this request's session. - * - * @param {Function} fn - * @return {Session} for chaining - * @api public - */ - -Session.prototype.regenerate = function(fn){ - this.req.sessionStore.regenerate(this.req, fn); - return this; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/session/store.js b/node_modules/express/node_modules/connect/lib/middleware/session/store.js deleted file mode 100644 index 54294cbdf..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/session/store.js +++ /dev/null @@ -1,84 +0,0 @@ - -/*! - * Connect - session - Store - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , Session = require('./session') - , Cookie = require('./cookie'); - -/** - * Initialize abstract `Store`. - * - * @api private - */ - -var Store = module.exports = function Store(options){}; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Store.prototype.__proto__ = EventEmitter.prototype; - -/** - * Re-generate the given requests's session. - * - * @param {IncomingRequest} req - * @return {Function} fn - * @api public - */ - -Store.prototype.regenerate = function(req, fn){ - var self = this; - this.destroy(req.sessionID, function(err){ - self.generate(req); - fn(err); - }); -}; - -/** - * Load a `Session` instance via the given `sid` - * and invoke the callback `fn(err, sess)`. - * - * @param {String} sid - * @param {Function} fn - * @api public - */ - -Store.prototype.load = function(sid, fn){ - var self = this; - this.get(sid, function(err, sess){ - if (err) return fn(err); - if (!sess) return fn(); - var req = { sessionID: sid, sessionStore: self }; - sess = self.createSession(req, sess); - fn(null, sess); - }); -}; - -/** - * Create session from JSON `sess` data. - * - * @param {IncomingRequest} req - * @param {Object} sess - * @return {Session} - * @api private - */ - -Store.prototype.createSession = function(req, sess){ - var expires = sess.cookie.expires - , orig = sess.cookie.originalMaxAge; - sess.cookie = new Cookie(sess.cookie); - if ('string' == typeof expires) sess.cookie.expires = new Date(expires); - sess.cookie.originalMaxAge = orig; - req.session = new Session(req, sess); - return req.session; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/static.js b/node_modules/express/node_modules/connect/lib/middleware/static.js deleted file mode 100644 index 67970dab4..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/static.js +++ /dev/null @@ -1,102 +0,0 @@ -/*! - * Connect - static - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var send = require('send') - , utils = require('../utils') - , parse = utils.parseUrl - , url = require('url'); - -/** - * Static: - * - * Static file server with the given `root` path. - * - * Examples: - * - * var oneDay = 86400000; - * - * connect() - * .use(connect.static(__dirname + '/public')) - * - * connect() - * .use(connect.static(__dirname + '/public', { maxAge: oneDay })) - * - * Options: - * - * - `maxAge` Browser cache maxAge in milliseconds. defaults to 0 - * - `hidden` Allow transfer of hidden files. defaults to false - * - `redirect` Redirect to trailing "/" when the pathname is a dir. defaults to true - * - `index` Default file name, defaults to 'index.html' - * - * @param {String} root - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(root, options){ - options = options || {}; - - // root required - if (!root) throw new Error('static() root path required'); - - // default redirect - var redirect = false !== options.redirect; - - return function staticMiddleware(req, res, next) { - if ('GET' != req.method && 'HEAD' != req.method) return next(); - var originalUrl = url.parse(req.originalUrl); - var path = parse(req).pathname; - var pause = utils.pause(req); - - if (path == '/' && originalUrl.pathname[originalUrl.pathname.length - 1] != '/') { - return directory(); - } - - function resume() { - next(); - pause.resume(); - } - - function directory() { - if (!redirect) return resume(); - var target; - originalUrl.pathname += '/'; - target = url.format(originalUrl); - res.statusCode = 303; - res.setHeader('Location', target); - res.end('Redirecting to ' + utils.escape(target)); - } - - function error(err) { - if (404 == err.status) return resume(); - next(err); - } - - send(req, path) - .maxage(options.maxAge || 0) - .root(root) - .index(options.index || 'index.html') - .hidden(options.hidden) - .on('error', error) - .on('directory', directory) - .pipe(res); - }; -}; - -/** - * Expose mime module. - * - * If you wish to extend the mime table use this - * reference to the "mime" module in the npm registry. - */ - -exports.mime = send.mime; diff --git a/node_modules/express/node_modules/connect/lib/middleware/staticCache.js b/node_modules/express/node_modules/connect/lib/middleware/staticCache.js deleted file mode 100644 index 66d3c1f62..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/staticCache.js +++ /dev/null @@ -1,238 +0,0 @@ - -/*! - * Connect - staticCache - * Copyright(c) 2011 Sencha Inc. - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils') - , Cache = require('../cache') - , fresh = require('fresh'); - -/** - * Static cache: - * - * Status: Deprecated. This middleware will be removed in - * Connect 3.0. You may be interested in: - * - * - [st](https://github.com/isaacs/st) - * - * Enables a memory cache layer on top of - * the `static()` middleware, serving popular - * static files. - * - * By default a maximum of 128 objects are - * held in cache, with a max of 256k each, - * totalling ~32mb. - * - * A Least-Recently-Used (LRU) cache algo - * is implemented through the `Cache` object, - * simply rotating cache objects as they are - * hit. This means that increasingly popular - * objects maintain their positions while - * others get shoved out of the stack and - * garbage collected. - * - * Benchmarks: - * - * static(): 2700 rps - * node-static: 5300 rps - * static() + staticCache(): 7500 rps - * - * Options: - * - * - `maxObjects` max cache objects [128] - * - `maxLength` max cache object length 256kb - * - * @param {Object} options - * @return {Function} - * @api public - */ - -module.exports = function staticCache(options){ - var options = options || {} - , cache = new Cache(options.maxObjects || 128) - , maxlen = options.maxLength || 1024 * 256; - - if (process.env.NODE_ENV !== 'test') { - console.warn('connect.staticCache() is deprecated and will be removed in 3.0'); - console.warn('use varnish or similar reverse proxy caches.'); - } - - return function staticCache(req, res, next){ - var key = cacheKey(req) - , ranges = req.headers.range - , hasCookies = req.headers.cookie - , hit = cache.get(key); - - // cache static - // TODO: change from staticCache() -> cache() - // and make this work for any request - req.on('static', function(stream){ - var headers = res._headers - , cc = utils.parseCacheControl(headers['cache-control'] || '') - , contentLength = headers['content-length'] - , hit; - - // dont cache set-cookie responses - if (headers['set-cookie']) return hasCookies = true; - - // dont cache when cookies are present - if (hasCookies) return; - - // ignore larger files - if (!contentLength || contentLength > maxlen) return; - - // don't cache partial files - if (headers['content-range']) return; - - // dont cache items we shouldn't be - // TODO: real support for must-revalidate / no-cache - if ( cc['no-cache'] - || cc['no-store'] - || cc['private'] - || cc['must-revalidate']) return; - - // if already in cache then validate - if (hit = cache.get(key)){ - if (headers.etag == hit[0].etag) { - hit[0].date = new Date; - return; - } else { - cache.remove(key); - } - } - - // validation notifiactions don't contain a steam - if (null == stream) return; - - // add the cache object - var arr = []; - - // store the chunks - stream.on('data', function(chunk){ - arr.push(chunk); - }); - - // flag it as complete - stream.on('end', function(){ - var cacheEntry = cache.add(key); - delete headers['x-cache']; // Clean up (TODO: others) - cacheEntry.push(200); - cacheEntry.push(headers); - cacheEntry.push.apply(cacheEntry, arr); - }); - }); - - if (req.method == 'GET' || req.method == 'HEAD') { - if (ranges) { - next(); - } else if (!hasCookies && hit && !mustRevalidate(req, hit)) { - res.setHeader('X-Cache', 'HIT'); - respondFromCache(req, res, hit); - } else { - res.setHeader('X-Cache', 'MISS'); - next(); - } - } else { - next(); - } - } -}; - -/** - * Respond with the provided cached value. - * TODO: Assume 200 code, that's iffy. - * - * @param {Object} req - * @param {Object} res - * @param {Object} cacheEntry - * @return {String} - * @api private - */ - -function respondFromCache(req, res, cacheEntry) { - var status = cacheEntry[0] - , headers = utils.merge({}, cacheEntry[1]) - , content = cacheEntry.slice(2); - - headers.age = (new Date - new Date(headers.date)) / 1000 || 0; - - switch (req.method) { - case 'HEAD': - res.writeHead(status, headers); - res.end(); - break; - case 'GET': - if (utils.conditionalGET(req) && fresh(req.headers, headers)) { - headers['content-length'] = 0; - res.writeHead(304, headers); - res.end(); - } else { - res.writeHead(status, headers); - - function write() { - while (content.length) { - if (false === res.write(content.shift())) { - res.once('drain', write); - return; - } - } - res.end(); - } - - write(); - } - break; - default: - // This should never happen. - res.writeHead(500, ''); - res.end(); - } -} - -/** - * Determine whether or not a cached value must be revalidated. - * - * @param {Object} req - * @param {Object} cacheEntry - * @return {String} - * @api private - */ - -function mustRevalidate(req, cacheEntry) { - var cacheHeaders = cacheEntry[1] - , reqCC = utils.parseCacheControl(req.headers['cache-control'] || '') - , cacheCC = utils.parseCacheControl(cacheHeaders['cache-control'] || '') - , cacheAge = (new Date - new Date(cacheHeaders.date)) / 1000 || 0; - - if ( cacheCC['no-cache'] - || cacheCC['must-revalidate'] - || cacheCC['proxy-revalidate']) return true; - - if (reqCC['no-cache']) return true; - - if (null != reqCC['max-age']) return reqCC['max-age'] < cacheAge; - - if (null != cacheCC['max-age']) return cacheCC['max-age'] < cacheAge; - - return false; -} - -/** - * The key to use in the cache. For now, this is the URL path and query. - * - * 'http://example.com?key=value' -> '/?key=value' - * - * @param {Object} req - * @return {String} - * @api private - */ - -function cacheKey(req) { - return utils.parseUrl(req).path; -} diff --git a/node_modules/express/node_modules/connect/lib/middleware/timeout.js b/node_modules/express/node_modules/connect/lib/middleware/timeout.js deleted file mode 100644 index 5496c024e..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/timeout.js +++ /dev/null @@ -1,55 +0,0 @@ -/*! - * Connect - timeout - * Ported from https://github.com/LearnBoost/connect-timeout - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var debug = require('debug')('connect:timeout'); - -/** - * Timeout: - * - * Times out the request in `ms`, defaulting to `5000`. The - * method `req.clearTimeout()` is added to revert this behaviour - * programmatically within your application's middleware, routes, etc. - * - * The timeout error is passed to `next()` so that you may customize - * the response behaviour. This error has the `.timeout` property as - * well as `.status == 503`. - * - * @param {Number} ms - * @return {Function} - * @api public - */ - -module.exports = function timeout(ms) { - ms = ms || 5000; - - return function(req, res, next) { - var id = setTimeout(function(){ - req.emit('timeout', ms); - }, ms); - - req.on('timeout', function(){ - if (res.headerSent) return debug('response started, cannot timeout'); - var err = new Error('Response timeout'); - err.timeout = ms; - err.status = 503; - next(err); - }); - - req.clearTimeout = function(){ - clearTimeout(id); - }; - - res.on('header', function(){ - clearTimeout(id); - }); - - next(); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js b/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js deleted file mode 100644 index ebc6f5fc4..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/urlencoded.js +++ /dev/null @@ -1,77 +0,0 @@ - -/*! - * Connect - urlencoded - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('../utils'); -var getBody = require('raw-body'); -var qs = require('qs'); - -/** - * Urlencoded: - * - * Parse x-ww-form-urlencoded request bodies, - * providing the parsed object as `req.body` using - * [qs](https://github.com/visionmedia/node-querystring). - * - * Options: - * - * - `limit` byte limit [1mb] - * - * @param {Object} options - * @return {Function} - * @api public - */ - -exports = module.exports = function(options){ - options = options || {}; - var verify = typeof options.verify === 'function' && options.verify; - - return function urlencoded(req, res, next) { - if (req._body) return next(); - req.body = req.body || {}; - - if (!utils.hasBody(req)) return next(); - - // check Content-Type - if ('application/x-www-form-urlencoded' != utils.mime(req)) return next(); - - // flag as parsed - req._body = true; - - // parse - getBody(req, { - limit: options.limit || '1mb', - length: req.headers['content-length'], - encoding: 'utf8' - }, function (err, buf) { - if (err) return next(err); - - if (verify) { - try { - verify(req, res, buf) - } catch (err) { - if (!err.status) err.status = 403; - return next(err); - } - } - - try { - req.body = buf.length - ? qs.parse(buf, options) - : {}; - } catch (err){ - err.body = buf; - return next(err); - } - next(); - }) - } -}; diff --git a/node_modules/express/node_modules/connect/lib/middleware/vhost.js b/node_modules/express/node_modules/connect/lib/middleware/vhost.js deleted file mode 100644 index abbb0500a..000000000 --- a/node_modules/express/node_modules/connect/lib/middleware/vhost.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Connect - vhost - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Vhost: - * - * Setup vhost for the given `hostname` and `server`. - * - * connect() - * .use(connect.vhost('foo.com', fooApp)) - * .use(connect.vhost('bar.com', barApp)) - * .use(connect.vhost('*.com', mainApp)) - * - * The `server` may be a Connect server or - * a regular Node `http.Server`. - * - * @param {String} hostname - * @param {Server} server - * @return {Function} - * @api public - */ - -module.exports = function vhost(hostname, server){ - if (!hostname) throw new Error('vhost hostname required'); - if (!server) throw new Error('vhost server required'); - var regexp = new RegExp('^' + hostname.replace(/[^*\w]/g, '\\$&').replace(/[*]/g, '(?:.*?)') + '$', 'i'); - if (server.onvhost) server.onvhost(hostname); - return function vhost(req, res, next){ - if (!req.headers.host) return next(); - var host = req.headers.host.split(':')[0]; - if (!regexp.test(host)) return next(); - if ('function' == typeof server) return server(req, res, next); - server.emit('request', req, res); - }; -}; diff --git a/node_modules/express/node_modules/connect/lib/patch.js b/node_modules/express/node_modules/connect/lib/patch.js deleted file mode 100644 index 22bcbc62c..000000000 --- a/node_modules/express/node_modules/connect/lib/patch.js +++ /dev/null @@ -1,89 +0,0 @@ - -/*! - * Connect - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , res = http.ServerResponse.prototype - , setHeader = res.setHeader - , _renderHeaders = res._renderHeaders - , writeHead = res.writeHead; - -// apply only once - -if (!res._hasConnectPatch) { - - /** - * Provide a public "header sent" flag - * until node does. - * - * @return {Boolean} - * @api public - */ - - res.__defineGetter__('headerSent', function(){ - return this._header; - }); - - /** - * Set header `field` to `val`, special-casing - * the `Set-Cookie` field for multiple support. - * - * @param {String} field - * @param {String} val - * @api public - */ - - res.setHeader = function(field, val){ - var key = field.toLowerCase() - , prev; - - // special-case Set-Cookie - if (this._headers && 'set-cookie' == key) { - if (prev = this.getHeader(field)) { - if (Array.isArray(prev)) { - val = prev.concat(val); - } else if (Array.isArray(val)) { - val = val.concat(prev); - } else { - val = [prev, val]; - } - } - // charset - } else if ('content-type' == key && this.charset) { - val += '; charset=' + this.charset; - } - - return setHeader.call(this, field, val); - }; - - /** - * Proxy to emit "header" event. - */ - - res._renderHeaders = function(){ - if (!this._emittedHeader) this.emit('header'); - this._emittedHeader = true; - return _renderHeaders.call(this); - }; - - res.writeHead = function(statusCode, reasonPhrase, headers){ - if (typeof reasonPhrase === 'object') headers = reasonPhrase; - if (typeof headers === 'object') { - Object.keys(headers).forEach(function(key){ - this.setHeader(key, headers[key]); - }, this); - } - if (!this._emittedHeader) this.emit('header'); - this._emittedHeader = true; - return writeHead.call(this, statusCode, reasonPhrase); - }; - - res._hasConnectPatch = true; -} diff --git a/node_modules/express/node_modules/connect/lib/proto.js b/node_modules/express/node_modules/connect/lib/proto.js deleted file mode 100644 index a945bc28b..000000000 --- a/node_modules/express/node_modules/connect/lib/proto.js +++ /dev/null @@ -1,233 +0,0 @@ -/*! - * Connect - HTTPServer - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , utils = require('./utils') - , debug = require('debug')('connect:dispatcher'); - -// prototype - -var app = module.exports = {}; - -// environment - -var env = process.env.NODE_ENV || 'development'; - -/** - * Utilize the given middleware `handle` to the given `route`, - * defaulting to _/_. This "route" is the mount-point for the - * middleware, when given a value other than _/_ the middleware - * is only effective when that segment is present in the request's - * pathname. - * - * For example if we were to mount a function at _/admin_, it would - * be invoked on _/admin_, and _/admin/settings_, however it would - * not be invoked for _/_, or _/posts_. - * - * Examples: - * - * var app = connect(); - * app.use(connect.favicon()); - * app.use(connect.logger()); - * app.use(connect.static(__dirname + '/public')); - * - * If we wanted to prefix static files with _/public_, we could - * "mount" the `static()` middleware: - * - * app.use('/public', connect.static(__dirname + '/public')); - * - * This api is chainable, so the following is valid: - * - * connect() - * .use(connect.favicon()) - * .use(connect.logger()) - * .use(connect.static(__dirname + '/public')) - * .listen(3000); - * - * @param {String|Function|Server} route, callback or server - * @param {Function|Server} callback or server - * @return {Server} for chaining - * @api public - */ - -app.use = function(route, fn){ - // default route to '/' - if ('string' != typeof route) { - fn = route; - route = '/'; - } - - // wrap sub-apps - if ('function' == typeof fn.handle) { - var server = fn; - fn.route = route; - fn = function(req, res, next){ - server.handle(req, res, next); - }; - } - - // wrap vanilla http.Servers - if (fn instanceof http.Server) { - fn = fn.listeners('request')[0]; - } - - // strip trailing slash - if ('/' == route[route.length - 1]) { - route = route.slice(0, -1); - } - - // add the middleware - debug('use %s %s', route || '/', fn.name || 'anonymous'); - this.stack.push({ route: route, handle: fn }); - - return this; -}; - -/** - * Handle server requests, punting them down - * the middleware stack. - * - * @api private - */ - -app.handle = function(req, res, out) { - var stack = this.stack - , search = 1 + req.url.indexOf('?') - , pathlength = search ? search - 1 : req.url.length - , fqdn = 1 + req.url.substr(0, pathlength).indexOf('://') - , protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : '' - , removed = '' - , slashAdded = false - , index = 0; - - function next(err) { - var layer, path, c; - - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } - - req.url = protohost + removed + req.url.substr(protohost.length); - req.originalUrl = req.originalUrl || req.url; - removed = ''; - - // next callback - layer = stack[index++]; - - // all done - if (!layer || res.headerSent) { - // delegate to parent - if (out) return out(err); - - // unhandled error - if (err) { - // default to 500 - if (res.statusCode < 400) res.statusCode = 500; - debug('default %s', res.statusCode); - - // respect err.status - if (err.status) res.statusCode = err.status; - - // production gets a basic error message - var msg = 'production' == env - ? http.STATUS_CODES[res.statusCode] - : err.stack || err.toString(); - msg = utils.escape(msg); - - // log to stderr in a non-test env - if ('test' != env) console.error(err.stack || err.toString()); - if (res.headerSent) return req.socket.destroy(); - res.setHeader('Content-Type', 'text/html'); - res.setHeader('Content-Length', Buffer.byteLength(msg)); - if ('HEAD' == req.method) return res.end(); - res.end(msg); - } else { - debug('default 404'); - res.statusCode = 404; - res.setHeader('Content-Type', 'text/html'); - if ('HEAD' == req.method) return res.end(); - res.end('Cannot ' + utils.escape(req.method) + ' ' + utils.escape(req.originalUrl) + '\n'); - } - return; - } - - try { - path = utils.parseUrl(req).pathname; - if (undefined == path) path = '/'; - - // skip this layer if the route doesn't match. - if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) return next(err); - - c = path[layer.route.length]; - if (c && '/' != c && '.' != c) return next(err); - - // Call the layer handler - // Trim off the part of the url that matches the route - removed = layer.route; - req.url = protohost + req.url.substr(protohost.length + removed.length); - - // Ensure leading slash - if (!fqdn && '/' != req.url[0]) { - req.url = '/' + req.url; - slashAdded = true; - } - - debug('%s %s : %s', layer.handle.name || 'anonymous', layer.route, req.originalUrl); - var arity = layer.handle.length; - if (err) { - if (arity === 4) { - layer.handle(err, req, res, next); - } else { - next(err); - } - } else if (arity < 4) { - layer.handle(req, res, next); - } else { - next(); - } - } catch (e) { - next(e); - } - } - next(); -}; - -/** - * Listen for connections. - * - * This method takes the same arguments - * as node's `http.Server#listen()`. - * - * HTTP and HTTPS: - * - * If you run your application both as HTTP - * and HTTPS you may wrap them individually, - * since your Connect "server" is really just - * a JavaScript `Function`. - * - * var connect = require('connect') - * , http = require('http') - * , https = require('https'); - * - * var app = connect(); - * - * http.createServer(app).listen(80); - * https.createServer(options, app).listen(443); - * - * @return {http.Server} - * @api public - */ - -app.listen = function(){ - var server = http.createServer(this); - return server.listen.apply(server, arguments); -}; diff --git a/node_modules/express/node_modules/connect/lib/public/directory.html b/node_modules/express/node_modules/connect/lib/public/directory.html deleted file mode 100644 index 8ed8b4ae7..000000000 --- a/node_modules/express/node_modules/connect/lib/public/directory.html +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - listing directory {directory} - - - - - -
    -

    {linked-path}

    - {files} -
    - - \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/lib/public/error.html b/node_modules/express/node_modules/connect/lib/public/error.html deleted file mode 100644 index a6d3fafd8..000000000 --- a/node_modules/express/node_modules/connect/lib/public/error.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - {error} - - - -
    -

    {title}

    -

    {statusCode} {error}

    -
      {stack}
    -
    - - diff --git a/node_modules/express/node_modules/connect/lib/public/favicon.ico b/node_modules/express/node_modules/connect/lib/public/favicon.ico deleted file mode 100644 index 895fc96a7..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/favicon.ico and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/folder.png b/node_modules/express/node_modules/connect/lib/public/icons/folder.png deleted file mode 100644 index 698f3d303..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/folder.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page.png b/node_modules/express/node_modules/connect/lib/public/icons/page.png deleted file mode 100644 index 03ddd799f..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_add.png b/node_modules/express/node_modules/connect/lib/public/icons/page_add.png deleted file mode 100644 index d5bfa0719..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_add.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png b/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png deleted file mode 100644 index 89ee2da07..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_attach.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_code.png b/node_modules/express/node_modules/connect/lib/public/icons/page_code.png deleted file mode 100644 index f7ea90419..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_code.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png b/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png deleted file mode 100644 index 195dc6d6c..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_copy.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png b/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png deleted file mode 100644 index 3141467c6..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_delete.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png b/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png deleted file mode 100644 index 046811ed7..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_edit.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_error.png b/node_modules/express/node_modules/connect/lib/public/icons/page_error.png deleted file mode 100644 index f07f449a4..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_error.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png b/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png deleted file mode 100644 index eb6158eb5..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_excel.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_find.png b/node_modules/express/node_modules/connect/lib/public/icons/page_find.png deleted file mode 100644 index 2f193889f..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_find.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png b/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png deleted file mode 100644 index 8e83281c5..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_gear.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_go.png b/node_modules/express/node_modules/connect/lib/public/icons/page_go.png deleted file mode 100644 index 80fe1ed0c..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_go.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_green.png b/node_modules/express/node_modules/connect/lib/public/icons/page_green.png deleted file mode 100644 index de8e003f9..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_green.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_key.png b/node_modules/express/node_modules/connect/lib/public/icons/page_key.png deleted file mode 100644 index d6626cb09..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_key.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png b/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png deleted file mode 100644 index 7e568703d..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_lightning.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_link.png b/node_modules/express/node_modules/connect/lib/public/icons/page_link.png deleted file mode 100644 index 312eab091..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_link.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png b/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png deleted file mode 100644 index 246a2f0b4..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_paintbrush.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png b/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png deleted file mode 100644 index 968f073fd..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_paste.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_red.png b/node_modules/express/node_modules/connect/lib/public/icons/page_red.png deleted file mode 100644 index 0b18247da..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_red.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png b/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png deleted file mode 100644 index cf347c7d4..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_refresh.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_save.png b/node_modules/express/node_modules/connect/lib/public/icons/page_save.png deleted file mode 100644 index caea546af..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_save.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white.png deleted file mode 100644 index 8b8b1ca00..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png deleted file mode 100644 index 8f8095e46..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_acrobat.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png deleted file mode 100644 index 159b24075..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_actionscript.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png deleted file mode 100644 index aa23dde37..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_add.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png deleted file mode 100644 index 34a05cccf..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_c.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png deleted file mode 100644 index f501a593a..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_camera.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png deleted file mode 100644 index 848bdaf3f..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cd.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png deleted file mode 100644 index 0c76bd129..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png deleted file mode 100644 index 87a691450..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_code_red.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png deleted file mode 100644 index c66011fb0..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_coldfusion.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png deleted file mode 100644 index 2b6b1007f..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_compressed.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png deleted file mode 100644 index a9f31a278..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_copy.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png deleted file mode 100644 index a87cf847c..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cplusplus.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png deleted file mode 100644 index ffb8fc932..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_csharp.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png deleted file mode 100644 index 0a7d6f4a6..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_cup.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png deleted file mode 100644 index bddba1f98..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_database.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png deleted file mode 100644 index af1ecaf29..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_delete.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png deleted file mode 100644 index 4cc537af0..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_dvd.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png deleted file mode 100644 index b93e77600..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_edit.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png deleted file mode 100644 index 9fc5a0a10..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_error.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png deleted file mode 100644 index b977d7e52..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_excel.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png deleted file mode 100644 index 581843637..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_find.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png deleted file mode 100644 index 5769120b1..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_flash.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png deleted file mode 100644 index 8d719df52..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_freehand.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png deleted file mode 100644 index 106f5aa36..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_gear.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png deleted file mode 100644 index e4a1ecba1..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_get.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png deleted file mode 100644 index 7e62a924b..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_go.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png deleted file mode 100644 index e902abb07..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_h.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png deleted file mode 100644 index 1d2d0a498..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_horizontal.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png deleted file mode 100644 index d61648452..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_key.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png deleted file mode 100644 index 7215d1e8b..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_lightning.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png deleted file mode 100644 index bf7bd1c9b..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_link.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png deleted file mode 100644 index f6b74cc40..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_magnify.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png deleted file mode 100644 index d3fffb6d9..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_medal.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png deleted file mode 100644 index a65bcb3e1..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_office.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png deleted file mode 100644 index 23a37b891..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paint.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png deleted file mode 100644 index f907e44b3..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paintbrush.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png deleted file mode 100644 index 5b2cbb3fd..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_paste.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png deleted file mode 100644 index 7868a2594..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_php.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png deleted file mode 100644 index 134b66936..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_picture.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png deleted file mode 100644 index c4eff0387..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_powerpoint.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png deleted file mode 100644 index 884ffd6f0..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_put.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png deleted file mode 100644 index f59b7c436..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_ruby.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png deleted file mode 100644 index 44084add7..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_stack.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png deleted file mode 100644 index 3a1441c9a..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_star.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png deleted file mode 100644 index e7708292a..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_swoosh.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png deleted file mode 100644 index 813f712f7..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png deleted file mode 100644 index d9cf13256..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_text_width.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png deleted file mode 100644 index 52699bfee..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_tux.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png deleted file mode 100644 index 4a05955b3..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_vector.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png deleted file mode 100644 index a0a433dfb..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_visualstudio.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png deleted file mode 100644 index 1eb880947..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_width.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png deleted file mode 100644 index ae8ecbf47..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_word.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png deleted file mode 100644 index 6ed2490ed..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_world.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png deleted file mode 100644 index fecadd08a..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_wrench.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png b/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png deleted file mode 100644 index fd4bbccdf..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_white_zip.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_word.png b/node_modules/express/node_modules/connect/lib/public/icons/page_word.png deleted file mode 100644 index 834cdfaf4..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_word.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/icons/page_world.png b/node_modules/express/node_modules/connect/lib/public/icons/page_world.png deleted file mode 100644 index b8895ddec..000000000 Binary files a/node_modules/express/node_modules/connect/lib/public/icons/page_world.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/lib/public/style.css b/node_modules/express/node_modules/connect/lib/public/style.css deleted file mode 100644 index 0709908a6..000000000 --- a/node_modules/express/node_modules/connect/lib/public/style.css +++ /dev/null @@ -1,257 +0,0 @@ -* { - margin: 0; - padding: 0; - outline: 0; -} - -body { - padding: 80px 100px; - font: 13px "Helvetica Neue", "Lucida Grande", "Arial"; - background: #ECE9E9 -webkit-gradient(linear, 0% 0%, 0% 100%, from(#fff), to(#ECE9E9)); - background: #ECE9E9 -moz-linear-gradient(top, #fff, #ECE9E9); - background-repeat: no-repeat; - color: #555; - -webkit-font-smoothing: antialiased; -} -h1, h2, h3 { - font-size: 22px; - color: #343434; -} -h1 em, h2 em { - padding: 0 5px; - font-weight: normal; -} -h1 { - font-size: 60px; -} -h2 { - margin-top: 10px; -} -h3 { - margin: 5px 0 10px 0; - padding-bottom: 5px; - border-bottom: 1px solid #eee; - font-size: 18px; -} -ul li { - list-style: none; -} -ul li:hover { - cursor: pointer; - color: #2e2e2e; -} -ul li .path { - padding-left: 5px; - font-weight: bold; -} -ul li .line { - padding-right: 5px; - font-style: italic; -} -ul li:first-child .path { - padding-left: 0; -} -p { - line-height: 1.5; -} -a { - color: #555; - text-decoration: none; -} -a:hover { - color: #303030; -} -#stacktrace { - margin-top: 15px; -} -.directory h1 { - margin-bottom: 15px; - font-size: 18px; -} -ul#files { - width: 100%; - height: 100%; - overflow: hidden; -} -ul#files li { - float: left; - width: 30%; - line-height: 25px; - margin: 1px; -} -ul#files li a { - display: block; - height: 25px; - border: 1px solid transparent; - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - border-radius: 5px; - overflow: hidden; - white-space: nowrap; -} -ul#files li a:focus, -ul#files li a:hover { - background: rgba(255,255,255,0.65); - border: 1px solid #ececec; -} -ul#files li a.highlight { - -webkit-transition: background .4s ease-in-out; - background: #ffff4f; - border-color: #E9DC51; -} -#search { - display: block; - position: fixed; - top: 20px; - right: 20px; - width: 90px; - -webkit-transition: width ease 0.2s, opacity ease 0.4s; - -moz-transition: width ease 0.2s, opacity ease 0.4s; - -webkit-border-radius: 32px; - -moz-border-radius: 32px; - -webkit-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -moz-box-shadow: inset 0px 0px 3px rgba(0, 0, 0, 0.25), inset 0px 1px 3px rgba(0, 0, 0, 0.7), 0px 1px 0px rgba(255, 255, 255, 0.03); - -webkit-font-smoothing: antialiased; - text-align: left; - font: 13px "Helvetica Neue", Arial, sans-serif; - padding: 4px 10px; - border: none; - background: transparent; - margin-bottom: 0; - outline: none; - opacity: 0.7; - color: #888; -} -#search:focus { - width: 120px; - opacity: 1.0; -} - -/*views*/ -#files span { - display: inline-block; - overflow: hidden; - text-overflow: ellipsis; - text-indent: 10px; -} -#files .name { - background-repeat: no-repeat; -} -#files .icon .name { - text-indent: 28px; -} - -/*tiles*/ -.view-tiles .name { - width: 100%; - background-position: 8px 5px; -} -.view-tiles .size, -.view-tiles .date { - display: none; -} - -/*details*/ -ul#files.view-details li { - float: none; - display: block; - width: 90%; -} -ul#files.view-details li.header { - height: 25px; - background: #000; - color: #fff; - font-weight: bold; -} -.view-details .header { - border-radius: 5px; -} -.view-details .name { - width: 60%; - background-position: 8px 5px; -} -.view-details .size { - width: 10%; -} -.view-details .date { - width: 30%; -} -.view-details .size, -.view-details .date { - text-align: right; - direction: rtl; -} - -/*mobile*/ -@media (max-width: 768px) { - body { - font-size: 13px; - line-height: 16px; - padding: 0; - } - #search { - position: static; - width: 100%; - font-size: 2em; - line-height: 1.8em; - text-indent: 10px; - border: 0; - border-radius: 0; - padding: 10px 0; - margin: 0; - } - #search:focus { - width: 100%; - border: 0; - opacity: 1; - } - .directory h1 { - font-size: 2em; - line-height: 1.5em; - color: #fff; - background: #000; - padding: 15px 10px; - margin: 0; - } - ul#files { - border-top: 1px solid #cacaca; - } - ul#files li { - float: none; - width: auto !important; - display: block; - border-bottom: 1px solid #cacaca; - font-size: 2em; - line-height: 1.2em; - text-indent: 0; - margin: 0; - } - ul#files li:nth-child(odd) { - background: #e0e0e0; - } - ul#files li a { - height: auto; - border: 0; - border-radius: 0; - padding: 15px 10px; - } - ul#files li a:focus, - ul#files li a:hover { - border: 0; - } - #files .header, - #files .size, - #files .date { - display: none !important; - } - #files .name { - float: none; - display: inline-block; - width: 100%; - text-indent: 0; - background-position: 0 0; - } - #files .icon .name { - text-indent: 41px; - } -} diff --git a/node_modules/express/node_modules/connect/lib/utils.js b/node_modules/express/node_modules/connect/lib/utils.js deleted file mode 100644 index 9839bc33f..000000000 --- a/node_modules/express/node_modules/connect/lib/utils.js +++ /dev/null @@ -1,408 +0,0 @@ - -/*! - * Connect - utils - * Copyright(c) 2010 Sencha Inc. - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var http = require('http') - , crypto = require('crypto') - , parse = require('url').parse - , sep = require('path').sep - , signature = require('cookie-signature') - , nodeVersion = process.versions.node.split('.'); - -// pause is broken in node < 0.10 -exports.brokenPause = parseInt(nodeVersion[0], 10) === 0 - && parseInt(nodeVersion[1], 10) < 10; - -/** - * Return `true` if the request has a body, otherwise return `false`. - * - * @param {IncomingMessage} req - * @return {Boolean} - * @api private - */ - -exports.hasBody = function(req) { - var encoding = 'transfer-encoding' in req.headers; - var length = 'content-length' in req.headers && req.headers['content-length'] !== '0'; - return encoding || length; -}; - -/** - * Extract the mime type from the given request's - * _Content-Type_ header. - * - * @param {IncomingMessage} req - * @return {String} - * @api private - */ - -exports.mime = function(req) { - var str = req.headers['content-type'] || ''; - return str.split(';')[0]; -}; - -/** - * Generate an `Error` from the given status `code` - * and optional `msg`. - * - * @param {Number} code - * @param {String} msg - * @return {Error} - * @api private - */ - -exports.error = function(code, msg){ - var err = new Error(msg || http.STATUS_CODES[code]); - err.status = code; - return err; -}; - -/** - * Return md5 hash of the given string and optional encoding, - * defaulting to hex. - * - * utils.md5('wahoo'); - * // => "e493298061761236c96b02ea6aa8a2ad" - * - * @param {String} str - * @param {String} encoding - * @return {String} - * @api private - */ - -exports.md5 = function(str, encoding){ - return crypto - .createHash('md5') - .update(str, 'utf8') - .digest(encoding || 'hex'); -}; - -/** - * Merge object b with object a. - * - * var a = { foo: 'bar' } - * , b = { bar: 'baz' }; - * - * utils.merge(a, b); - * // => { foo: 'bar', bar: 'baz' } - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api private - */ - -exports.merge = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ - -exports.sign = function(val, secret){ - console.warn('do not use utils.sign(), use https://github.com/visionmedia/node-cookie-signature') - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/=+$/, ''); -}; - -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ - -exports.unsign = function(val, secret){ - console.warn('do not use utils.unsign(), use https://github.com/visionmedia/node-cookie-signature') - var str = val.slice(0, val.lastIndexOf('.')); - return exports.sign(str, secret) == val - ? str - : false; -}; - -/** - * Parse signed cookies, returning an object - * containing the decoded key/value pairs, - * while removing the signed key from `obj`. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.parseSignedCookies = function(obj, secret){ - var ret = {}; - Object.keys(obj).forEach(function(key){ - var val = obj[key]; - if (0 == val.indexOf('s:')) { - val = signature.unsign(val.slice(2), secret); - if (val) { - ret[key] = val; - delete obj[key]; - } - } - }); - return ret; -}; - -/** - * Parse a signed cookie string, return the decoded value - * - * @param {String} str signed cookie string - * @param {String} secret - * @return {String} decoded value - * @api private - */ - -exports.parseSignedCookie = function(str, secret){ - return 0 == str.indexOf('s:') - ? signature.unsign(str.slice(2), secret) - : str; -}; - -/** - * Parse JSON cookies. - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.parseJSONCookies = function(obj){ - Object.keys(obj).forEach(function(key){ - var val = obj[key]; - var res = exports.parseJSONCookie(val); - if (res) obj[key] = res; - }); - return obj; -}; - -/** - * Parse JSON cookie string - * - * @param {String} str - * @return {Object} Parsed object or null if not json cookie - * @api private - */ - -exports.parseJSONCookie = function(str) { - if (0 == str.indexOf('j:')) { - try { - return JSON.parse(str.slice(2)); - } catch (err) { - // no op - } - } -}; - -/** - * Pause `data` and `end` events on the given `obj`. - * Middleware performing async tasks _should_ utilize - * this utility (or similar), to re-emit data once - * the async operation has completed, otherwise these - * events may be lost. Pause is only required for - * node versions less than 10, and is replaced with - * noop's otherwise. - * - * var pause = utils.pause(req); - * fs.readFile(path, function(){ - * next(); - * pause.resume(); - * }); - * - * @param {Object} obj - * @return {Object} - * @api private - */ - -exports.pause = exports.brokenPause - ? require('pause') - : function () { - return { - end: noop, - resume: noop - } - } - -/** - * Strip `Content-*` headers from `res`. - * - * @param {ServerResponse} res - * @api private - */ - -exports.removeContentHeaders = function(res){ - if (!res._headers) return; - Object.keys(res._headers).forEach(function(field){ - if (0 == field.indexOf('content')) { - res.removeHeader(field); - } - }); -}; - -/** - * Check if `req` is a conditional GET request. - * - * @param {IncomingMessage} req - * @return {Boolean} - * @api private - */ - -exports.conditionalGET = function(req) { - return req.headers['if-modified-since'] - || req.headers['if-none-match']; -}; - -/** - * Respond with 401 "Unauthorized". - * - * @param {ServerResponse} res - * @param {String} realm - * @api private - */ - -exports.unauthorized = function(res, realm) { - res.statusCode = 401; - res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"'); - res.end('Unauthorized'); -}; - -/** - * Respond with 304 "Not Modified". - * - * @param {ServerResponse} res - * @param {Object} headers - * @api private - */ - -exports.notModified = function(res) { - exports.removeContentHeaders(res); - res.statusCode = 304; - res.end(); -}; - -/** - * Return an ETag in the form of `"-"` - * from the given `stat`. - * - * @param {Object} stat - * @return {String} - * @api private - */ - -exports.etag = function(stat) { - return '"' + stat.size + '-' + Number(stat.mtime) + '"'; -}; - -/** - * Parse the given Cache-Control `str`. - * - * @param {String} str - * @return {Object} - * @api private - */ - -exports.parseCacheControl = function(str){ - var directives = str.split(',') - , obj = {}; - - for(var i = 0, len = directives.length; i < len; i++) { - var parts = directives[i].split('=') - , key = parts.shift().trim() - , val = parseInt(parts.shift(), 10); - - obj[key] = isNaN(val) ? true : val; - } - - return obj; -}; - -/** - * Parse the `req` url with memoization. - * - * @param {ServerRequest} req - * @return {Object} - * @api private - */ - -exports.parseUrl = function(req){ - var parsed = req._parsedUrl; - if (parsed && parsed.href == req.url) { - return parsed; - } else { - parsed = parse(req.url); - - if (parsed.auth && !parsed.protocol && ~parsed.href.indexOf('//')) { - // This parses pathnames, and a strange pathname like //r@e should work - parsed = parse(req.url.replace(/@/g, '%40')); - } - - return req._parsedUrl = parsed; - } -}; - -/** - * Parse byte `size` string. - * - * @param {String} size - * @return {Number} - * @api private - */ - -exports.parseBytes = require('bytes'); - -/** - * Normalizes the path separator from system separator - * to URL separator, aka `/`. - * - * @param {String} path - * @return {String} - * @api private - */ - -exports.normalizeSlashes = function normalizeSlashes(path) { - return path.split(sep).join('/'); -}; - -function noop() {} diff --git a/node_modules/express/node_modules/connect/node_modules/batch/.npmignore b/node_modules/express/node_modules/connect/node_modules/batch/.npmignore deleted file mode 100644 index f1250e584..000000000 --- a/node_modules/express/node_modules/connect/node_modules/batch/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/express/node_modules/connect/node_modules/batch/History.md b/node_modules/express/node_modules/connect/node_modules/batch/History.md deleted file mode 100644 index b1b77526a..000000000 --- a/node_modules/express/node_modules/connect/node_modules/batch/History.md +++ /dev/null @@ -1,66 +0,0 @@ - -0.5.0 / 2013-07-29 -================== - - * add `.throws(true)` to opt-in to responding with an array of error objects - * make `new` optional - -0.4.0 / 2013-06-05 -================== - - * add catching of immediate callback errors - -0.3.2 / 2013-03-15 -================== - - * remove Emitter call in constructor - -0.3.1 / 2013-03-13 -================== - - * add Emitter() mixin for client. Closes #8 - -0.3.0 / 2013-03-13 -================== - - * add component.json - * add result example - * add .concurrency support - * add concurrency example - * add parallel example - -0.2.1 / 2012-11-08 -================== - - * add .start, .end, and .duration properties - * change dependencies to devDependencies - -0.2.0 / 2012-10-04 -================== - - * add progress events. Closes #5 (__BREAKING CHANGE__) - -0.1.1 / 2012-07-03 -================== - - * change "complete" event to "progress" - -0.1.0 / 2012-07-03 -================== - - * add Emitter inheritance and emit "complete" [burcu] - -0.0.3 / 2012-06-02 -================== - - * Callback results should be in the order of the queued functions. - -0.0.2 / 2012-02-12 -================== - - * any node - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/node_modules/connect/node_modules/batch/Makefile b/node_modules/express/node_modules/connect/node_modules/batch/Makefile deleted file mode 100644 index 634e37219..000000000 --- a/node_modules/express/node_modules/connect/node_modules/batch/Makefile +++ /dev/null @@ -1,6 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/batch/Readme.md b/node_modules/express/node_modules/connect/node_modules/batch/Readme.md deleted file mode 100644 index f2345c67b..000000000 --- a/node_modules/express/node_modules/connect/node_modules/batch/Readme.md +++ /dev/null @@ -1,74 +0,0 @@ - -# batch - - Simple async batch with concurrency control and progress reporting. - -## Installation - -``` -$ npm install batch -``` - -## API - -```js -var Batch = require('batch') - , batch = new Batch; - -batch.concurrency(4); - -ids.forEach(function(id){ - batch.push(function(done){ - User.get(id, done); - }); -}); - -batch.on('progress', function(e){ - -}); - -batch.end(function(err, users){ - -}); -``` - -### Progress events - - Contain the "job" index, response value, duration information, and completion data. - -```js -{ index: 1, - value: 'bar', - pending: 2, - total: 3, - complete: 2, - percent: 66, - start: Thu Oct 04 2012 12:25:53 GMT-0700 (PDT), - end: Thu Oct 04 2012 12:25:53 GMT-0700 (PDT), - duration: 0 } -``` - -## License - -(The MIT License) - -Copyright (c) 2013 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/connect/node_modules/batch/component.json b/node_modules/express/node_modules/connect/node_modules/batch/component.json deleted file mode 100644 index 0ea7e5824..000000000 --- a/node_modules/express/node_modules/connect/node_modules/batch/component.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "batch", - "repo": "visionmedia/batch", - "description": "Async task batching", - "version": "0.5.0", - "keywords": ["batch", "async", "utility", "concurrency", "concurrent"], - "dependencies": { - "component/emitter": "*" - }, - "development": {}, - "scripts": [ - "index.js" - ] -} diff --git a/node_modules/express/node_modules/connect/node_modules/batch/index.js b/node_modules/express/node_modules/connect/node_modules/batch/index.js deleted file mode 100644 index 932d40455..000000000 --- a/node_modules/express/node_modules/connect/node_modules/batch/index.js +++ /dev/null @@ -1,158 +0,0 @@ -/** - * Module dependencies. - */ - -try { - var EventEmitter = require('events').EventEmitter; -} catch (err) { - var Emitter = require('emitter'); -} - -/** - * Noop. - */ - -function noop(){} - -/** - * Expose `Batch`. - */ - -module.exports = Batch; - -/** - * Create a new Batch. - */ - -function Batch() { - if (!(this instanceof Batch)) return new Batch; - this.fns = []; - this.concurrency(Infinity); - this.throws(true); - for (var i = 0, len = arguments.length; i < len; ++i) { - this.push(arguments[i]); - } -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -if (EventEmitter) { - Batch.prototype.__proto__ = EventEmitter.prototype; -} else { - Emitter(Batch.prototype); -} - -/** - * Set concurrency to `n`. - * - * @param {Number} n - * @return {Batch} - * @api public - */ - -Batch.prototype.concurrency = function(n){ - this.n = n; - return this; -}; - -/** - * Queue a function. - * - * @param {Function} fn - * @return {Batch} - * @api public - */ - -Batch.prototype.push = function(fn){ - this.fns.push(fn); - return this; -}; - -/** - * Set wether Batch will or will not throw up. - * - * @param {Boolean} throws - * @return {Batch} - * @api public - */ -Batch.prototype.throws = function(throws) { - this.e = !!throws; - return this; -}; - -/** - * Execute all queued functions in parallel, - * executing `cb(err, results)`. - * - * @param {Function} cb - * @return {Batch} - * @api public - */ - -Batch.prototype.end = function(cb){ - var self = this - , total = this.fns.length - , pending = total - , results = [] - , errors = [] - , cb = cb || noop - , fns = this.fns - , max = this.n - , throws = this.e - , index = 0 - , done; - - // empty - if (!fns.length) return cb(null, results); - - // process - function next() { - var i = index++; - var fn = fns[i]; - if (!fn) return; - var start = new Date; - - try { - fn(callback); - } catch (err) { - callback(err); - } - - function callback(err, res){ - if (done) return; - if (err && throws) return done = true, cb(err); - var complete = total - pending + 1; - var end = new Date; - - results[i] = res; - errors[i] = err; - - self.emit('progress', { - index: i, - value: res, - error: err, - pending: pending, - total: total, - complete: complete, - percent: complete / total * 100 | 0, - start: start, - end: end, - duration: end - start - }); - - if (--pending) next() - else if(!throws) cb(errors, results); - else cb(null, results); - } - } - - // concurrency - for (var i = 0; i < fns.length; i++) { - if (i == max) break; - next(); - } - - return this; -}; diff --git a/node_modules/express/node_modules/connect/node_modules/batch/package.json b/node_modules/express/node_modules/connect/node_modules/batch/package.json deleted file mode 100644 index 27bdc188a..000000000 --- a/node_modules/express/node_modules/connect/node_modules/batch/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "batch", - "version": "0.5.0", - "description": "Simple async batch", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "main": "index", - "readme": "\n# batch\n\n Simple async batch with concurrency control and progress reporting.\n\n## Installation\n\n```\n$ npm install batch\n```\n\n## API\n\n```js\nvar Batch = require('batch')\n , batch = new Batch;\n\nbatch.concurrency(4);\n\nids.forEach(function(id){\n batch.push(function(done){\n User.get(id, done);\n });\n});\n\nbatch.on('progress', function(e){\n\n});\n\nbatch.end(function(err, users){\n\n});\n```\n\n### Progress events\n\n Contain the \"job\" index, response value, duration information, and completion data.\n\n```js\n{ index: 1,\n value: 'bar',\n pending: 2,\n total: 3,\n complete: 2,\n percent: 66,\n start: Thu Oct 04 2012 12:25:53 GMT-0700 (PDT),\n end: Thu Oct 04 2012 12:25:53 GMT-0700 (PDT),\n duration: 0 }\n```\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2013 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "_id": "batch@0.5.0", - "dist": { - "shasum": "e3480edd5ad84f92cf61240bfc7a6822506275ab" - }, - "_from": "batch@0.5.0", - "_resolved": "https://registry.npmjs.org/batch/-/batch-0.5.0.tgz" -} diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/.npmignore b/node_modules/express/node_modules/connect/node_modules/bytes/.npmignore deleted file mode 100644 index 9daeafb98..000000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/History.md b/node_modules/express/node_modules/connect/node_modules/bytes/History.md deleted file mode 100644 index f233ed160..000000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/History.md +++ /dev/null @@ -1,15 +0,0 @@ - -0.2.1 / 2013-04-01 -================== - - * add .component - -0.2.0 / 2012-10-28 -================== - - * bytes(200).should.eql('200b') - -0.1.0 / 2012-07-04 -================== - - * add bytes to string conversion [yields] diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/Makefile b/node_modules/express/node_modules/connect/node_modules/bytes/Makefile deleted file mode 100644 index 8e8640f2e..000000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --reporter spec \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/Readme.md b/node_modules/express/node_modules/connect/node_modules/bytes/Readme.md deleted file mode 100644 index 9325d5bf4..000000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/Readme.md +++ /dev/null @@ -1,51 +0,0 @@ -# node-bytes - - Byte string parser / formatter. - -## Example: - -```js -bytes('1kb') -// => 1024 - -bytes('2mb') -// => 2097152 - -bytes('1gb') -// => 1073741824 - -bytes(1073741824) -// => 1gb -``` - -## Installation - -``` -$ npm install bytes -$ component install visionmedia/bytes.js -``` - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/component.json b/node_modules/express/node_modules/connect/node_modules/bytes/component.json deleted file mode 100644 index 2929c25d6..000000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/component.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "name": "bytes", - "description": "byte size string parser / serializer", - "keywords": ["bytes", "utility"], - "version": "0.2.1", - "scripts": ["index.js"] -} diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/index.js b/node_modules/express/node_modules/connect/node_modules/bytes/index.js deleted file mode 100644 index 70b2e01a4..000000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/index.js +++ /dev/null @@ -1,39 +0,0 @@ - -/** - * Parse byte `size` string. - * - * @param {String} size - * @return {Number} - * @api public - */ - -module.exports = function(size) { - if ('number' == typeof size) return convert(size); - var parts = size.match(/^(\d+(?:\.\d+)?) *(kb|mb|gb)$/) - , n = parseFloat(parts[1]) - , type = parts[2]; - - var map = { - kb: 1 << 10 - , mb: 1 << 20 - , gb: 1 << 30 - }; - - return map[type] * n; -}; - -/** - * convert bytes into string. - * - * @param {Number} b - bytes to convert - * @return {String} - * @api public - */ - -function convert (b) { - var gb = 1 << 30, mb = 1 << 20, kb = 1 << 10; - if (b >= gb) return (Math.round(b / gb * 100) / 100) + 'gb'; - if (b >= mb) return (Math.round(b / mb * 100) / 100) + 'mb'; - if (b >= kb) return (Math.round(b / kb * 100) / 100) + 'kb'; - return b + 'b'; -} diff --git a/node_modules/express/node_modules/connect/node_modules/bytes/package.json b/node_modules/express/node_modules/connect/node_modules/bytes/package.json deleted file mode 100644 index 83230954e..000000000 --- a/node_modules/express/node_modules/connect/node_modules/bytes/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "bytes", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "description": "byte size string parser / serializer", - "version": "0.2.1", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "component": { - "scripts": { - "bytes/index.js": "index.js" - } - }, - "readme": "# node-bytes\n\n Byte string parser / formatter.\n\n## Example:\n\n```js\nbytes('1kb')\n// => 1024\n\nbytes('2mb')\n// => 2097152\n\nbytes('1gb')\n// => 1073741824\n\nbytes(1073741824)\n// => 1gb\n```\n\n## Installation\n\n```\n$ npm install bytes\n$ component install visionmedia/bytes.js\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "_id": "bytes@0.2.1", - "dist": { - "shasum": "13114f18ead29c4ada0a4e6e383feb87a526fe40" - }, - "_from": "bytes@0.2.1", - "_resolved": "https://registry.npmjs.org/bytes/-/bytes-0.2.1.tgz" -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/.jshintrc b/node_modules/express/node_modules/connect/node_modules/multiparty/.jshintrc deleted file mode 100644 index a93b50cfb..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/.jshintrc +++ /dev/null @@ -1,70 +0,0 @@ -{ - // Settings - "passfail" : false, // Stop on first error. - "maxerr" : 100, // Maximum errors before stopping. - - - // Predefined globals whom JSHint will ignore. - "browser" : false, // Standard browser globals e.g. `window`, `document`. - - "node" : true, - "rhino" : false, - "couch" : false, - "wsh" : false, // Windows Scripting Host. - - "jquery" : false, - "prototypejs" : false, - "mootools" : false, - "dojo" : false, - - - "predef" : [ - "describe", "it", "before", "after" - ], - - // Development. - "debug" : true, // Allow debugger statements e.g. browser breakpoints. - "devel" : true, // Allow development statements e.g. `console.log();`. - - - // EcmaScript 5. - "es5" : true, // Allow EcmaScript 5 syntax. - "strict" : false, // Require `use strict` pragma in every file. - "globalstrict" : true, // Allow global "use strict" (also enables 'strict'). - - - // The Good Parts. - "asi" : true, // Tolerate Automatic Semicolon Insertion (no semicolons). - "laxbreak" : false, // Tolerate unsafe line breaks e.g. `return [\n] x` without semicolons. - "laxcomma" : true, - "bitwise" : false, // Prohibit bitwise operators (&, |, ^, etc.). - "boss" : true, // Tolerate assignments inside if, for & while. Usually conditions & loops are for comparison, not assignments. - "curly" : false, // Require {} for every new block or scope. - "eqeqeq" : true, // Require triple equals i.e. `===`. - "eqnull" : true, // Tolerate use of `== null`. - "evil" : false, // Tolerate use of `eval`. - "expr" : false, // Tolerate `ExpressionStatement` as Programs. - "forin" : false, // Prohibt `for in` loops without `hasOwnProperty`. - "immed" : true, // Require immediate invocations to be wrapped in parens e.g. `( function(){}() );` - "latedef" : false, // Prohibit variable use before definition. - "loopfunc" : false, // Allow functions to be defined within loops. - "noarg" : true, // Prohibit use of `arguments.caller` and `arguments.callee`. - "regexp" : false, // Prohibit `.` and `[^...]` in regular expressions. - "regexdash" : false, // Tolerate unescaped last dash i.e. `[-...]`. - "scripturl" : false, // Tolerate script-targeted URLs. - "shadow" : false, // Allows re-define variables later in code e.g. `var x=1; x=2;`. - "supernew" : false, // Tolerate `new function () { ... };` and `new Object;`. - "undef" : true, // Require all non-global variables be declared before they are used. - - - // Persone styling prefrences. - "newcap" : true, // Require capitalization of all constructor functions e.g. `new F()`. - "noempty" : true, // Prohibit use of empty blocks. - "nonew" : true, // Prohibit use of constructors for side-effects. - "nomen" : false, // Prohibit use of initial or trailing underbars in names. - "onevar" : false, // Allow only one `var` statement per function. - "plusplus" : false, // Prohibit use of `++` & `--`. - "sub" : false, // Tolerate all forms of subscript notation besides dot notation e.g. `dict['key']` instead of `dict.key`. - "trailing" : true, // Prohibit trailing whitespaces. - "white" : false // Check against strict whitespace and indentation rules. -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/.npmignore b/node_modules/express/node_modules/connect/node_modules/multiparty/.npmignore deleted file mode 100644 index 07e6e472c..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/.travis.yml b/node_modules/express/node_modules/connect/node_modules/multiparty/.travis.yml deleted file mode 100644 index b1fc4b015..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" -before_script: - - ulimit -n 500 diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/CHANGELOG.md b/node_modules/express/node_modules/connect/node_modules/multiparty/CHANGELOG.md deleted file mode 100644 index ea54d9a13..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/CHANGELOG.md +++ /dev/null @@ -1,191 +0,0 @@ -### 2.2.0 - - * additional callback API to support multiple files with same field name - * fix assertion crash when max field count is exceeded - * fix assertion crash when client aborts an invalid request - * (>=v0.10 only) unpipe the request when an error occurs to save resources. - * update readable-stream to ~1.1.9 - * fix assertion crash when EMFILE occurrs - * (no more assertions - only 'error' events) - -### 2.1.9 - - * relax content-type detection regex. (thanks amitaibu) - -### 2.1.8 - - * replace deprecated Buffer.write(). (thanks hueniverse) - -### 2.1.7 - - * add repository field to package.json - -### 2.1.6 - - * expose `hash` as an option to `Form`. (thanks wookiehangover) - -### 2.1.5 - - * fix possible 'close' event before all temp files are done - -### 2.1.4 - - * fix crash for invalid requests - -### 2.1.3 - - * add `file.size` - -### 2.1.2 - - * proper backpressure support - * update s3 example - -### 2.1.1 - - * fix uploads larger than 2KB - * fix both s3 and upload example - * add part.byteCount and part.byteOffset - -### 2.1.0 (recalled) - - * Complete rewrite. See README for changes and new API. - -### v1.0.13 - -* Only update hash if update method exists (Sven Lito) -* According to travis v0.10 needs to go quoted (Sven Lito) -* Bumping build node versions (Sven Lito) -* Additional fix for empty requests (Eugene Girshov) -* Change the default to 1000, to match the new Node behaviour. (OrangeDog) -* Add ability to control maxKeys in the querystring parser. (OrangeDog) -* Adjust test case to work with node 0.9.x (Eugene Girshov) -* Update package.json (Sven Lito) -* Path adjustment according to eb4468b (Markus Ast) - -### v1.0.12 - -* Emit error on aborted connections (Eugene Girshov) -* Add support for empty requests (Eugene Girshov) -* Fix name/filename handling in Content-Disposition (jesperp) -* Tolerate malformed closing boundary in multipart (Eugene Girshov) -* Ignore preamble in multipart messages (Eugene Girshov) -* Add support for application/json (Mike Frey, Carlos Rodriguez) -* Add support for Base64 encoding (Elmer Bulthuis) -* Add File#toJSON (TJ Holowaychuk) -* Remove support for Node.js 0.4 & 0.6 (Andrew Kelley) -* Documentation improvements (Sven Lito, Andre Azevedo) -* Add support for application/octet-stream (Ion Lupascu, Chris Scribner) -* Use os.tmpDir() to get tmp directory (Andrew Kelley) -* Improve package.json (Andrew Kelley, Sven Lito) -* Fix benchmark script (Andrew Kelley) -* Fix scope issue in incoming_forms (Sven Lito) -* Fix file handle leak on error (OrangeDog) - -### v1.0.11 - -* Calculate checksums for incoming files (sreuter) -* Add definition parameters to "IncomingForm" as an argument (Math-) - -### v1.0.10 - -* Make parts to be proper Streams (Matt Robenolt) - -### v1.0.9 - -* Emit progress when content length header parsed (Tim Koschützki) -* Fix Readme syntax due to GitHub changes (goob) -* Replace references to old 'sys' module in Readme with 'util' (Peter Sugihara) - -### v1.0.8 - -* Strip potentially unsafe characters when using `keepExtensions: true`. -* Switch to utest / urun for testing -* Add travis build - -### v1.0.7 - -* Remove file from package that was causing problems when installing on windows. (#102) -* Fix typos in Readme (Jason Davies). - -### v1.0.6 - -* Do not default to the default to the field name for file uploads where - filename="". - -### v1.0.5 - -* Support filename="" in multipart parts -* Explain unexpected end() errors in parser better - -**Note:** Starting with this version, formidable emits 'file' events for empty -file input fields. Previously those were incorrectly emitted as regular file -input fields with value = "". - -### v1.0.4 - -* Detect a good default tmp directory regardless of platform. (#88) - -### v1.0.3 - -* Fix problems with utf8 characters (#84) / semicolons in filenames (#58) -* Small performance improvements -* New test suite and fixture system - -### v1.0.2 - -* Exclude node\_modules folder from git -* Implement new `'aborted'` event -* Fix files in example folder to work with recent node versions -* Make gently a devDependency - -[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.1...v1.0.2) - -### v1.0.1 - -* Fix package.json to refer to proper main directory. (#68, Dean Landolt) - -[See Commits](https://github.com/felixge/node-formidable/compare/v1.0.0...v1.0.1) - -### v1.0.0 - -* Add support for multipart boundaries that are quoted strings. (Jeff Craig) - -This marks the beginning of development on version 2.0 which will include -several architectural improvements. - -[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.11...v1.0.0) - -### v0.9.11 - -* Emit `'progress'` event when receiving data, regardless of parsing it. (Tim Koschützki) -* Use [W3C FileAPI Draft](http://dev.w3.org/2006/webapi/FileAPI/) properties for File class - -**Important:** The old property names of the File class will be removed in a -future release. - -[See Commits](https://github.com/felixge/node-formidable/compare/v0.9.10...v0.9.11) - -### Older releases - -These releases were done before starting to maintain the above Changelog: - -* [v0.9.10](https://github.com/felixge/node-formidable/compare/v0.9.9...v0.9.10) -* [v0.9.9](https://github.com/felixge/node-formidable/compare/v0.9.8...v0.9.9) -* [v0.9.8](https://github.com/felixge/node-formidable/compare/v0.9.7...v0.9.8) -* [v0.9.7](https://github.com/felixge/node-formidable/compare/v0.9.6...v0.9.7) -* [v0.9.6](https://github.com/felixge/node-formidable/compare/v0.9.5...v0.9.6) -* [v0.9.5](https://github.com/felixge/node-formidable/compare/v0.9.4...v0.9.5) -* [v0.9.4](https://github.com/felixge/node-formidable/compare/v0.9.3...v0.9.4) -* [v0.9.3](https://github.com/felixge/node-formidable/compare/v0.9.2...v0.9.3) -* [v0.9.2](https://github.com/felixge/node-formidable/compare/v0.9.1...v0.9.2) -* [v0.9.1](https://github.com/felixge/node-formidable/compare/v0.9.0...v0.9.1) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.9.0](https://github.com/felixge/node-formidable/compare/v0.8.0...v0.9.0) -* [v0.1.0](https://github.com/felixge/node-formidable/commits/v0.1.0) diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/LICENSE b/node_modules/express/node_modules/connect/node_modules/multiparty/LICENSE deleted file mode 100644 index 8488a4056..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (C) 2011-2013 Felix Geisendörfer, Andrew Kelley - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/README.md b/node_modules/express/node_modules/connect/node_modules/multiparty/README.md deleted file mode 100644 index f149ac046..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/README.md +++ /dev/null @@ -1,177 +0,0 @@ -[![Build Status](https://travis-ci.org/superjoe30/node-multiparty.png?branch=master)](https://travis-ci.org/superjoe30/node-multiparty) -# multiparty - -Parse http requests with content-type `multipart/form-data`, also known as file uploads. - -See also [busboy](https://github.com/mscdex/busboy) - a -[faster](https://github.com/mscdex/dicer/wiki/Benchmarks) alternative -which may be worth looking into. - -### Why the fork? - - * This module uses the Node.js v0.10 streams properly, *even in Node.js v0.8* - * It will not create a temp file for you unless you want it to. - * Counts bytes and does math to help you figure out the `Content-Length` of - each part. - * You can easily stream uploads to s3 with - [knox](https://github.com/LearnBoost/knox), for [example](examples/s3.js). - * Less bugs. This code is simpler, has all deprecated functionality removed, - has cleaner tests, and does not try to do anything beyond multipart stream - parsing. - -## Installation - -``` -npm install multiparty -``` - -## Usage - - * See [examples](examples). - -Parse an incoming `multipart/form-data` request. - -```js -var multiparty = require('multiparty') - , http = require('http') - , util = require('util') - -http.createServer(function(req, res) { - if (req.url === '/upload' && req.method === 'POST') { - // parse a file upload - var form = new multiparty.Form(); - - form.parse(req, function(err, fields, files) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received upload:\n\n'); - res.end(util.inspect({fields: fields, files: files})); - }); - - return; - } - - // show a file upload form - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); -}).listen(8080); -``` - -## API - -### multiparty.Form -```js -var form = new multiparty.Form(options) -``` -Creates a new form. Options: - - * `encoding` - sets encoding for the incoming form fields. Defaults to `utf8`. - * `maxFieldSize` - Limits the amount of memory a field (not a file) can - allocate in bytes. If this value is exceeded, an `error` event is emitted. - The default size is 2MB. - * `maxFields` - Limits the number of fields that will be parsed before - emitting an `error` event. A file counts as a field in this case. - Defaults to 1000. - * `autoFields` - Enables `field` events. This is automatically set to `true` - if you add a `field` listener. - * `autoFiles` - Enables `file` events. This is automatically set to `true` - if you add a `file` listener. - * `uploadDir` - Only relevant when `autoFiles` is `true`. The directory for - placing file uploads in. You can move them later using `fs.rename()`. - Defaults to `os.tmpDir()`. - * `hash` - Only relevant when `autoFiles` is `true`. If you want checksums - calculated for incoming files, set this to either `sha1` or `md5`. - Defaults to off. - -#### form.parse(request, [cb]) - -Parses an incoming node.js `request` containing form data. If `cb` is -provided, `autoFields` and `autoFiles` are set to `true` and all fields and -files are collected and passed to the callback: - -```js -form.parse(req, function(err, fieldsObject, filesObject, fieldsList, filesList) { - // ... -}); -``` - -It is often convenient to access a field or file by name. In this situation, -use `fieldsObject` or `filesObject`. However sometimes, as in the case of a -`` the multipart stream will contain -multiple files of the same input name, and you are interested in all of them. -In this case, use `filesList`. - -Another example is when you do not care what the field name of a file is; you -are merely interested in a single upload. In this case, set `maxFields` to 1 -(assuming no other fields expected besides the file) and use `filesList[0]`. - -#### form.bytesReceived - -The amount of bytes received for this form so far. - -#### form.bytesExpected - -The expected number of bytes in this form. - -### Events - -#### 'error' (err) - -You definitely want to handle this event. If not your server *will* crash when -users submit bogus multipart requests! - -#### 'part' (part) - -Emitted when a part is encountered in the request. `part` is a -`ReadableStream`. It also has the following properties: - - * `headers` - the headers for this part. For example, you may be interested - in `content-type`. - * `name` - the field name for this part - * `filename` - only if the part is an incoming file - * `byteOffset` - the byte offset of this part in the request body - * `byteCount` - assuming that this is the last part in the request, - this is the size of this part in bytes. You could use this, for - example, to set the `Content-Length` header if uploading to S3. - If the part had a `Content-Length` header then that value is used - here instead. - -#### 'aborted' - -Emitted when the request is aborted. This event will be followed shortly -by an `error` event. In practice you do not need to handle this event. - -#### 'progress' (bytesReceived, bytesExpected) - -#### 'close' - -Emitted after all parts have been parsed and emitted. Not emitted if an `error` -event is emitted. This is typically when you would send your response. - -#### 'file' (name, file) - -**By default multiparty will not touch your hard drive.** But if you add this -listener, multiparty automatically sets `form.autoFiles` to `true` and will -stream uploads to disk for you. - - * `name` - the field name for this file - * `file` - an object with these properties: - - `fieldName` - same as `name` - the field name for this file - - `originalFilename` - the filename that the user reports for the file - - `path` - the absolute path of the uploaded file on disk - - `headers` - the HTTP headers that were sent along with this file - - `size` - size of the file in bytes - -If you set the `form.hash` option, then `file` will also contain a `hash` -property which is the checksum of the file. - -#### 'field' (name, value) - - * `name` - field name - * `value` - string field value - diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/examples/azureblobstorage.js b/node_modules/express/node_modules/connect/node_modules/multiparty/examples/azureblobstorage.js deleted file mode 100644 index 273c3321a..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/examples/azureblobstorage.js +++ /dev/null @@ -1,41 +0,0 @@ -var http = require('http') - , util = require('util') - , multiparty = require('../') - , azure = require('azure') - , PORT = process.env.PORT || 27372 - -var server = http.createServer(function(req, res) { - if (req.url === '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url === '/upload') { - - var blobService = azure.createBlobService(); - var form = new multiparty.Form(); - form.on('part', function(part) { - if (!part.filename) return; - - var size = part.byteCount - part.byteOffset; - var name = part.filename; - var container = 'blobContainerName'; - - blobService.createBlockBlobFromStream(container, name, part, size, function(error) { - if (error) { - // error handling - } - }); - }); - form.parse(req); - - res.send('File uploaded successfully'); - } -}); -server.listen(PORT, function() { - console.info('listening on http://0.0.0.0:'+PORT+'/'); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/examples/s3.js b/node_modules/express/node_modules/connect/node_modules/multiparty/examples/s3.js deleted file mode 100644 index 60617ba2c..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/examples/s3.js +++ /dev/null @@ -1,74 +0,0 @@ -var http = require('http') - , util = require('util') - , multiparty = require('../') - , knox = require('knox') - , Batch = require('batch') - , PORT = process.env.PORT || 27372 - -var s3Client = knox.createClient({ - secure: false, - key: process.env.S3_KEY, - secret: process.env.S3_SECRET, - bucket: process.env.S3_BUCKET, -}); - -var server = http.createServer(function(req, res) { - if (req.url === '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url === '/upload') { - var headers = { - 'x-amz-acl': 'public-read', - }; - var form = new multiparty.Form(); - var batch = new Batch(); - batch.push(function(cb) { - form.on('field', function(name, value) { - if (name === 'path') { - var destPath = value; - if (destPath[0] !== '/') destPath = '/' + destPath; - cb(null, destPath); - } - }); - }); - batch.push(function(cb) { - form.on('part', function(part) { - if (! part.filename) return; - cb(null, part); - }); - }); - batch.end(function(err, results) { - if (err) throw err; - form.removeListener('close', onEnd); - var destPath = results[0] - , part = results[1]; - - headers['Content-Length'] = part.byteCount; - s3Client.putStream(part, destPath, headers, function(err, s3Response) { - if (err) throw err; - res.statusCode = s3Response.statusCode; - s3Response.pipe(res); - console.log("https://s3.amazonaws.com/" + process.env.S3_BUCKET + destPath); - }); - }); - form.on('close', onEnd); - form.parse(req); - - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } - - function onEnd() { - throw new Error("no uploaded file"); - } -}); -server.listen(PORT, function() { - console.info('listening on http://0.0.0.0:'+PORT+'/'); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/examples/upload.js b/node_modules/express/node_modules/connect/node_modules/multiparty/examples/upload.js deleted file mode 100644 index 5dd392684..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/examples/upload.js +++ /dev/null @@ -1,37 +0,0 @@ -var http = require('http') - , util = require('util') - , multiparty = require('../') - , PORT = process.env.PORT || 27372 - -var server = http.createServer(function(req, res) { - if (req.url === '/') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - } else if (req.url === '/upload') { - var form = new multiparty.Form(); - - form.parse(req, function(err, fields, files) { - if (err) { - res.writeHead(400, {'content-type': 'text/plain'}); - res.end("invalid request: " + err.message); - return; - } - res.writeHead(200, {'content-type': 'text/plain'}); - res.write('received fields:\n\n '+util.inspect(fields)); - res.write('\n\n'); - res.end('received files:\n\n '+util.inspect(files)); - }); - } else { - res.writeHead(404, {'content-type': 'text/plain'}); - res.end('404'); - } -}); -server.listen(PORT, function() { - console.info('listening on http://0.0.0.0:'+PORT+'/'); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/index.js b/node_modules/express/node_modules/connect/node_modules/multiparty/index.js deleted file mode 100644 index 71c88ae37..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/index.js +++ /dev/null @@ -1,618 +0,0 @@ -exports.Form = Form; - -var stream = require('readable-stream') - , util = require('util') - , fs = require('fs') - , crypto = require('crypto') - , path = require('path') - , os = require('os') - , StringDecoder = require('string_decoder').StringDecoder - , StreamCounter = require('stream-counter') - -var START = 0 - , START_BOUNDARY = 1 - , HEADER_FIELD_START = 2 - , HEADER_FIELD = 3 - , HEADER_VALUE_START = 4 - , HEADER_VALUE = 5 - , HEADER_VALUE_ALMOST_DONE = 6 - , HEADERS_ALMOST_DONE = 7 - , PART_DATA_START = 8 - , PART_DATA = 9 - , PART_END = 10 - , END = 11 - - , LF = 10 - , CR = 13 - , SPACE = 32 - , HYPHEN = 45 - , COLON = 58 - , A = 97 - , Z = 122 - -var CONTENT_TYPE_RE = /^multipart\/(form-data|related);\s*boundary=(?:"([^"]+)"|([^;]+))$/i; -var FILE_EXT_RE = /(\.[_\-a-zA-Z0-9]{0,16}).*/; -var LAST_BOUNDARY_SUFFIX_LEN = 4; // --\r\n - -util.inherits(Form, stream.Writable); -function Form(options) { - var self = this; - stream.Writable.call(self); - - options = options || {}; - - self.error = null; - self.finished = false; - - self.autoFields = !!options.autoFields; - self.autoFiles = !!options.autoFields; - - self.maxFields = options.maxFields || 1000; - self.maxFieldsSize = options.maxFieldsSize || 2 * 1024 * 1024; - self.uploadDir = options.uploadDir || os.tmpDir(); - self.encoding = options.encoding || 'utf8'; - self.hash = options.hash || false; - - self.bytesReceived = 0; - self.bytesExpected = null; - - self.openedFiles = []; - self.totalFieldSize = 0; - self.totalFieldCount = 0; - self.flushing = 0; - - self.backpressure = false; - self.writeCbs = []; - - if (options.boundary) setUpParser(self, options.boundary); - - self.on('newListener', function(eventName) { - if (eventName === 'file') { - self.autoFiles = true; - } else if (eventName === 'field') { - self.autoFields = true; - } - }); -} - -Form.prototype.parse = function(req, cb) { - var self = this; - - // if the user supplies a callback, this implies autoFields and autoFiles - if (cb) { - self.autoFields = true; - self.autoFiles = true; - } - - self.handleError = handleError; - self.bytesExpected = getBytesExpected(req.headers); - - req.on('error', handleError); - req.on('aborted', onReqAborted); - - var contentType = req.headers['content-type']; - if (!contentType) { - handleError(new Error('missing content-type header')); - return; - } - - var m = contentType.match(CONTENT_TYPE_RE); - if (!m) { - handleError(new Error('unrecognized content-type: ' + contentType)); - return; - } - var boundary = m[2] || m[3]; - setUpParser(self, boundary); - req.pipe(self); - - if (cb) { - var fieldsTable = {}; - var filesTable = {}; - var fieldsList = []; - var filesList = []; - self.on('error', function(err) { - cb(err); - }); - self.on('field', function(name, value) { - fieldsTable[name] = value; - fieldsList.push({name: name, value: value}); - }); - self.on('file', function(name, file) { - filesTable[name] = file; - filesList.push(file); - }); - self.on('close', function() { - cb(null, fieldsTable, filesTable, fieldsList, filesList); - }); - } - - function onReqAborted() { - self.emit('aborted'); - handleError(new Error("Request aborted")); - } - - function handleError(err) { - var first = !self.error; - if (first) { - self.error = err; - req.removeListener('aborted', onReqAborted); - - // welp. 0.8 doesn't support unpipe, too bad so sad. - // let's drop support for 0.8 soon. - if (req.unpipe) { - req.unpipe(self); - } - } - - self.openedFiles.forEach(function(file) { - file.ws.destroy(); - fs.unlink(file.path, function(err) { - // this is already an error condition, ignore 2nd error - }); - }); - self.openedFiles = []; - - if (first) { - self.emit('error', err); - } - } - -}; - -Form.prototype._write = function(buffer, encoding, cb) { - var self = this - , i = 0 - , len = buffer.length - , prevIndex = self.index - , index = self.index - , state = self.state - , lookbehind = self.lookbehind - , boundary = self.boundary - , boundaryChars = self.boundaryChars - , boundaryLength = self.boundary.length - , boundaryEnd = boundaryLength - 1 - , bufferLength = buffer.length - , c - , cl - - for (i = 0; i < len; i++) { - c = buffer[i]; - switch (state) { - case START: - index = 0; - state = START_BOUNDARY; - /* falls through */ - case START_BOUNDARY: - if (index === boundaryLength - 2) { - if (c !== CR) return self.handleError(new Error("Expected CR Received " + c)); - index++; - break; - } else if (index === boundaryLength - 1) { - if (c !== LF) return self.handleError(new Error("Expected LF Received " + c)); - index = 0; - self.onParsePartBegin(); - state = HEADER_FIELD_START; - break; - } - - if (c !== boundary[index+2]) index = -2; - if (c === boundary[index+2]) index++; - break; - case HEADER_FIELD_START: - state = HEADER_FIELD; - self.headerFieldMark = i; - index = 0; - /* falls through */ - case HEADER_FIELD: - if (c === CR) { - self.headerFieldMark = null; - state = HEADERS_ALMOST_DONE; - break; - } - - index++; - if (c === HYPHEN) break; - - if (c === COLON) { - if (index === 1) { - // empty header field - self.handleError(new Error("Empty header field")); - return; - } - self.onParseHeaderField(buffer.slice(self.headerFieldMark, i)); - self.headerFieldMark = null; - state = HEADER_VALUE_START; - break; - } - - cl = lower(c); - if (cl < A || cl > Z) { - self.handleError(new Error("Expected alphabetic character, received " + c)); - return; - } - break; - case HEADER_VALUE_START: - if (c === SPACE) break; - - self.headerValueMark = i; - state = HEADER_VALUE; - /* falls through */ - case HEADER_VALUE: - if (c === CR) { - self.onParseHeaderValue(buffer.slice(self.headerValueMark, i)); - self.headerValueMark = null; - self.onParseHeaderEnd(); - state = HEADER_VALUE_ALMOST_DONE; - } - break; - case HEADER_VALUE_ALMOST_DONE: - if (c !== LF) return self.handleError(new Error("Expected LF Received " + c)); - state = HEADER_FIELD_START; - break; - case HEADERS_ALMOST_DONE: - if (c !== LF) return self.handleError(new Error("Expected LF Received " + c)); - var err = self.onParseHeadersEnd(i + 1); - if (err) return self.handleError(err); - state = PART_DATA_START; - break; - case PART_DATA_START: - state = PART_DATA; - self.partDataMark = i; - /* falls through */ - case PART_DATA: - prevIndex = index; - - if (index === 0) { - // boyer-moore derrived algorithm to safely skip non-boundary data - i += boundaryEnd; - while (i < bufferLength && !(buffer[i] in boundaryChars)) { - i += boundaryLength; - } - i -= boundaryEnd; - c = buffer[i]; - } - - if (index < boundaryLength) { - if (boundary[index] === c) { - if (index === 0) { - self.onParsePartData(buffer.slice(self.partDataMark, i)); - self.partDataMark = null; - } - index++; - } else { - index = 0; - } - } else if (index === boundaryLength) { - index++; - if (c === CR) { - // CR = part boundary - self.partBoundaryFlag = true; - } else if (c === HYPHEN) { - // HYPHEN = end boundary - self.lastBoundaryFlag = true; - } else { - index = 0; - } - } else if (index - 1 === boundaryLength) { - if (self.partBoundaryFlag) { - index = 0; - if (c === LF) { - self.partBoundaryFlag = false; - self.onParsePartEnd(); - self.onParsePartBegin(); - state = HEADER_FIELD_START; - break; - } - } else if (self.lastBoundaryFlag) { - if (c === HYPHEN) { - self.onParsePartEnd(); - self.end(); - state = END; - } else { - index = 0; - } - } else { - index = 0; - } - } - - if (index > 0) { - // when matching a possible boundary, keep a lookbehind reference - // in case it turns out to be a false lead - lookbehind[index-1] = c; - } else if (prevIndex > 0) { - // if our boundary turned out to be rubbish, the captured lookbehind - // belongs to partData - self.onParsePartData(lookbehind.slice(0, prevIndex)); - prevIndex = 0; - self.partDataMark = i; - - // reconsider the current character even so it interrupted the sequence - // it could be the beginning of a new sequence - i--; - } - - break; - case END: - break; - default: - self.handleError(new Error("Parser has invalid state.")); - return; - } - } - - if (self.headerFieldMark != null) { - self.onParseHeaderField(buffer.slice(self.headerFieldMark)); - self.headerFieldMark = 0; - } - if (self.headerValueMark != null) { - self.onParseHeaderValue(buffer.slice(self.headerValueMark)); - self.headerValueMark = 0; - } - if (self.partDataMark != null) { - self.onParsePartData(buffer.slice(self.partDataMark)); - self.partDataMark = 0; - } - - self.index = index; - self.state = state; - - self.bytesReceived += buffer.length; - self.emit('progress', self.bytesReceived, self.bytesExpected); - - if (self.backpressure) { - self.writeCbs.push(cb); - } else { - cb(); - } -}; - -Form.prototype.onParsePartBegin = function() { - clearPartVars(this); -} - -Form.prototype.onParseHeaderField = function(b) { - this.headerField += this.headerFieldDecoder.write(b); -} - -Form.prototype.onParseHeaderValue = function(b) { - this.headerValue += this.headerValueDecoder.write(b); -} - -Form.prototype.onParseHeaderEnd = function() { - this.headerField = this.headerField.toLowerCase(); - this.partHeaders[this.headerField] = this.headerValue; - - var m; - if (this.headerField === 'content-disposition') { - if (m = this.headerValue.match(/\bname="([^"]+)"/i)) { - this.partName = m[1]; - } - this.partFilename = parseFilename(this.headerValue); - } else if (this.headerField === 'content-transfer-encoding') { - this.partTransferEncoding = this.headerValue.toLowerCase(); - } - - this.headerFieldDecoder = new StringDecoder(this.encoding); - this.headerField = ''; - this.headerValueDecoder = new StringDecoder(this.encoding); - this.headerValue = ''; -} - -Form.prototype.onParsePartData = function(b) { - if (this.partTransferEncoding === 'base64') { - this.backpressure = ! this.destStream.write(b.toString('ascii'), 'base64'); - } else { - this.backpressure = ! this.destStream.write(b); - } -} - -Form.prototype.onParsePartEnd = function() { - if (this.destStream) { - flushWriteCbs(this); - var s = this.destStream; - process.nextTick(function() { - s.end(); - }); - } - clearPartVars(this); -} - -Form.prototype.onParseHeadersEnd = function(offset) { - var self = this; - switch(self.partTransferEncoding){ - case 'binary': - case '7bit': - case '8bit': - self.partTransferEncoding = 'binary'; - break; - - case 'base64': break; - default: - return new Error("unknown transfer-encoding: " + self.partTransferEncoding); - } - - self.totalFieldCount += 1; - if (self.totalFieldCount >= self.maxFields) { - return new Error("maxFields " + self.maxFields + " exceeded."); - } - - self.destStream = new stream.PassThrough(); - self.destStream.on('drain', function() { - flushWriteCbs(self); - }); - self.destStream.headers = self.partHeaders; - self.destStream.name = self.partName; - self.destStream.filename = self.partFilename; - self.destStream.byteOffset = self.bytesReceived + offset; - var partContentLength = self.destStream.headers['content-length']; - self.destStream.byteCount = partContentLength ? - parseInt(partContentLength, 10) : - (self.bytesExpected - self.destStream.byteOffset - - self.boundary.length - LAST_BOUNDARY_SUFFIX_LEN); - - self.emit('part', self.destStream); - if (self.destStream.filename == null && self.autoFields) { - handleField(self, self.destStream); - } else if (self.destStream.filename != null && self.autoFiles) { - handleFile(self, self.destStream); - } -} - -function flushWriteCbs(self) { - self.writeCbs.forEach(function(cb) { - process.nextTick(cb); - }); - self.writeCbs = []; - self.backpressure = false; -} - -function getBytesExpected(headers) { - var contentLength = headers['content-length']; - if (contentLength) { - return parseInt(contentLength, 10); - } else if (headers['transfer-encoding'] == null) { - return 0; - } else { - return null; - } -} - -function beginFlush(self) { - self.flushing += 1; -} - -function endFlush(self) { - self.flushing -= 1; - maybeClose(self); -} - -function maybeClose(self) { - if (!self.flushing && self.finished && !self.error) { - self.emit('close'); - } -} - -function handleFile(self, fileStream) { - beginFlush(self); - var file = { - fieldName: fileStream.name, - originalFilename: fileStream.filename, - path: uploadPath(self.uploadDir, fileStream.filename), - headers: fileStream.headers, - }; - file.ws = fs.createWriteStream(file.path); - self.openedFiles.push(file); - fileStream.pipe(file.ws); - var counter = new StreamCounter(); - fileStream.pipe(counter); - var hashWorkaroundStream - , hash = null; - if (self.hash) { - // workaround stream because https://github.com/joyent/node/issues/5216 - hashWorkaroundStream = stream.Writable(); - hash = crypto.createHash(self.hash); - hashWorkaroundStream._write = function(buffer, encoding, callback) { - hash.update(buffer); - callback(); - }; - fileStream.pipe(hashWorkaroundStream); - } - file.ws.on('error', function(err) { - if (!self.error) self.handleError(err); - }); - file.ws.on('close', function() { - if (hash) file.hash = hash.digest('hex'); - file.size = counter.bytes; - self.emit('file', fileStream.name, file); - endFlush(self); - }); -} - -function handleField(self, fieldStream) { - var value = ''; - var decoder = new StringDecoder(self.encoding); - - beginFlush(self); - fieldStream.on('readable', function() { - var buffer = fieldStream.read(); - if (!buffer) return; - - self.totalFieldSize += buffer.length; - if (self.totalFieldSize > self.maxFieldsSize) { - self.handleError(new Error("maxFieldsSize " + self.maxFieldsSize + " exceeded")); - return; - } - value += decoder.write(buffer); - }); - - fieldStream.on('end', function() { - self.emit('field', fieldStream.name, value); - endFlush(self); - }); -} - -function clearPartVars(self) { - self.partHeaders = {}; - self.partName = null; - self.partFilename = null; - self.partTransferEncoding = 'binary'; - self.destStream = null; - - self.headerFieldDecoder = new StringDecoder(self.encoding); - self.headerField = ""; - self.headerValueDecoder = new StringDecoder(self.encoding); - self.headerValue = ""; -} - -function setUpParser(self, boundary) { - self.boundary = new Buffer(boundary.length + 4); - self.boundary.write('\r\n--', 0, boundary.length + 4, 'ascii'); - self.boundary.write(boundary, 4, boundary.length, 'ascii'); - self.lookbehind = new Buffer(self.boundary.length + 8); - self.state = START; - self.boundaryChars = {}; - for (var i = 0; i < self.boundary.length; i++) { - self.boundaryChars[self.boundary[i]] = true; - } - - self.index = null; - self.partBoundaryFlag = false; - self.lastBoundaryFlag = false; - - self.on('finish', function() { - if ((self.state === HEADER_FIELD_START && self.index === 0) || - (self.state === PART_DATA && self.index === self.boundary.length)) - { - self.onParsePartEnd(); - } else if (self.state !== END) { - self.handleError(new Error('stream ended unexpectedly')); - } - self.finished = true; - maybeClose(self); - }); -} - -function uploadPath(baseDir, filename) { - var ext = path.extname(filename).replace(FILE_EXT_RE, '$1'); - var name = process.pid + '-' + - (Math.random() * 0x100000000 + 1).toString(36) + ext; - return path.join(baseDir, name); -} - -function parseFilename(headerValue) { - var m = headerValue.match(/\bfilename="(.*?)"($|; )/i); - if (!m) return; - - var filename = m[1].substr(m[1].lastIndexOf('\\') + 1); - filename = filename.replace(/%22/g, '"'); - filename = filename.replace(/&#([\d]{4});/g, function(m, code) { - return String.fromCharCode(code); - }); - return filename; -} - -function lower(c) { - return c | 0x20; -} - diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/.npmignore b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/.npmignore deleted file mode 100644 index 38344f87a..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -build/ -test/ -examples/ -fs.js -zlib.js \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/LICENSE b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/LICENSE deleted file mode 100644 index e3d4e695a..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/README.md b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/README.md deleted file mode 100644 index be976683e..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/README.md +++ /dev/null @@ -1,768 +0,0 @@ -# readable-stream - -A new class of streams for Node.js - -This module provides the new Stream base classes introduced in Node -v0.10, for use in Node v0.8. You can use it to have programs that -have to work with node v0.8, while being forward-compatible for v0.10 -and beyond. When you drop support for v0.8, you can remove this -module, and only use the native streams. - -This is almost exactly the same codebase as appears in Node v0.10. -However: - -1. The exported object is actually the Readable class. Decorating the - native `stream` module would be global pollution. -2. In v0.10, you can safely use `base64` as an argument to - `setEncoding` in Readable streams. However, in v0.8, the - StringDecoder class has no `end()` method, which is problematic for - Base64. So, don't use that, because it'll break and be weird. - -Other than that, the API is the same as `require('stream')` in v0.10, -so the API docs are reproduced below. - ----------- - - Stability: 2 - Unstable - -A stream is an abstract interface implemented by various objects in -Node. For example a request to an HTTP server is a stream, as is -stdout. Streams are readable, writable, or both. All streams are -instances of [EventEmitter][] - -You can load the Stream base classes by doing `require('stream')`. -There are base classes provided for Readable streams, Writable -streams, Duplex streams, and Transform streams. - -## Compatibility - -In earlier versions of Node, the Readable stream interface was -simpler, but also less powerful and less useful. - -* Rather than waiting for you to call the `read()` method, `'data'` - events would start emitting immediately. If you needed to do some - I/O to decide how to handle data, then you had to store the chunks - in some kind of buffer so that they would not be lost. -* The `pause()` method was advisory, rather than guaranteed. This - meant that you still had to be prepared to receive `'data'` events - even when the stream was in a paused state. - -In Node v0.10, the Readable class described below was added. For -backwards compatibility with older Node programs, Readable streams -switch into "old mode" when a `'data'` event handler is added, or when -the `pause()` or `resume()` methods are called. The effect is that, -even if you are not using the new `read()` method and `'readable'` -event, you no longer have to worry about losing `'data'` chunks. - -Most programs will continue to function normally. However, this -introduces an edge case in the following conditions: - -* No `'data'` event handler is added. -* The `pause()` and `resume()` methods are never called. - -For example, consider the following code: - -```javascript -// WARNING! BROKEN! -net.createServer(function(socket) { - - // we add an 'end' method, but never consume the data - socket.on('end', function() { - // It will never get here. - socket.end('I got your message (but didnt read it)\n'); - }); - -}).listen(1337); -``` - -In versions of node prior to v0.10, the incoming message data would be -simply discarded. However, in Node v0.10 and beyond, the socket will -remain paused forever. - -The workaround in this situation is to call the `resume()` method to -trigger "old mode" behavior: - -```javascript -// Workaround -net.createServer(function(socket) { - - socket.on('end', function() { - socket.end('I got your message (but didnt read it)\n'); - }); - - // start the flow of data, discarding it. - socket.resume(); - -}).listen(1337); -``` - -In addition to new Readable streams switching into old-mode, pre-v0.10 -style streams can be wrapped in a Readable class using the `wrap()` -method. - -## Class: stream.Readable - - - -A `Readable Stream` has the following methods, members, and events. - -Note that `stream.Readable` is an abstract class designed to be -extended with an underlying implementation of the `_read(size)` -method. (See below.) - -### new stream.Readable([options]) - -* `options` {Object} - * `highWaterMark` {Number} The maximum number of bytes to store in - the internal buffer before ceasing to read from the underlying - resource. Default=16kb - * `encoding` {String} If specified, then buffers will be decoded to - strings using the specified encoding. Default=null - * `objectMode` {Boolean} Whether this stream should behave - as a stream of objects. Meaning that stream.read(n) returns - a single value instead of a Buffer of size n - -In classes that extend the Readable class, make sure to call the -constructor so that the buffering settings can be properly -initialized. - -### readable.\_read(size) - -* `size` {Number} Number of bytes to read asynchronously - -Note: **This function should NOT be called directly.** It should be -implemented by child classes, and called by the internal Readable -class methods only. - -All Readable stream implementations must provide a `_read` method -to fetch data from the underlying resource. - -This method is prefixed with an underscore because it is internal to -the class that defines it, and should not be called directly by user -programs. However, you **are** expected to override this method in -your own extension classes. - -When data is available, put it into the read queue by calling -`readable.push(chunk)`. If `push` returns false, then you should stop -reading. When `_read` is called again, you should start pushing more -data. - -The `size` argument is advisory. Implementations where a "read" is a -single call that returns data can use this to know how much data to -fetch. Implementations where that is not relevant, such as TCP or -TLS, may ignore this argument, and simply provide data whenever it -becomes available. There is no need, for example to "wait" until -`size` bytes are available before calling `stream.push(chunk)`. - -### readable.push(chunk) - -* `chunk` {Buffer | null | String} Chunk of data to push into the read queue -* return {Boolean} Whether or not more pushes should be performed - -Note: **This function should be called by Readable implementors, NOT -by consumers of Readable subclasses.** The `_read()` function will not -be called again until at least one `push(chunk)` call is made. If no -data is available, then you MAY call `push('')` (an empty string) to -allow a future `_read` call, without adding any data to the queue. - -The `Readable` class works by putting data into a read queue to be -pulled out later by calling the `read()` method when the `'readable'` -event fires. - -The `push()` method will explicitly insert some data into the read -queue. If it is called with `null` then it will signal the end of the -data. - -In some cases, you may be wrapping a lower-level source which has some -sort of pause/resume mechanism, and a data callback. In those cases, -you could wrap the low-level source object by doing something like -this: - -```javascript -// source is an object with readStop() and readStart() methods, -// and an `ondata` member that gets called when it has data, and -// an `onend` member that gets called when the data is over. - -var stream = new Readable(); - -source.ondata = function(chunk) { - // if push() returns false, then we need to stop reading from source - if (!stream.push(chunk)) - source.readStop(); -}; - -source.onend = function() { - stream.push(null); -}; - -// _read will be called when the stream wants to pull more data in -// the advisory size argument is ignored in this case. -stream._read = function(n) { - source.readStart(); -}; -``` - -### readable.unshift(chunk) - -* `chunk` {Buffer | null | String} Chunk of data to unshift onto the read queue -* return {Boolean} Whether or not more pushes should be performed - -This is the corollary of `readable.push(chunk)`. Rather than putting -the data at the *end* of the read queue, it puts it at the *front* of -the read queue. - -This is useful in certain use-cases where a stream is being consumed -by a parser, which needs to "un-consume" some data that it has -optimistically pulled out of the source. - -```javascript -// A parser for a simple data protocol. -// The "header" is a JSON object, followed by 2 \n characters, and -// then a message body. -// -// Note: This can be done more simply as a Transform stream. See below. - -function SimpleProtocol(source, options) { - if (!(this instanceof SimpleProtocol)) - return new SimpleProtocol(options); - - Readable.call(this, options); - this._inBody = false; - this._sawFirstCr = false; - - // source is a readable stream, such as a socket or file - this._source = source; - - var self = this; - source.on('end', function() { - self.push(null); - }); - - // give it a kick whenever the source is readable - // read(0) will not consume any bytes - source.on('readable', function() { - self.read(0); - }); - - this._rawHeader = []; - this.header = null; -} - -SimpleProtocol.prototype = Object.create( - Readable.prototype, { constructor: { value: SimpleProtocol }}); - -SimpleProtocol.prototype._read = function(n) { - if (!this._inBody) { - var chunk = this._source.read(); - - // if the source doesn't have data, we don't have data yet. - if (chunk === null) - return this.push(''); - - // check if the chunk has a \n\n - var split = -1; - for (var i = 0; i < chunk.length; i++) { - if (chunk[i] === 10) { // '\n' - if (this._sawFirstCr) { - split = i; - break; - } else { - this._sawFirstCr = true; - } - } else { - this._sawFirstCr = false; - } - } - - if (split === -1) { - // still waiting for the \n\n - // stash the chunk, and try again. - this._rawHeader.push(chunk); - this.push(''); - } else { - this._inBody = true; - var h = chunk.slice(0, split); - this._rawHeader.push(h); - var header = Buffer.concat(this._rawHeader).toString(); - try { - this.header = JSON.parse(header); - } catch (er) { - this.emit('error', new Error('invalid simple protocol data')); - return; - } - // now, because we got some extra data, unshift the rest - // back into the read queue so that our consumer will see it. - var b = chunk.slice(split); - this.unshift(b); - - // and let them know that we are done parsing the header. - this.emit('header', this.header); - } - } else { - // from there on, just provide the data to our consumer. - // careful not to push(null), since that would indicate EOF. - var chunk = this._source.read(); - if (chunk) this.push(chunk); - } -}; - -// Usage: -var parser = new SimpleProtocol(source); -// Now parser is a readable stream that will emit 'header' -// with the parsed header data. -``` - -### readable.wrap(stream) - -* `stream` {Stream} An "old style" readable stream - -If you are using an older Node library that emits `'data'` events and -has a `pause()` method that is advisory only, then you can use the -`wrap()` method to create a Readable stream that uses the old stream -as its data source. - -For example: - -```javascript -var OldReader = require('./old-api-module.js').OldReader; -var oreader = new OldReader; -var Readable = require('stream').Readable; -var myReader = new Readable().wrap(oreader); - -myReader.on('readable', function() { - myReader.read(); // etc. -}); -``` - -### Event: 'readable' - -When there is data ready to be consumed, this event will fire. - -When this event emits, call the `read()` method to consume the data. - -### Event: 'end' - -Emitted when the stream has received an EOF (FIN in TCP terminology). -Indicates that no more `'data'` events will happen. If the stream is -also writable, it may be possible to continue writing. - -### Event: 'data' - -The `'data'` event emits either a `Buffer` (by default) or a string if -`setEncoding()` was used. - -Note that adding a `'data'` event listener will switch the Readable -stream into "old mode", where data is emitted as soon as it is -available, rather than waiting for you to call `read()` to consume it. - -### Event: 'error' - -Emitted if there was an error receiving data. - -### Event: 'close' - -Emitted when the underlying resource (for example, the backing file -descriptor) has been closed. Not all streams will emit this. - -### readable.setEncoding(encoding) - -Makes the `'data'` event emit a string instead of a `Buffer`. `encoding` -can be `'utf8'`, `'utf16le'` (`'ucs2'`), `'ascii'`, or `'hex'`. - -The encoding can also be set by specifying an `encoding` field to the -constructor. - -### readable.read([size]) - -* `size` {Number | null} Optional number of bytes to read. -* Return: {Buffer | String | null} - -Note: **This function SHOULD be called by Readable stream users.** - -Call this method to consume data once the `'readable'` event is -emitted. - -The `size` argument will set a minimum number of bytes that you are -interested in. If not set, then the entire content of the internal -buffer is returned. - -If there is no data to consume, or if there are fewer bytes in the -internal buffer than the `size` argument, then `null` is returned, and -a future `'readable'` event will be emitted when more is available. - -Calling `stream.read(0)` will always return `null`, and will trigger a -refresh of the internal buffer, but otherwise be a no-op. - -### readable.pipe(destination, [options]) - -* `destination` {Writable Stream} -* `options` {Object} Optional - * `end` {Boolean} Default=true - -Connects this readable stream to `destination` WriteStream. Incoming -data on this stream gets written to `destination`. Properly manages -back-pressure so that a slow destination will not be overwhelmed by a -fast readable stream. - -This function returns the `destination` stream. - -For example, emulating the Unix `cat` command: - - process.stdin.pipe(process.stdout); - -By default `end()` is called on the destination when the source stream -emits `end`, so that `destination` is no longer writable. Pass `{ end: -false }` as `options` to keep the destination stream open. - -This keeps `writer` open so that "Goodbye" can be written at the -end. - - reader.pipe(writer, { end: false }); - reader.on("end", function() { - writer.end("Goodbye\n"); - }); - -Note that `process.stderr` and `process.stdout` are never closed until -the process exits, regardless of the specified options. - -### readable.unpipe([destination]) - -* `destination` {Writable Stream} Optional - -Undo a previously established `pipe()`. If no destination is -provided, then all previously established pipes are removed. - -### readable.pause() - -Switches the readable stream into "old mode", where data is emitted -using a `'data'` event rather than being buffered for consumption via -the `read()` method. - -Ceases the flow of data. No `'data'` events are emitted while the -stream is in a paused state. - -### readable.resume() - -Switches the readable stream into "old mode", where data is emitted -using a `'data'` event rather than being buffered for consumption via -the `read()` method. - -Resumes the incoming `'data'` events after a `pause()`. - - -## Class: stream.Writable - - - -A `Writable` Stream has the following methods, members, and events. - -Note that `stream.Writable` is an abstract class designed to be -extended with an underlying implementation of the -`_write(chunk, encoding, cb)` method. (See below.) - -### new stream.Writable([options]) - -* `options` {Object} - * `highWaterMark` {Number} Buffer level when `write()` starts - returning false. Default=16kb - * `decodeStrings` {Boolean} Whether or not to decode strings into - Buffers before passing them to `_write()`. Default=true - -In classes that extend the Writable class, make sure to call the -constructor so that the buffering settings can be properly -initialized. - -### writable.\_write(chunk, encoding, callback) - -* `chunk` {Buffer | String} The chunk to be written. Will always - be a buffer unless the `decodeStrings` option was set to `false`. -* `encoding` {String} If the chunk is a string, then this is the - encoding type. Ignore chunk is a buffer. Note that chunk will - **always** be a buffer unless the `decodeStrings` option is - explicitly set to `false`. -* `callback` {Function} Call this function (optionally with an error - argument) when you are done processing the supplied chunk. - -All Writable stream implementations must provide a `_write` method to -send data to the underlying resource. - -Note: **This function MUST NOT be called directly.** It should be -implemented by child classes, and called by the internal Writable -class methods only. - -Call the callback using the standard `callback(error)` pattern to -signal that the write completed successfully or with an error. - -If the `decodeStrings` flag is set in the constructor options, then -`chunk` may be a string rather than a Buffer, and `encoding` will -indicate the sort of string that it is. This is to support -implementations that have an optimized handling for certain string -data encodings. If you do not explicitly set the `decodeStrings` -option to `false`, then you can safely ignore the `encoding` argument, -and assume that `chunk` will always be a Buffer. - -This method is prefixed with an underscore because it is internal to -the class that defines it, and should not be called directly by user -programs. However, you **are** expected to override this method in -your own extension classes. - - -### writable.write(chunk, [encoding], [callback]) - -* `chunk` {Buffer | String} Data to be written -* `encoding` {String} Optional. If `chunk` is a string, then encoding - defaults to `'utf8'` -* `callback` {Function} Optional. Called when this chunk is - successfully written. -* Returns {Boolean} - -Writes `chunk` to the stream. Returns `true` if the data has been -flushed to the underlying resource. Returns `false` to indicate that -the buffer is full, and the data will be sent out in the future. The -`'drain'` event will indicate when the buffer is empty again. - -The specifics of when `write()` will return false, is determined by -the `highWaterMark` option provided to the constructor. - -### writable.end([chunk], [encoding], [callback]) - -* `chunk` {Buffer | String} Optional final data to be written -* `encoding` {String} Optional. If `chunk` is a string, then encoding - defaults to `'utf8'` -* `callback` {Function} Optional. Called when the final chunk is - successfully written. - -Call this method to signal the end of the data being written to the -stream. - -### Event: 'drain' - -Emitted when the stream's write queue empties and it's safe to write -without buffering again. Listen for it when `stream.write()` returns -`false`. - -### Event: 'close' - -Emitted when the underlying resource (for example, the backing file -descriptor) has been closed. Not all streams will emit this. - -### Event: 'finish' - -When `end()` is called and there are no more chunks to write, this -event is emitted. - -### Event: 'pipe' - -* `source` {Readable Stream} - -Emitted when the stream is passed to a readable stream's pipe method. - -### Event 'unpipe' - -* `source` {Readable Stream} - -Emitted when a previously established `pipe()` is removed using the -source Readable stream's `unpipe()` method. - -## Class: stream.Duplex - - - -A "duplex" stream is one that is both Readable and Writable, such as a -TCP socket connection. - -Note that `stream.Duplex` is an abstract class designed to be -extended with an underlying implementation of the `_read(size)` -and `_write(chunk, encoding, callback)` methods as you would with a Readable or -Writable stream class. - -Since JavaScript doesn't have multiple prototypal inheritance, this -class prototypally inherits from Readable, and then parasitically from -Writable. It is thus up to the user to implement both the lowlevel -`_read(n)` method as well as the lowlevel `_write(chunk, encoding, cb)` method -on extension duplex classes. - -### new stream.Duplex(options) - -* `options` {Object} Passed to both Writable and Readable - constructors. Also has the following fields: - * `allowHalfOpen` {Boolean} Default=true. If set to `false`, then - the stream will automatically end the readable side when the - writable side ends and vice versa. - -In classes that extend the Duplex class, make sure to call the -constructor so that the buffering settings can be properly -initialized. - -## Class: stream.Transform - -A "transform" stream is a duplex stream where the output is causally -connected in some way to the input, such as a zlib stream or a crypto -stream. - -There is no requirement that the output be the same size as the input, -the same number of chunks, or arrive at the same time. For example, a -Hash stream will only ever have a single chunk of output which is -provided when the input is ended. A zlib stream will either produce -much smaller or much larger than its input. - -Rather than implement the `_read()` and `_write()` methods, Transform -classes must implement the `_transform()` method, and may optionally -also implement the `_flush()` method. (See below.) - -### new stream.Transform([options]) - -* `options` {Object} Passed to both Writable and Readable - constructors. - -In classes that extend the Transform class, make sure to call the -constructor so that the buffering settings can be properly -initialized. - -### transform.\_transform(chunk, encoding, callback) - -* `chunk` {Buffer | String} The chunk to be transformed. Will always - be a buffer unless the `decodeStrings` option was set to `false`. -* `encoding` {String} If the chunk is a string, then this is the - encoding type. (Ignore if `decodeStrings` chunk is a buffer.) -* `callback` {Function} Call this function (optionally with an error - argument) when you are done processing the supplied chunk. - -Note: **This function MUST NOT be called directly.** It should be -implemented by child classes, and called by the internal Transform -class methods only. - -All Transform stream implementations must provide a `_transform` -method to accept input and produce output. - -`_transform` should do whatever has to be done in this specific -Transform class, to handle the bytes being written, and pass them off -to the readable portion of the interface. Do asynchronous I/O, -process things, and so on. - -Call `transform.push(outputChunk)` 0 or more times to generate output -from this input chunk, depending on how much data you want to output -as a result of this chunk. - -Call the callback function only when the current chunk is completely -consumed. Note that there may or may not be output as a result of any -particular input chunk. - -This method is prefixed with an underscore because it is internal to -the class that defines it, and should not be called directly by user -programs. However, you **are** expected to override this method in -your own extension classes. - -### transform.\_flush(callback) - -* `callback` {Function} Call this function (optionally with an error - argument) when you are done flushing any remaining data. - -Note: **This function MUST NOT be called directly.** It MAY be implemented -by child classes, and if so, will be called by the internal Transform -class methods only. - -In some cases, your transform operation may need to emit a bit more -data at the end of the stream. For example, a `Zlib` compression -stream will store up some internal state so that it can optimally -compress the output. At the end, however, it needs to do the best it -can with what is left, so that the data will be complete. - -In those cases, you can implement a `_flush` method, which will be -called at the very end, after all the written data is consumed, but -before emitting `end` to signal the end of the readable side. Just -like with `_transform`, call `transform.push(chunk)` zero or more -times, as appropriate, and call `callback` when the flush operation is -complete. - -This method is prefixed with an underscore because it is internal to -the class that defines it, and should not be called directly by user -programs. However, you **are** expected to override this method in -your own extension classes. - -### Example: `SimpleProtocol` parser - -The example above of a simple protocol parser can be implemented much -more simply by using the higher level `Transform` stream class. - -In this example, rather than providing the input as an argument, it -would be piped into the parser, which is a more idiomatic Node stream -approach. - -```javascript -function SimpleProtocol(options) { - if (!(this instanceof SimpleProtocol)) - return new SimpleProtocol(options); - - Transform.call(this, options); - this._inBody = false; - this._sawFirstCr = false; - this._rawHeader = []; - this.header = null; -} - -SimpleProtocol.prototype = Object.create( - Transform.prototype, { constructor: { value: SimpleProtocol }}); - -SimpleProtocol.prototype._transform = function(chunk, encoding, done) { - if (!this._inBody) { - // check if the chunk has a \n\n - var split = -1; - for (var i = 0; i < chunk.length; i++) { - if (chunk[i] === 10) { // '\n' - if (this._sawFirstCr) { - split = i; - break; - } else { - this._sawFirstCr = true; - } - } else { - this._sawFirstCr = false; - } - } - - if (split === -1) { - // still waiting for the \n\n - // stash the chunk, and try again. - this._rawHeader.push(chunk); - } else { - this._inBody = true; - var h = chunk.slice(0, split); - this._rawHeader.push(h); - var header = Buffer.concat(this._rawHeader).toString(); - try { - this.header = JSON.parse(header); - } catch (er) { - this.emit('error', new Error('invalid simple protocol data')); - return; - } - // and let them know that we are done parsing the header. - this.emit('header', this.header); - - // now, because we got some extra data, emit this first. - this.push(b); - } - } else { - // from there on, just provide the data to our consumer as-is. - this.push(b); - } - done(); -}; - -var parser = new SimpleProtocol(); -source.pipe(parser) - -// Now parser is a readable stream that will emit 'header' -// with the parsed header data. -``` - - -## Class: stream.PassThrough - -This is a trivial implementation of a `Transform` stream that simply -passes the input bytes across to the output. Its purpose is mainly -for examples and testing, but there are occasionally use cases where -it can come in handy. - - -[EventEmitter]: events.html#events_class_events_eventemitter diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/duplex.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/duplex.js deleted file mode 100644 index ca807af87..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/duplex.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_duplex.js") diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/float.patch b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/float.patch deleted file mode 100644 index b984607a4..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/float.patch +++ /dev/null @@ -1,923 +0,0 @@ -diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js -index c5a741c..a2e0d8e 100644 ---- a/lib/_stream_duplex.js -+++ b/lib/_stream_duplex.js -@@ -26,8 +26,8 @@ - - module.exports = Duplex; - var util = require('util'); --var Readable = require('_stream_readable'); --var Writable = require('_stream_writable'); -+var Readable = require('./_stream_readable'); -+var Writable = require('./_stream_writable'); - - util.inherits(Duplex, Readable); - -diff --git a/lib/_stream_passthrough.js b/lib/_stream_passthrough.js -index a5e9864..330c247 100644 ---- a/lib/_stream_passthrough.js -+++ b/lib/_stream_passthrough.js -@@ -25,7 +25,7 @@ - - module.exports = PassThrough; - --var Transform = require('_stream_transform'); -+var Transform = require('./_stream_transform'); - var util = require('util'); - util.inherits(PassThrough, Transform); - -diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js -index 0c3fe3e..90a8298 100644 ---- a/lib/_stream_readable.js -+++ b/lib/_stream_readable.js -@@ -23,10 +23,34 @@ module.exports = Readable; - Readable.ReadableState = ReadableState; - - var EE = require('events').EventEmitter; -+if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { -+ return emitter.listeners(type).length; -+}; -+ -+if (!global.setImmediate) global.setImmediate = function setImmediate(fn) { -+ return setTimeout(fn, 0); -+}; -+if (!global.clearImmediate) global.clearImmediate = function clearImmediate(i) { -+ return clearTimeout(i); -+}; -+ - var Stream = require('stream'); - var util = require('util'); -+if (!util.isUndefined) { -+ var utilIs = require('core-util-is'); -+ for (var f in utilIs) { -+ util[f] = utilIs[f]; -+ } -+} - var StringDecoder; --var debug = util.debuglog('stream'); -+var debug; -+if (util.debuglog) -+ debug = util.debuglog('stream'); -+else try { -+ debug = require('debuglog')('stream'); -+} catch (er) { -+ debug = function() {}; -+} - - util.inherits(Readable, Stream); - -@@ -380,7 +404,7 @@ function chunkInvalid(state, chunk) { - - - function onEofChunk(stream, state) { -- if (state.decoder && !state.ended) { -+ if (state.decoder && !state.ended && state.decoder.end) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); -diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js -index b1f9fcc..b0caf57 100644 ---- a/lib/_stream_transform.js -+++ b/lib/_stream_transform.js -@@ -64,8 +64,14 @@ - - module.exports = Transform; - --var Duplex = require('_stream_duplex'); -+var Duplex = require('./_stream_duplex'); - var util = require('util'); -+if (!util.isUndefined) { -+ var utilIs = require('core-util-is'); -+ for (var f in utilIs) { -+ util[f] = utilIs[f]; -+ } -+} - util.inherits(Transform, Duplex); - - -diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js -index ba2e920..f49288b 100644 ---- a/lib/_stream_writable.js -+++ b/lib/_stream_writable.js -@@ -27,6 +27,12 @@ module.exports = Writable; - Writable.WritableState = WritableState; - - var util = require('util'); -+if (!util.isUndefined) { -+ var utilIs = require('core-util-is'); -+ for (var f in utilIs) { -+ util[f] = utilIs[f]; -+ } -+} - var Stream = require('stream'); - - util.inherits(Writable, Stream); -@@ -119,7 +125,7 @@ function WritableState(options, stream) { - function Writable(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. -- if (!(this instanceof Writable) && !(this instanceof Stream.Duplex)) -+ if (!(this instanceof Writable) && !(this instanceof require('./_stream_duplex'))) - return new Writable(options); - - this._writableState = new WritableState(options, this); -diff --git a/test/simple/test-stream-big-push.js b/test/simple/test-stream-big-push.js -index e3787e4..8cd2127 100644 ---- a/test/simple/test-stream-big-push.js -+++ b/test/simple/test-stream-big-push.js -@@ -21,7 +21,7 @@ - - var common = require('../common'); - var assert = require('assert'); --var stream = require('stream'); -+var stream = require('../../'); - var str = 'asdfasdfasdfasdfasdf'; - - var r = new stream.Readable({ -diff --git a/test/simple/test-stream-end-paused.js b/test/simple/test-stream-end-paused.js -index bb73777..d40efc7 100644 ---- a/test/simple/test-stream-end-paused.js -+++ b/test/simple/test-stream-end-paused.js -@@ -25,7 +25,7 @@ var gotEnd = false; - - // Make sure we don't miss the end event for paused 0-length streams - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var stream = new Readable(); - var calledRead = false; - stream._read = function() { -diff --git a/test/simple/test-stream-pipe-after-end.js b/test/simple/test-stream-pipe-after-end.js -index b46ee90..0be8366 100644 ---- a/test/simple/test-stream-pipe-after-end.js -+++ b/test/simple/test-stream-pipe-after-end.js -@@ -22,8 +22,8 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('_stream_readable'); --var Writable = require('_stream_writable'); -+var Readable = require('../../lib/_stream_readable'); -+var Writable = require('../../lib/_stream_writable'); - var util = require('util'); - - util.inherits(TestReadable, Readable); -diff --git a/test/simple/test-stream-pipe-cleanup.js b/test/simple/test-stream-pipe-cleanup.js -deleted file mode 100644 -index f689358..0000000 ---- a/test/simple/test-stream-pipe-cleanup.js -+++ /dev/null -@@ -1,122 +0,0 @@ --// Copyright Joyent, Inc. and other Node contributors. --// --// Permission is hereby granted, free of charge, to any person obtaining a --// copy of this software and associated documentation files (the --// "Software"), to deal in the Software without restriction, including --// without limitation the rights to use, copy, modify, merge, publish, --// distribute, sublicense, and/or sell copies of the Software, and to permit --// persons to whom the Software is furnished to do so, subject to the --// following conditions: --// --// The above copyright notice and this permission notice shall be included --// in all copies or substantial portions of the Software. --// --// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN --// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE --// USE OR OTHER DEALINGS IN THE SOFTWARE. -- --// This test asserts that Stream.prototype.pipe does not leave listeners --// hanging on the source or dest. -- --var common = require('../common'); --var stream = require('stream'); --var assert = require('assert'); --var util = require('util'); -- --function Writable() { -- this.writable = true; -- this.endCalls = 0; -- stream.Stream.call(this); --} --util.inherits(Writable, stream.Stream); --Writable.prototype.end = function() { -- this.endCalls++; --}; -- --Writable.prototype.destroy = function() { -- this.endCalls++; --}; -- --function Readable() { -- this.readable = true; -- stream.Stream.call(this); --} --util.inherits(Readable, stream.Stream); -- --function Duplex() { -- this.readable = true; -- Writable.call(this); --} --util.inherits(Duplex, Writable); -- --var i = 0; --var limit = 100; -- --var w = new Writable(); -- --var r; -- --for (i = 0; i < limit; i++) { -- r = new Readable(); -- r.pipe(w); -- r.emit('end'); --} --assert.equal(0, r.listeners('end').length); --assert.equal(limit, w.endCalls); -- --w.endCalls = 0; -- --for (i = 0; i < limit; i++) { -- r = new Readable(); -- r.pipe(w); -- r.emit('close'); --} --assert.equal(0, r.listeners('close').length); --assert.equal(limit, w.endCalls); -- --w.endCalls = 0; -- --r = new Readable(); -- --for (i = 0; i < limit; i++) { -- w = new Writable(); -- r.pipe(w); -- w.emit('close'); --} --assert.equal(0, w.listeners('close').length); -- --r = new Readable(); --w = new Writable(); --var d = new Duplex(); --r.pipe(d); // pipeline A --d.pipe(w); // pipeline B --assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup --assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup --assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup --assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup --assert.equal(w.listeners('end').length, 0); --assert.equal(w.listeners('close').length, 1); // B.cleanup -- --r.emit('end'); --assert.equal(d.endCalls, 1); --assert.equal(w.endCalls, 0); --assert.equal(r.listeners('end').length, 0); --assert.equal(r.listeners('close').length, 0); --assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup --assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup --assert.equal(w.listeners('end').length, 0); --assert.equal(w.listeners('close').length, 1); // B.cleanup -- --d.emit('end'); --assert.equal(d.endCalls, 1); --assert.equal(w.endCalls, 1); --assert.equal(r.listeners('end').length, 0); --assert.equal(r.listeners('close').length, 0); --assert.equal(d.listeners('end').length, 0); --assert.equal(d.listeners('close').length, 0); --assert.equal(w.listeners('end').length, 0); --assert.equal(w.listeners('close').length, 0); -diff --git a/test/simple/test-stream-pipe-error-handling.js b/test/simple/test-stream-pipe-error-handling.js -index c5d724b..c7d6b7d 100644 ---- a/test/simple/test-stream-pipe-error-handling.js -+++ b/test/simple/test-stream-pipe-error-handling.js -@@ -21,7 +21,7 @@ - - var common = require('../common'); - var assert = require('assert'); --var Stream = require('stream').Stream; -+var Stream = require('../../').Stream; - - (function testErrorListenerCatches() { - var source = new Stream(); -diff --git a/test/simple/test-stream-pipe-event.js b/test/simple/test-stream-pipe-event.js -index cb9d5fe..56f8d61 100644 ---- a/test/simple/test-stream-pipe-event.js -+++ b/test/simple/test-stream-pipe-event.js -@@ -20,7 +20,7 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common'); --var stream = require('stream'); -+var stream = require('../../'); - var assert = require('assert'); - var util = require('util'); - -diff --git a/test/simple/test-stream-push-order.js b/test/simple/test-stream-push-order.js -index f2e6ec2..a5c9bf9 100644 ---- a/test/simple/test-stream-push-order.js -+++ b/test/simple/test-stream-push-order.js -@@ -20,7 +20,7 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common.js'); --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var assert = require('assert'); - - var s = new Readable({ -diff --git a/test/simple/test-stream-push-strings.js b/test/simple/test-stream-push-strings.js -index 06f43dc..1701a9a 100644 ---- a/test/simple/test-stream-push-strings.js -+++ b/test/simple/test-stream-push-strings.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var util = require('util'); - - util.inherits(MyStream, Readable); -diff --git a/test/simple/test-stream-readable-event.js b/test/simple/test-stream-readable-event.js -index ba6a577..a8e6f7b 100644 ---- a/test/simple/test-stream-readable-event.js -+++ b/test/simple/test-stream-readable-event.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - - (function first() { - // First test, not reading when the readable is added. -diff --git a/test/simple/test-stream-readable-flow-recursion.js b/test/simple/test-stream-readable-flow-recursion.js -index 2891ad6..11689ba 100644 ---- a/test/simple/test-stream-readable-flow-recursion.js -+++ b/test/simple/test-stream-readable-flow-recursion.js -@@ -27,7 +27,7 @@ var assert = require('assert'); - // more data continuously, but without triggering a nextTick - // warning or RangeError. - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - - // throw an error if we trigger a nextTick warning. - process.throwDeprecation = true; -diff --git a/test/simple/test-stream-unshift-empty-chunk.js b/test/simple/test-stream-unshift-empty-chunk.js -index 0c96476..7827538 100644 ---- a/test/simple/test-stream-unshift-empty-chunk.js -+++ b/test/simple/test-stream-unshift-empty-chunk.js -@@ -24,7 +24,7 @@ var assert = require('assert'); - - // This test verifies that stream.unshift(Buffer(0)) or - // stream.unshift('') does not set state.reading=false. --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - - var r = new Readable(); - var nChunks = 10; -diff --git a/test/simple/test-stream-unshift-read-race.js b/test/simple/test-stream-unshift-read-race.js -index 83fd9fa..17c18aa 100644 ---- a/test/simple/test-stream-unshift-read-race.js -+++ b/test/simple/test-stream-unshift-read-race.js -@@ -29,7 +29,7 @@ var assert = require('assert'); - // 3. push() after the EOF signaling null is an error. - // 4. _read() is not called after pushing the EOF null chunk. - --var stream = require('stream'); -+var stream = require('../../'); - var hwm = 10; - var r = stream.Readable({ highWaterMark: hwm }); - var chunks = 10; -@@ -51,7 +51,14 @@ r._read = function(n) { - - function push(fast) { - assert(!pushedNull, 'push() after null push'); -- var c = pos >= data.length ? null : data.slice(pos, pos + n); -+ var c; -+ if (pos >= data.length) -+ c = null; -+ else { -+ if (n + pos > data.length) -+ n = data.length - pos; -+ c = data.slice(pos, pos + n); -+ } - pushedNull = c === null; - if (fast) { - pos += n; -diff --git a/test/simple/test-stream-writev.js b/test/simple/test-stream-writev.js -index 5b49e6e..b5321f3 100644 ---- a/test/simple/test-stream-writev.js -+++ b/test/simple/test-stream-writev.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var stream = require('stream'); -+var stream = require('../../'); - - var queue = []; - for (var decode = 0; decode < 2; decode++) { -diff --git a/test/simple/test-stream2-basic.js b/test/simple/test-stream2-basic.js -index 3814bf0..248c1be 100644 ---- a/test/simple/test-stream2-basic.js -+++ b/test/simple/test-stream2-basic.js -@@ -21,7 +21,7 @@ - - - var common = require('../common.js'); --var R = require('_stream_readable'); -+var R = require('../../lib/_stream_readable'); - var assert = require('assert'); - - var util = require('util'); -diff --git a/test/simple/test-stream2-compatibility.js b/test/simple/test-stream2-compatibility.js -index 6cdd4e9..f0fa84b 100644 ---- a/test/simple/test-stream2-compatibility.js -+++ b/test/simple/test-stream2-compatibility.js -@@ -21,7 +21,7 @@ - - - var common = require('../common.js'); --var R = require('_stream_readable'); -+var R = require('../../lib/_stream_readable'); - var assert = require('assert'); - - var util = require('util'); -diff --git a/test/simple/test-stream2-finish-pipe.js b/test/simple/test-stream2-finish-pipe.js -index 39b274f..006a19b 100644 ---- a/test/simple/test-stream2-finish-pipe.js -+++ b/test/simple/test-stream2-finish-pipe.js -@@ -20,7 +20,7 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common.js'); --var stream = require('stream'); -+var stream = require('../../'); - var Buffer = require('buffer').Buffer; - - var r = new stream.Readable(); -diff --git a/test/simple/test-stream2-fs.js b/test/simple/test-stream2-fs.js -deleted file mode 100644 -index e162406..0000000 ---- a/test/simple/test-stream2-fs.js -+++ /dev/null -@@ -1,72 +0,0 @@ --// Copyright Joyent, Inc. and other Node contributors. --// --// Permission is hereby granted, free of charge, to any person obtaining a --// copy of this software and associated documentation files (the --// "Software"), to deal in the Software without restriction, including --// without limitation the rights to use, copy, modify, merge, publish, --// distribute, sublicense, and/or sell copies of the Software, and to permit --// persons to whom the Software is furnished to do so, subject to the --// following conditions: --// --// The above copyright notice and this permission notice shall be included --// in all copies or substantial portions of the Software. --// --// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN --// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE --// USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- --var common = require('../common.js'); --var R = require('_stream_readable'); --var assert = require('assert'); -- --var fs = require('fs'); --var FSReadable = fs.ReadStream; -- --var path = require('path'); --var file = path.resolve(common.fixturesDir, 'x1024.txt'); -- --var size = fs.statSync(file).size; -- --var expectLengths = [1024]; -- --var util = require('util'); --var Stream = require('stream'); -- --util.inherits(TestWriter, Stream); -- --function TestWriter() { -- Stream.apply(this); -- this.buffer = []; -- this.length = 0; --} -- --TestWriter.prototype.write = function(c) { -- this.buffer.push(c.toString()); -- this.length += c.length; -- return true; --}; -- --TestWriter.prototype.end = function(c) { -- if (c) this.buffer.push(c.toString()); -- this.emit('results', this.buffer); --} -- --var r = new FSReadable(file); --var w = new TestWriter(); -- --w.on('results', function(res) { -- console.error(res, w.length); -- assert.equal(w.length, size); -- var l = 0; -- assert.deepEqual(res.map(function (c) { -- return c.length; -- }), expectLengths); -- console.log('ok'); --}); -- --r.pipe(w); -diff --git a/test/simple/test-stream2-httpclient-response-end.js b/test/simple/test-stream2-httpclient-response-end.js -deleted file mode 100644 -index 15cffc2..0000000 ---- a/test/simple/test-stream2-httpclient-response-end.js -+++ /dev/null -@@ -1,52 +0,0 @@ --// Copyright Joyent, Inc. and other Node contributors. --// --// Permission is hereby granted, free of charge, to any person obtaining a --// copy of this software and associated documentation files (the --// "Software"), to deal in the Software without restriction, including --// without limitation the rights to use, copy, modify, merge, publish, --// distribute, sublicense, and/or sell copies of the Software, and to permit --// persons to whom the Software is furnished to do so, subject to the --// following conditions: --// --// The above copyright notice and this permission notice shall be included --// in all copies or substantial portions of the Software. --// --// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN --// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE --// USE OR OTHER DEALINGS IN THE SOFTWARE. -- --var common = require('../common.js'); --var assert = require('assert'); --var http = require('http'); --var msg = 'Hello'; --var readable_event = false; --var end_event = false; --var server = http.createServer(function(req, res) { -- res.writeHead(200, {'Content-Type': 'text/plain'}); -- res.end(msg); --}).listen(common.PORT, function() { -- http.get({port: common.PORT}, function(res) { -- var data = ''; -- res.on('readable', function() { -- console.log('readable event'); -- readable_event = true; -- data += res.read(); -- }); -- res.on('end', function() { -- console.log('end event'); -- end_event = true; -- assert.strictEqual(msg, data); -- server.close(); -- }); -- }); --}); -- --process.on('exit', function() { -- assert(readable_event); -- assert(end_event); --}); -- -diff --git a/test/simple/test-stream2-large-read-stall.js b/test/simple/test-stream2-large-read-stall.js -index 2fbfbca..667985b 100644 ---- a/test/simple/test-stream2-large-read-stall.js -+++ b/test/simple/test-stream2-large-read-stall.js -@@ -30,7 +30,7 @@ var PUSHSIZE = 20; - var PUSHCOUNT = 1000; - var HWM = 50; - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var r = new Readable({ - highWaterMark: HWM - }); -@@ -39,23 +39,23 @@ var rs = r._readableState; - r._read = push; - - r.on('readable', function() { -- console.error('>> readable'); -+ //console.error('>> readable'); - do { -- console.error(' > read(%d)', READSIZE); -+ //console.error(' > read(%d)', READSIZE); - var ret = r.read(READSIZE); -- console.error(' < %j (%d remain)', ret && ret.length, rs.length); -+ //console.error(' < %j (%d remain)', ret && ret.length, rs.length); - } while (ret && ret.length === READSIZE); - -- console.error('<< after read()', -- ret && ret.length, -- rs.needReadable, -- rs.length); -+ //console.error('<< after read()', -+ // ret && ret.length, -+ // rs.needReadable, -+ // rs.length); - }); - - var endEmitted = false; - r.on('end', function() { - endEmitted = true; -- console.error('end'); -+ //console.error('end'); - }); - - var pushes = 0; -@@ -64,11 +64,11 @@ function push() { - return; - - if (pushes++ === PUSHCOUNT) { -- console.error(' push(EOF)'); -+ //console.error(' push(EOF)'); - return r.push(null); - } - -- console.error(' push #%d', pushes); -+ //console.error(' push #%d', pushes); - if (r.push(new Buffer(PUSHSIZE))) - setTimeout(push); - } -diff --git a/test/simple/test-stream2-objects.js b/test/simple/test-stream2-objects.js -index 3e6931d..ff47d89 100644 ---- a/test/simple/test-stream2-objects.js -+++ b/test/simple/test-stream2-objects.js -@@ -21,8 +21,8 @@ - - - var common = require('../common.js'); --var Readable = require('_stream_readable'); --var Writable = require('_stream_writable'); -+var Readable = require('../../lib/_stream_readable'); -+var Writable = require('../../lib/_stream_writable'); - var assert = require('assert'); - - // tiny node-tap lookalike. -diff --git a/test/simple/test-stream2-pipe-error-handling.js b/test/simple/test-stream2-pipe-error-handling.js -index cf7531c..e3f3e4e 100644 ---- a/test/simple/test-stream2-pipe-error-handling.js -+++ b/test/simple/test-stream2-pipe-error-handling.js -@@ -21,7 +21,7 @@ - - var common = require('../common'); - var assert = require('assert'); --var stream = require('stream'); -+var stream = require('../../'); - - (function testErrorListenerCatches() { - var count = 1000; -diff --git a/test/simple/test-stream2-pipe-error-once-listener.js b/test/simple/test-stream2-pipe-error-once-listener.js -index 5e8e3cb..53b2616 100755 ---- a/test/simple/test-stream2-pipe-error-once-listener.js -+++ b/test/simple/test-stream2-pipe-error-once-listener.js -@@ -24,7 +24,7 @@ var common = require('../common.js'); - var assert = require('assert'); - - var util = require('util'); --var stream = require('stream'); -+var stream = require('../../'); - - - var Read = function() { -diff --git a/test/simple/test-stream2-push.js b/test/simple/test-stream2-push.js -index b63edc3..eb2b0e9 100644 ---- a/test/simple/test-stream2-push.js -+++ b/test/simple/test-stream2-push.js -@@ -20,7 +20,7 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common.js'); --var stream = require('stream'); -+var stream = require('../../'); - var Readable = stream.Readable; - var Writable = stream.Writable; - var assert = require('assert'); -diff --git a/test/simple/test-stream2-read-sync-stack.js b/test/simple/test-stream2-read-sync-stack.js -index e8a7305..9740a47 100644 ---- a/test/simple/test-stream2-read-sync-stack.js -+++ b/test/simple/test-stream2-read-sync-stack.js -@@ -21,7 +21,7 @@ - - var common = require('../common'); - var assert = require('assert'); --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - var r = new Readable(); - var N = 256 * 1024; - -diff --git a/test/simple/test-stream2-readable-empty-buffer-no-eof.js b/test/simple/test-stream2-readable-empty-buffer-no-eof.js -index cd30178..4b1659d 100644 ---- a/test/simple/test-stream2-readable-empty-buffer-no-eof.js -+++ b/test/simple/test-stream2-readable-empty-buffer-no-eof.js -@@ -22,10 +22,9 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('stream').Readable; -+var Readable = require('../../').Readable; - - test1(); --test2(); - - function test1() { - var r = new Readable(); -@@ -88,31 +87,3 @@ function test1() { - console.log('ok'); - }); - } -- --function test2() { -- var r = new Readable({ encoding: 'base64' }); -- var reads = 5; -- r._read = function(n) { -- if (!reads--) -- return r.push(null); // EOF -- else -- return r.push(new Buffer('x')); -- }; -- -- var results = []; -- function flow() { -- var chunk; -- while (null !== (chunk = r.read())) -- results.push(chunk + ''); -- } -- r.on('readable', flow); -- r.on('end', function() { -- results.push('EOF'); -- }); -- flow(); -- -- process.on('exit', function() { -- assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]); -- console.log('ok'); -- }); --} -diff --git a/test/simple/test-stream2-readable-from-list.js b/test/simple/test-stream2-readable-from-list.js -index 7c96ffe..04a96f5 100644 ---- a/test/simple/test-stream2-readable-from-list.js -+++ b/test/simple/test-stream2-readable-from-list.js -@@ -21,7 +21,7 @@ - - var assert = require('assert'); - var common = require('../common.js'); --var fromList = require('_stream_readable')._fromList; -+var fromList = require('../../lib/_stream_readable')._fromList; - - // tiny node-tap lookalike. - var tests = []; -diff --git a/test/simple/test-stream2-readable-legacy-drain.js b/test/simple/test-stream2-readable-legacy-drain.js -index 675da8e..51fd3d5 100644 ---- a/test/simple/test-stream2-readable-legacy-drain.js -+++ b/test/simple/test-stream2-readable-legacy-drain.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var Stream = require('stream'); -+var Stream = require('../../'); - var Readable = Stream.Readable; - - var r = new Readable(); -diff --git a/test/simple/test-stream2-readable-non-empty-end.js b/test/simple/test-stream2-readable-non-empty-end.js -index 7314ae7..c971898 100644 ---- a/test/simple/test-stream2-readable-non-empty-end.js -+++ b/test/simple/test-stream2-readable-non-empty-end.js -@@ -21,7 +21,7 @@ - - var assert = require('assert'); - var common = require('../common.js'); --var Readable = require('_stream_readable'); -+var Readable = require('../../lib/_stream_readable'); - - var len = 0; - var chunks = new Array(10); -diff --git a/test/simple/test-stream2-readable-wrap-empty.js b/test/simple/test-stream2-readable-wrap-empty.js -index 2e5cf25..fd8a3dc 100644 ---- a/test/simple/test-stream2-readable-wrap-empty.js -+++ b/test/simple/test-stream2-readable-wrap-empty.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('_stream_readable'); -+var Readable = require('../../lib/_stream_readable'); - var EE = require('events').EventEmitter; - - var oldStream = new EE(); -diff --git a/test/simple/test-stream2-readable-wrap.js b/test/simple/test-stream2-readable-wrap.js -index 90eea01..6b177f7 100644 ---- a/test/simple/test-stream2-readable-wrap.js -+++ b/test/simple/test-stream2-readable-wrap.js -@@ -22,8 +22,8 @@ - var common = require('../common'); - var assert = require('assert'); - --var Readable = require('_stream_readable'); --var Writable = require('_stream_writable'); -+var Readable = require('../../lib/_stream_readable'); -+var Writable = require('../../lib/_stream_writable'); - var EE = require('events').EventEmitter; - - var testRuns = 0, completedRuns = 0; -diff --git a/test/simple/test-stream2-set-encoding.js b/test/simple/test-stream2-set-encoding.js -index 5d2c32a..685531b 100644 ---- a/test/simple/test-stream2-set-encoding.js -+++ b/test/simple/test-stream2-set-encoding.js -@@ -22,7 +22,7 @@ - - var common = require('../common.js'); - var assert = require('assert'); --var R = require('_stream_readable'); -+var R = require('../../lib/_stream_readable'); - var util = require('util'); - - // tiny node-tap lookalike. -diff --git a/test/simple/test-stream2-transform.js b/test/simple/test-stream2-transform.js -index 9c9ddd8..a0cacc6 100644 ---- a/test/simple/test-stream2-transform.js -+++ b/test/simple/test-stream2-transform.js -@@ -21,8 +21,8 @@ - - var assert = require('assert'); - var common = require('../common.js'); --var PassThrough = require('_stream_passthrough'); --var Transform = require('_stream_transform'); -+var PassThrough = require('../../').PassThrough; -+var Transform = require('../../').Transform; - - // tiny node-tap lookalike. - var tests = []; -diff --git a/test/simple/test-stream2-unpipe-drain.js b/test/simple/test-stream2-unpipe-drain.js -index d66dc3c..365b327 100644 ---- a/test/simple/test-stream2-unpipe-drain.js -+++ b/test/simple/test-stream2-unpipe-drain.js -@@ -22,7 +22,7 @@ - - var common = require('../common.js'); - var assert = require('assert'); --var stream = require('stream'); -+var stream = require('../../'); - var crypto = require('crypto'); - - var util = require('util'); -diff --git a/test/simple/test-stream2-unpipe-leak.js b/test/simple/test-stream2-unpipe-leak.js -index 99f8746..17c92ae 100644 ---- a/test/simple/test-stream2-unpipe-leak.js -+++ b/test/simple/test-stream2-unpipe-leak.js -@@ -22,7 +22,7 @@ - - var common = require('../common.js'); - var assert = require('assert'); --var stream = require('stream'); -+var stream = require('../../'); - - var chunk = new Buffer('hallo'); - -diff --git a/test/simple/test-stream2-writable.js b/test/simple/test-stream2-writable.js -index 704100c..209c3a6 100644 ---- a/test/simple/test-stream2-writable.js -+++ b/test/simple/test-stream2-writable.js -@@ -20,8 +20,8 @@ - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - var common = require('../common.js'); --var W = require('_stream_writable'); --var D = require('_stream_duplex'); -+var W = require('../../').Writable; -+var D = require('../../').Duplex; - var assert = require('assert'); - - var util = require('util'); -diff --git a/test/simple/test-stream3-pause-then-read.js b/test/simple/test-stream3-pause-then-read.js -index b91bde3..2f72c15 100644 ---- a/test/simple/test-stream3-pause-then-read.js -+++ b/test/simple/test-stream3-pause-then-read.js -@@ -22,7 +22,7 @@ - var common = require('../common'); - var assert = require('assert'); - --var stream = require('stream'); -+var stream = require('../../'); - var Readable = stream.Readable; - var Writable = stream.Writable; - diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_duplex.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_duplex.js deleted file mode 100644 index a2e0d8e0d..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_duplex.js +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -module.exports = Duplex; -var util = require('util'); -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -Object.keys(Writable.prototype).forEach(function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); - -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(this.end.bind(this)); -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_passthrough.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_passthrough.js deleted file mode 100644 index 330c247d4..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_passthrough.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); -var util = require('util'); -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_readable.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_readable.js deleted file mode 100644 index 2d00efb43..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_readable.js +++ /dev/null @@ -1,924 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Readable; -Readable.ReadableState = ReadableState; - -var EE = require('events').EventEmitter; -if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; -}; - -if (!global.setImmediate) global.setImmediate = function setImmediate(fn) { - return setTimeout(fn, 0); -}; -if (!global.clearImmediate) global.clearImmediate = function clearImmediate(i) { - return clearTimeout(i); -}; - -var Stream = require('stream'); -var util = require('util'); -if (!util.isUndefined) { - var utilIs = require('core-util-is'); - for (var f in utilIs) { - util[f] = utilIs[f]; - } -} -var StringDecoder; -var debug; -if (util.debuglog) - debug = util.debuglog('stream'); -else try { - debug = require('debuglog')('stream'); -} catch (er) { - debug = function() {}; -} - -util.inherits(Readable, Stream); - -function ReadableState(options, stream) { - options = options || {}; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var defaultHwm = options.objectMode ? 16 : 16 * 1024; - this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require('string_decoder').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); -} - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - - if (util.isString(chunk) && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (util.isNullOrUndefined(chunk)) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - - if (!addToFront) - state.reading = false; - - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) - state.buffer.unshift(chunk); - else - state.buffer.push(chunk); - - if (state.needReadable) - emitReadable(stream); - } - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require('string_decoder').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 128MB -var MAX_HWM = 0x800000; -function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; - } - return n; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - if (isNaN(n) || util.isNull(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } - - if (n <= 0) - return 0; - - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); - - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } - - return n; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function(n) { - debug('read', n); - var state = this._readableState; - var nOrig = n; - - if (!util.isNumber(n) || n > 0) - state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) - endReadable(this); - else - emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) - endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } - - if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - } - - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - - var ret; - if (n > 0) - ret = fromList(n, state); - else - ret = null; - - if (util.isNull(ret)) { - state.needReadable = true; - n = 0; - } - - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended && state.length === 0) - endReadable(this); - - if (!util.isNull(ret)) - this.emit('data', ret); - - return ret; -}; - -function chunkInvalid(state, chunk) { - var er = null; - if (!util.isBuffer(chunk) && - !util.isString(chunk) && - !util.isNullOrUndefined(chunk) && - !state.objectMode && - !er) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - - -function onEofChunk(stream, state) { - if (state.decoder && !state.ended && state.decoder.end) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(function() { - maybeReadMore_(stream, state); - }); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); -}; - -Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - debug('onunpipe'); - if (readable === src) { - cleanup(); - } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && - (!dest._writableState || dest._writableState.needDrain)) - ondrain(); - } - - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - if (false === ret) { - debug('false write response, pause', - src._readableState.awaitDrain); - src._readableState.awaitDrain++; - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (Array.isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; - - - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) - state.awaitDrain--; - if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = state.pipes.indexOf(dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - // If listening to data, and it has not explicitly been paused, - // then call resume to start the flow of data on the next tick. - if (ev === 'data' && false !== this._readableState.flowing) { - this.resume(); - } - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - var self = this; - process.nextTick(function() { - debug('readable nexttick read 0'); - self.read(0); - }); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function() { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - if (!state.reading) { - debug('resume read 0'); - this.read(0); - } - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(function() { - resume_(stream, state); - }); - } -} - -function resume_(stream, state) { - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) - stream.read(0); -} - -Readable.prototype.pause = function() { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - if (state.flowing) { - do { - var chunk = stream.read(); - } while (null !== chunk && state.flowing); - } -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function(chunk) { - debug('wrapped data'); - if (state.decoder) - chunk = state.decoder.write(chunk); - if (!chunk || !state.objectMode && !chunk.length) - return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (util.isFunction(stream[i]) && util.isUndefined(this[i])) { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - events.forEach(function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; - - // nothing in the list, definitely empty. - if (list.length === 0) - return null; - - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_transform.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_transform.js deleted file mode 100644 index b0caf57d8..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_transform.js +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); -var util = require('util'); -if (!util.isUndefined) { - var utilIs = require('core-util-is'); - for (var f in utilIs) { - util[f] = utilIs[f]; - } -} -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (!util.isNullOrUndefined(data)) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - this.once('prefinish', function() { - if (util.isFunction(this._flush)) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} - -Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); -}; - -Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function(n) { - var ts = this._transformState; - - if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - - -function done(stream, er) { - if (er) - return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var ts = stream._transformState; - - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); - - if (ts.transforming) - throw new Error('calling transform done when still transforming'); - - return stream.push(null); -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_writable.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_writable.js deleted file mode 100644 index 1dfca70d8..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/lib/_stream_writable.js +++ /dev/null @@ -1,460 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; -Writable.WritableState = WritableState; - -var util = require('util'); -if (!util.isUndefined) { - var utilIs = require('core-util-is'); - for (var f in utilIs) { - util[f] = utilIs[f]; - } -} -var Stream = require('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - options = options || {}; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var defaultHwm = options.objectMode ? 16 : 16 * 1024; - this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.buffer = []; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; -} - -function Writable(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof require('./_stream_duplex'))) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); -}; - - -function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!util.isBuffer(chunk) && - !util.isString(chunk) && - !util.isNullOrUndefined(chunk) && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (util.isFunction(encoding)) { - cb = encoding; - encoding = null; - } - - if (util.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (!util.isFunction(cb)) - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } - - return ret; -}; - -Writable.prototype.cork = function() { - var state = this._writableState; - - state.corked++; -}; - -Writable.prototype.uncork = function() { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && - !state.corked && - !state.finished && - !state.bufferProcessing && - state.buffer.length) - clearBuffer(this, state); - } -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - util.isString(chunk)) { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (util.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - state.needDrain = !ret; - - if (state.writing || state.corked) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, false, len, chunk, encoding, cb); - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) - stream._writev(chunk, state.onwrite); - else - stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - state.pendingcb--; - cb(er); - }); - else { - state.pendingcb--; - cb(er); - } - - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); - - if (!finished && - !state.corked && - !state.bufferProcessing && - state.buffer.length) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - - if (stream._writev && state.buffer.length > 1) { - // Fast case, write everything using _writev() - var cbs = []; - for (var c = 0; c < state.buffer.length; c++) - cbs.push(state.buffer[c].callback); - - // count the one we are adding, as well. - // TODO(isaacs) clean this up - state.pendingcb++; - doWrite(stream, state, true, state.length, state.buffer, '', function(err) { - for (var i = 0; i < cbs.length; i++) { - state.pendingcb--; - cbs[i](err); - } - }); - - // Clear buffer - state.buffer = []; - } else { - // Slow case, write chunks one-by-one - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } - - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; - } - - state.bufferProcessing = false; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); - -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (util.isFunction(chunk)) { - cb = chunk; - chunk = null; - encoding = null; - } else if (util.isFunction(encoding)) { - cb = encoding; - encoding = null; - } - - if (!util.isNullOrUndefined(chunk)) - this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; - - -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} - -function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } -} - -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else - prefinish(stream, state); - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - process.nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/README.md b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/README.md deleted file mode 100644 index 5a76b4149..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/float.patch b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/float.patch deleted file mode 100644 index a06d5c05f..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return reduceToSingleString(output, base, braces); --} -- -- --function formatPrimitive(ctx, value) { -- if (isUndefined(value)) -- return ctx.stylize('undefined', 'undefined'); -- if (isString(value)) { -- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') -- .replace(/'/g, "\\'") -- .replace(/\\"/g, '"') + '\''; -- return ctx.stylize(simple, 'string'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/lib/util.js deleted file mode 100644 index 9074e8ebc..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/lib/util.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return Buffer.isBuffer(arg); -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/package.json b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/package.json deleted file mode 100644 index cb9aa927d..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "core-util-is", - "version": "1.0.1", - "description": "The `util.is*` functions introduced in Node v0.12.", - "main": "lib/util.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/core-util-is" - }, - "keywords": [ - "util", - "isBuffer", - "isArray", - "isNumber", - "isString", - "isRegExp", - "isThis", - "isThat", - "polyfill" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/isaacs/core-util-is/issues" - }, - "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/isaacs/core-util-is", - "_id": "core-util-is@1.0.1", - "_from": "core-util-is@~1.0.0" -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/util.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/util.js deleted file mode 100644 index 007fa1057..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/core-util-is/util.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return arg instanceof Buffer; -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/LICENSE b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/LICENSE deleted file mode 100644 index a3187cc10..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to -deal in the Software without restriction, including without limitation the -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -sell copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/README.md b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/README.md deleted file mode 100644 index dc6fccecc..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# debuglog - backport of util.debuglog() from node v0.11 - -To facilitate using the `util.debuglog()` function that will be available when -node v0.12 is released now, this is a copy extracted from the source. - -## require('debuglog') - -Return `util.debuglog`, if it exists, otherwise it will return an internal copy -of the implementation from node v0.11. - -## debuglog(section) - -* `section` {String} The section of the program to be debugged -* Returns: {Function} The logging function - -This is used to create a function which conditionally writes to stderr -based on the existence of a `NODE_DEBUG` environment variable. If the -`section` name appears in that environment variable, then the returned -function will be similar to `console.error()`. If not, then the -returned function is a no-op. - -For example: - -```javascript -var debuglog = util.debuglog('foo'); - -var bar = 123; -debuglog('hello from foo [%d]', bar); -``` - -If this program is run with `NODE_DEBUG=foo` in the environment, then -it will output something like: - - FOO 3245: hello from foo [123] - -where `3245` is the process id. If it is not run with that -environment variable set, then it will not print anything. - -You may separate multiple `NODE_DEBUG` environment variables with a -comma. For example, `NODE_DEBUG=fs,net,tls`. diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/debuglog.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/debuglog.js deleted file mode 100644 index da465c294..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/debuglog.js +++ /dev/null @@ -1,22 +0,0 @@ -var util = require('util'); - -module.exports = util.debuglog || debuglog; - -var debugs = {}; -var debugEnviron = process.env.NODE_DEBUG || ''; - -function debuglog(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = util.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/package.json b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/package.json deleted file mode 100644 index b54332bec..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/node_modules/debuglog/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "debuglog", - "version": "0.0.2", - "description": "backport of util.debuglog from node v0.11", - "license": "MIT", - "main": "debuglog.js", - "repository": { - "type": "git", - "url": "https://github.com/sam-github/node-debuglog.git" - }, - "author": { - "name": "Sam Roberts", - "email": "sam@strongloop.com" - }, - "engines": { - "node": "*" - }, - "readme": "# debuglog - backport of util.debuglog() from node v0.11\n\nTo facilitate using the `util.debuglog()` function that will be available when\nnode v0.12 is released now, this is a copy extracted from the source.\n\n## require('debuglog')\n\nReturn `util.debuglog`, if it exists, otherwise it will return an internal copy\nof the implementation from node v0.11.\n\n## debuglog(section)\n\n* `section` {String} The section of the program to be debugged\n* Returns: {Function} The logging function\n\nThis is used to create a function which conditionally writes to stderr\nbased on the existence of a `NODE_DEBUG` environment variable. If the\n`section` name appears in that environment variable, then the returned\nfunction will be similar to `console.error()`. If not, then the\nreturned function is a no-op.\n\nFor example:\n\n```javascript\nvar debuglog = util.debuglog('foo');\n\nvar bar = 123;\ndebuglog('hello from foo [%d]', bar);\n```\n\nIf this program is run with `NODE_DEBUG=foo` in the environment, then\nit will output something like:\n\n FOO 3245: hello from foo [123]\n\nwhere `3245` is the process id. If it is not run with that\nenvironment variable set, then it will not print anything.\n\nYou may separate multiple `NODE_DEBUG` environment variables with a\ncomma. For example, `NODE_DEBUG=fs,net,tls`.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/sam-github/node-debuglog/issues" - }, - "homepage": "https://github.com/sam-github/node-debuglog", - "_id": "debuglog@0.0.2", - "dist": { - "shasum": "6b3ca12c2f07006f68eb7450aa109ff798434777" - }, - "_from": "debuglog@0.0.2", - "_resolved": "https://registry.npmjs.org/debuglog/-/debuglog-0.0.2.tgz" -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/package.json b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/package.json deleted file mode 100644 index 49566cdbd..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "readable-stream", - "version": "1.1.10", - "description": "An exploration of a new kind of readable streams for Node.js", - "main": "readable.js", - "dependencies": { - "core-util-is": "~1.0.0", - "debuglog": "0.0.2" - }, - "devDependencies": { - "tap": "~0.2.6" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/readable-stream" - }, - "keywords": [ - "readable", - "stream", - "pipe" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "optionalDependencies": { - "debuglog": "0.0.2" - }, - "readme": "# readable-stream\n\nA new class of streams for Node.js\n\nThis module provides the new Stream base classes introduced in Node\nv0.10, for use in Node v0.8. You can use it to have programs that\nhave to work with node v0.8, while being forward-compatible for v0.10\nand beyond. When you drop support for v0.8, you can remove this\nmodule, and only use the native streams.\n\nThis is almost exactly the same codebase as appears in Node v0.10.\nHowever:\n\n1. The exported object is actually the Readable class. Decorating the\n native `stream` module would be global pollution.\n2. In v0.10, you can safely use `base64` as an argument to\n `setEncoding` in Readable streams. However, in v0.8, the\n StringDecoder class has no `end()` method, which is problematic for\n Base64. So, don't use that, because it'll break and be weird.\n\nOther than that, the API is the same as `require('stream')` in v0.10,\nso the API docs are reproduced below.\n\n----------\n\n Stability: 2 - Unstable\n\nA stream is an abstract interface implemented by various objects in\nNode. For example a request to an HTTP server is a stream, as is\nstdout. Streams are readable, writable, or both. All streams are\ninstances of [EventEmitter][]\n\nYou can load the Stream base classes by doing `require('stream')`.\nThere are base classes provided for Readable streams, Writable\nstreams, Duplex streams, and Transform streams.\n\n## Compatibility\n\nIn earlier versions of Node, the Readable stream interface was\nsimpler, but also less powerful and less useful.\n\n* Rather than waiting for you to call the `read()` method, `'data'`\n events would start emitting immediately. If you needed to do some\n I/O to decide how to handle data, then you had to store the chunks\n in some kind of buffer so that they would not be lost.\n* The `pause()` method was advisory, rather than guaranteed. This\n meant that you still had to be prepared to receive `'data'` events\n even when the stream was in a paused state.\n\nIn Node v0.10, the Readable class described below was added. For\nbackwards compatibility with older Node programs, Readable streams\nswitch into \"old mode\" when a `'data'` event handler is added, or when\nthe `pause()` or `resume()` methods are called. The effect is that,\neven if you are not using the new `read()` method and `'readable'`\nevent, you no longer have to worry about losing `'data'` chunks.\n\nMost programs will continue to function normally. However, this\nintroduces an edge case in the following conditions:\n\n* No `'data'` event handler is added.\n* The `pause()` and `resume()` methods are never called.\n\nFor example, consider the following code:\n\n```javascript\n// WARNING! BROKEN!\nnet.createServer(function(socket) {\n\n // we add an 'end' method, but never consume the data\n socket.on('end', function() {\n // It will never get here.\n socket.end('I got your message (but didnt read it)\\n');\n });\n\n}).listen(1337);\n```\n\nIn versions of node prior to v0.10, the incoming message data would be\nsimply discarded. However, in Node v0.10 and beyond, the socket will\nremain paused forever.\n\nThe workaround in this situation is to call the `resume()` method to\ntrigger \"old mode\" behavior:\n\n```javascript\n// Workaround\nnet.createServer(function(socket) {\n\n socket.on('end', function() {\n socket.end('I got your message (but didnt read it)\\n');\n });\n\n // start the flow of data, discarding it.\n socket.resume();\n\n}).listen(1337);\n```\n\nIn addition to new Readable streams switching into old-mode, pre-v0.10\nstyle streams can be wrapped in a Readable class using the `wrap()`\nmethod.\n\n## Class: stream.Readable\n\n\n\nA `Readable Stream` has the following methods, members, and events.\n\nNote that `stream.Readable` is an abstract class designed to be\nextended with an underlying implementation of the `_read(size)`\nmethod. (See below.)\n\n### new stream.Readable([options])\n\n* `options` {Object}\n * `highWaterMark` {Number} The maximum number of bytes to store in\n the internal buffer before ceasing to read from the underlying\n resource. Default=16kb\n * `encoding` {String} If specified, then buffers will be decoded to\n strings using the specified encoding. Default=null\n * `objectMode` {Boolean} Whether this stream should behave\n as a stream of objects. Meaning that stream.read(n) returns\n a single value instead of a Buffer of size n\n\nIn classes that extend the Readable class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n### readable.\\_read(size)\n\n* `size` {Number} Number of bytes to read asynchronously\n\nNote: **This function should NOT be called directly.** It should be\nimplemented by child classes, and called by the internal Readable\nclass methods only.\n\nAll Readable stream implementations must provide a `_read` method\nto fetch data from the underlying resource.\n\nThis method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you **are** expected to override this method in\nyour own extension classes.\n\nWhen data is available, put it into the read queue by calling\n`readable.push(chunk)`. If `push` returns false, then you should stop\nreading. When `_read` is called again, you should start pushing more\ndata.\n\nThe `size` argument is advisory. Implementations where a \"read\" is a\nsingle call that returns data can use this to know how much data to\nfetch. Implementations where that is not relevant, such as TCP or\nTLS, may ignore this argument, and simply provide data whenever it\nbecomes available. There is no need, for example to \"wait\" until\n`size` bytes are available before calling `stream.push(chunk)`.\n\n### readable.push(chunk)\n\n* `chunk` {Buffer | null | String} Chunk of data to push into the read queue\n* return {Boolean} Whether or not more pushes should be performed\n\nNote: **This function should be called by Readable implementors, NOT\nby consumers of Readable subclasses.** The `_read()` function will not\nbe called again until at least one `push(chunk)` call is made. If no\ndata is available, then you MAY call `push('')` (an empty string) to\nallow a future `_read` call, without adding any data to the queue.\n\nThe `Readable` class works by putting data into a read queue to be\npulled out later by calling the `read()` method when the `'readable'`\nevent fires.\n\nThe `push()` method will explicitly insert some data into the read\nqueue. If it is called with `null` then it will signal the end of the\ndata.\n\nIn some cases, you may be wrapping a lower-level source which has some\nsort of pause/resume mechanism, and a data callback. In those cases,\nyou could wrap the low-level source object by doing something like\nthis:\n\n```javascript\n// source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nvar stream = new Readable();\n\nsource.ondata = function(chunk) {\n // if push() returns false, then we need to stop reading from source\n if (!stream.push(chunk))\n source.readStop();\n};\n\nsource.onend = function() {\n stream.push(null);\n};\n\n// _read will be called when the stream wants to pull more data in\n// the advisory size argument is ignored in this case.\nstream._read = function(n) {\n source.readStart();\n};\n```\n\n### readable.unshift(chunk)\n\n* `chunk` {Buffer | null | String} Chunk of data to unshift onto the read queue\n* return {Boolean} Whether or not more pushes should be performed\n\nThis is the corollary of `readable.push(chunk)`. Rather than putting\nthe data at the *end* of the read queue, it puts it at the *front* of\nthe read queue.\n\nThis is useful in certain use-cases where a stream is being consumed\nby a parser, which needs to \"un-consume\" some data that it has\noptimistically pulled out of the source.\n\n```javascript\n// A parser for a simple data protocol.\n// The \"header\" is a JSON object, followed by 2 \\n characters, and\n// then a message body.\n//\n// Note: This can be done more simply as a Transform stream. See below.\n\nfunction SimpleProtocol(source, options) {\n if (!(this instanceof SimpleProtocol))\n return new SimpleProtocol(options);\n\n Readable.call(this, options);\n this._inBody = false;\n this._sawFirstCr = false;\n\n // source is a readable stream, such as a socket or file\n this._source = source;\n\n var self = this;\n source.on('end', function() {\n self.push(null);\n });\n\n // give it a kick whenever the source is readable\n // read(0) will not consume any bytes\n source.on('readable', function() {\n self.read(0);\n });\n\n this._rawHeader = [];\n this.header = null;\n}\n\nSimpleProtocol.prototype = Object.create(\n Readable.prototype, { constructor: { value: SimpleProtocol }});\n\nSimpleProtocol.prototype._read = function(n) {\n if (!this._inBody) {\n var chunk = this._source.read();\n\n // if the source doesn't have data, we don't have data yet.\n if (chunk === null)\n return this.push('');\n\n // check if the chunk has a \\n\\n\n var split = -1;\n for (var i = 0; i < chunk.length; i++) {\n if (chunk[i] === 10) { // '\\n'\n if (this._sawFirstCr) {\n split = i;\n break;\n } else {\n this._sawFirstCr = true;\n }\n } else {\n this._sawFirstCr = false;\n }\n }\n\n if (split === -1) {\n // still waiting for the \\n\\n\n // stash the chunk, and try again.\n this._rawHeader.push(chunk);\n this.push('');\n } else {\n this._inBody = true;\n var h = chunk.slice(0, split);\n this._rawHeader.push(h);\n var header = Buffer.concat(this._rawHeader).toString();\n try {\n this.header = JSON.parse(header);\n } catch (er) {\n this.emit('error', new Error('invalid simple protocol data'));\n return;\n }\n // now, because we got some extra data, unshift the rest\n // back into the read queue so that our consumer will see it.\n var b = chunk.slice(split);\n this.unshift(b);\n\n // and let them know that we are done parsing the header.\n this.emit('header', this.header);\n }\n } else {\n // from there on, just provide the data to our consumer.\n // careful not to push(null), since that would indicate EOF.\n var chunk = this._source.read();\n if (chunk) this.push(chunk);\n }\n};\n\n// Usage:\nvar parser = new SimpleProtocol(source);\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.\n```\n\n### readable.wrap(stream)\n\n* `stream` {Stream} An \"old style\" readable stream\n\nIf you are using an older Node library that emits `'data'` events and\nhas a `pause()` method that is advisory only, then you can use the\n`wrap()` method to create a Readable stream that uses the old stream\nas its data source.\n\nFor example:\n\n```javascript\nvar OldReader = require('./old-api-module.js').OldReader;\nvar oreader = new OldReader;\nvar Readable = require('stream').Readable;\nvar myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', function() {\n myReader.read(); // etc.\n});\n```\n\n### Event: 'readable'\n\nWhen there is data ready to be consumed, this event will fire.\n\nWhen this event emits, call the `read()` method to consume the data.\n\n### Event: 'end'\n\nEmitted when the stream has received an EOF (FIN in TCP terminology).\nIndicates that no more `'data'` events will happen. If the stream is\nalso writable, it may be possible to continue writing.\n\n### Event: 'data'\n\nThe `'data'` event emits either a `Buffer` (by default) or a string if\n`setEncoding()` was used.\n\nNote that adding a `'data'` event listener will switch the Readable\nstream into \"old mode\", where data is emitted as soon as it is\navailable, rather than waiting for you to call `read()` to consume it.\n\n### Event: 'error'\n\nEmitted if there was an error receiving data.\n\n### Event: 'close'\n\nEmitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n### readable.setEncoding(encoding)\n\nMakes the `'data'` event emit a string instead of a `Buffer`. `encoding`\ncan be `'utf8'`, `'utf16le'` (`'ucs2'`), `'ascii'`, or `'hex'`.\n\nThe encoding can also be set by specifying an `encoding` field to the\nconstructor.\n\n### readable.read([size])\n\n* `size` {Number | null} Optional number of bytes to read.\n* Return: {Buffer | String | null}\n\nNote: **This function SHOULD be called by Readable stream users.**\n\nCall this method to consume data once the `'readable'` event is\nemitted.\n\nThe `size` argument will set a minimum number of bytes that you are\ninterested in. If not set, then the entire content of the internal\nbuffer is returned.\n\nIf there is no data to consume, or if there are fewer bytes in the\ninternal buffer than the `size` argument, then `null` is returned, and\na future `'readable'` event will be emitted when more is available.\n\nCalling `stream.read(0)` will always return `null`, and will trigger a\nrefresh of the internal buffer, but otherwise be a no-op.\n\n### readable.pipe(destination, [options])\n\n* `destination` {Writable Stream}\n* `options` {Object} Optional\n * `end` {Boolean} Default=true\n\nConnects this readable stream to `destination` WriteStream. Incoming\ndata on this stream gets written to `destination`. Properly manages\nback-pressure so that a slow destination will not be overwhelmed by a\nfast readable stream.\n\nThis function returns the `destination` stream.\n\nFor example, emulating the Unix `cat` command:\n\n process.stdin.pipe(process.stdout);\n\nBy default `end()` is called on the destination when the source stream\nemits `end`, so that `destination` is no longer writable. Pass `{ end:\nfalse }` as `options` to keep the destination stream open.\n\nThis keeps `writer` open so that \"Goodbye\" can be written at the\nend.\n\n reader.pipe(writer, { end: false });\n reader.on(\"end\", function() {\n writer.end(\"Goodbye\\n\");\n });\n\nNote that `process.stderr` and `process.stdout` are never closed until\nthe process exits, regardless of the specified options.\n\n### readable.unpipe([destination])\n\n* `destination` {Writable Stream} Optional\n\nUndo a previously established `pipe()`. If no destination is\nprovided, then all previously established pipes are removed.\n\n### readable.pause()\n\nSwitches the readable stream into \"old mode\", where data is emitted\nusing a `'data'` event rather than being buffered for consumption via\nthe `read()` method.\n\nCeases the flow of data. No `'data'` events are emitted while the\nstream is in a paused state.\n\n### readable.resume()\n\nSwitches the readable stream into \"old mode\", where data is emitted\nusing a `'data'` event rather than being buffered for consumption via\nthe `read()` method.\n\nResumes the incoming `'data'` events after a `pause()`.\n\n\n## Class: stream.Writable\n\n\n\nA `Writable` Stream has the following methods, members, and events.\n\nNote that `stream.Writable` is an abstract class designed to be\nextended with an underlying implementation of the\n`_write(chunk, encoding, cb)` method. (See below.)\n\n### new stream.Writable([options])\n\n* `options` {Object}\n * `highWaterMark` {Number} Buffer level when `write()` starts\n returning false. Default=16kb\n * `decodeStrings` {Boolean} Whether or not to decode strings into\n Buffers before passing them to `_write()`. Default=true\n\nIn classes that extend the Writable class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n### writable.\\_write(chunk, encoding, callback)\n\n* `chunk` {Buffer | String} The chunk to be written. Will always\n be a buffer unless the `decodeStrings` option was set to `false`.\n* `encoding` {String} If the chunk is a string, then this is the\n encoding type. Ignore chunk is a buffer. Note that chunk will\n **always** be a buffer unless the `decodeStrings` option is\n explicitly set to `false`.\n* `callback` {Function} Call this function (optionally with an error\n argument) when you are done processing the supplied chunk.\n\nAll Writable stream implementations must provide a `_write` method to\nsend data to the underlying resource.\n\nNote: **This function MUST NOT be called directly.** It should be\nimplemented by child classes, and called by the internal Writable\nclass methods only.\n\nCall the callback using the standard `callback(error)` pattern to\nsignal that the write completed successfully or with an error.\n\nIf the `decodeStrings` flag is set in the constructor options, then\n`chunk` may be a string rather than a Buffer, and `encoding` will\nindicate the sort of string that it is. This is to support\nimplementations that have an optimized handling for certain string\ndata encodings. If you do not explicitly set the `decodeStrings`\noption to `false`, then you can safely ignore the `encoding` argument,\nand assume that `chunk` will always be a Buffer.\n\nThis method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you **are** expected to override this method in\nyour own extension classes.\n\n\n### writable.write(chunk, [encoding], [callback])\n\n* `chunk` {Buffer | String} Data to be written\n* `encoding` {String} Optional. If `chunk` is a string, then encoding\n defaults to `'utf8'`\n* `callback` {Function} Optional. Called when this chunk is\n successfully written.\n* Returns {Boolean}\n\nWrites `chunk` to the stream. Returns `true` if the data has been\nflushed to the underlying resource. Returns `false` to indicate that\nthe buffer is full, and the data will be sent out in the future. The\n`'drain'` event will indicate when the buffer is empty again.\n\nThe specifics of when `write()` will return false, is determined by\nthe `highWaterMark` option provided to the constructor.\n\n### writable.end([chunk], [encoding], [callback])\n\n* `chunk` {Buffer | String} Optional final data to be written\n* `encoding` {String} Optional. If `chunk` is a string, then encoding\n defaults to `'utf8'`\n* `callback` {Function} Optional. Called when the final chunk is\n successfully written.\n\nCall this method to signal the end of the data being written to the\nstream.\n\n### Event: 'drain'\n\nEmitted when the stream's write queue empties and it's safe to write\nwithout buffering again. Listen for it when `stream.write()` returns\n`false`.\n\n### Event: 'close'\n\nEmitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n### Event: 'finish'\n\nWhen `end()` is called and there are no more chunks to write, this\nevent is emitted.\n\n### Event: 'pipe'\n\n* `source` {Readable Stream}\n\nEmitted when the stream is passed to a readable stream's pipe method.\n\n### Event 'unpipe'\n\n* `source` {Readable Stream}\n\nEmitted when a previously established `pipe()` is removed using the\nsource Readable stream's `unpipe()` method.\n\n## Class: stream.Duplex\n\n\n\nA \"duplex\" stream is one that is both Readable and Writable, such as a\nTCP socket connection.\n\nNote that `stream.Duplex` is an abstract class designed to be\nextended with an underlying implementation of the `_read(size)`\nand `_write(chunk, encoding, callback)` methods as you would with a Readable or\nWritable stream class.\n\nSince JavaScript doesn't have multiple prototypal inheritance, this\nclass prototypally inherits from Readable, and then parasitically from\nWritable. It is thus up to the user to implement both the lowlevel\n`_read(n)` method as well as the lowlevel `_write(chunk, encoding, cb)` method\non extension duplex classes.\n\n### new stream.Duplex(options)\n\n* `options` {Object} Passed to both Writable and Readable\n constructors. Also has the following fields:\n * `allowHalfOpen` {Boolean} Default=true. If set to `false`, then\n the stream will automatically end the readable side when the\n writable side ends and vice versa.\n\nIn classes that extend the Duplex class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n## Class: stream.Transform\n\nA \"transform\" stream is a duplex stream where the output is causally\nconnected in some way to the input, such as a zlib stream or a crypto\nstream.\n\nThere is no requirement that the output be the same size as the input,\nthe same number of chunks, or arrive at the same time. For example, a\nHash stream will only ever have a single chunk of output which is\nprovided when the input is ended. A zlib stream will either produce\nmuch smaller or much larger than its input.\n\nRather than implement the `_read()` and `_write()` methods, Transform\nclasses must implement the `_transform()` method, and may optionally\nalso implement the `_flush()` method. (See below.)\n\n### new stream.Transform([options])\n\n* `options` {Object} Passed to both Writable and Readable\n constructors.\n\nIn classes that extend the Transform class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n### transform.\\_transform(chunk, encoding, callback)\n\n* `chunk` {Buffer | String} The chunk to be transformed. Will always\n be a buffer unless the `decodeStrings` option was set to `false`.\n* `encoding` {String} If the chunk is a string, then this is the\n encoding type. (Ignore if `decodeStrings` chunk is a buffer.)\n* `callback` {Function} Call this function (optionally with an error\n argument) when you are done processing the supplied chunk.\n\nNote: **This function MUST NOT be called directly.** It should be\nimplemented by child classes, and called by the internal Transform\nclass methods only.\n\nAll Transform stream implementations must provide a `_transform`\nmethod to accept input and produce output.\n\n`_transform` should do whatever has to be done in this specific\nTransform class, to handle the bytes being written, and pass them off\nto the readable portion of the interface. Do asynchronous I/O,\nprocess things, and so on.\n\nCall `transform.push(outputChunk)` 0 or more times to generate output\nfrom this input chunk, depending on how much data you want to output\nas a result of this chunk.\n\nCall the callback function only when the current chunk is completely\nconsumed. Note that there may or may not be output as a result of any\nparticular input chunk.\n\nThis method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you **are** expected to override this method in\nyour own extension classes.\n\n### transform.\\_flush(callback)\n\n* `callback` {Function} Call this function (optionally with an error\n argument) when you are done flushing any remaining data.\n\nNote: **This function MUST NOT be called directly.** It MAY be implemented\nby child classes, and if so, will be called by the internal Transform\nclass methods only.\n\nIn some cases, your transform operation may need to emit a bit more\ndata at the end of the stream. For example, a `Zlib` compression\nstream will store up some internal state so that it can optimally\ncompress the output. At the end, however, it needs to do the best it\ncan with what is left, so that the data will be complete.\n\nIn those cases, you can implement a `_flush` method, which will be\ncalled at the very end, after all the written data is consumed, but\nbefore emitting `end` to signal the end of the readable side. Just\nlike with `_transform`, call `transform.push(chunk)` zero or more\ntimes, as appropriate, and call `callback` when the flush operation is\ncomplete.\n\nThis method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you **are** expected to override this method in\nyour own extension classes.\n\n### Example: `SimpleProtocol` parser\n\nThe example above of a simple protocol parser can be implemented much\nmore simply by using the higher level `Transform` stream class.\n\nIn this example, rather than providing the input as an argument, it\nwould be piped into the parser, which is a more idiomatic Node stream\napproach.\n\n```javascript\nfunction SimpleProtocol(options) {\n if (!(this instanceof SimpleProtocol))\n return new SimpleProtocol(options);\n\n Transform.call(this, options);\n this._inBody = false;\n this._sawFirstCr = false;\n this._rawHeader = [];\n this.header = null;\n}\n\nSimpleProtocol.prototype = Object.create(\n Transform.prototype, { constructor: { value: SimpleProtocol }});\n\nSimpleProtocol.prototype._transform = function(chunk, encoding, done) {\n if (!this._inBody) {\n // check if the chunk has a \\n\\n\n var split = -1;\n for (var i = 0; i < chunk.length; i++) {\n if (chunk[i] === 10) { // '\\n'\n if (this._sawFirstCr) {\n split = i;\n break;\n } else {\n this._sawFirstCr = true;\n }\n } else {\n this._sawFirstCr = false;\n }\n }\n\n if (split === -1) {\n // still waiting for the \\n\\n\n // stash the chunk, and try again.\n this._rawHeader.push(chunk);\n } else {\n this._inBody = true;\n var h = chunk.slice(0, split);\n this._rawHeader.push(h);\n var header = Buffer.concat(this._rawHeader).toString();\n try {\n this.header = JSON.parse(header);\n } catch (er) {\n this.emit('error', new Error('invalid simple protocol data'));\n return;\n }\n // and let them know that we are done parsing the header.\n this.emit('header', this.header);\n\n // now, because we got some extra data, emit this first.\n this.push(b);\n }\n } else {\n // from there on, just provide the data to our consumer as-is.\n this.push(b);\n }\n done();\n};\n\nvar parser = new SimpleProtocol();\nsource.pipe(parser)\n\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.\n```\n\n\n## Class: stream.PassThrough\n\nThis is a trivial implementation of a `Transform` stream that simply\npasses the input bytes across to the output. Its purpose is mainly\nfor examples and testing, but there are occasionally use cases where\nit can come in handy.\n\n\n[EventEmitter]: events.html#events_class_events_eventemitter\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/readable-stream/issues" - }, - "homepage": "https://github.com/isaacs/readable-stream", - "_id": "readable-stream@1.1.10", - "_from": "readable-stream@~1.1.9" -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/passthrough.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/passthrough.js deleted file mode 100644 index 27e8d8a55..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/passthrough.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_passthrough.js") diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/readable.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/readable.js deleted file mode 100644 index 09b8bf509..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/readable.js +++ /dev/null @@ -1,7 +0,0 @@ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = require('stream'); -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/transform.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/transform.js deleted file mode 100644 index 5d482f078..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/transform.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_transform.js") diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/writable.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/writable.js deleted file mode 100644 index e1e9efdf3..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/readable-stream/writable.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_writable.js") diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/.npmignore b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/.npmignore deleted file mode 100644 index 07e6e472c..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/README.md b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/README.md deleted file mode 100644 index 8d6a1928f..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# stream-counter - -Keep track of how many bytes have been written to a stream. - -## Usage - -```js -var StreamCounter = require('stream-counter'); -var counter = new StreamCounter(); -counter.on('progress', function() { - console.log("progress", counter.bytes); -}); -fs.createReadStream('foo.txt').pipe(counter); -``` diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/index.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/index.js deleted file mode 100644 index c490c2dbe..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/index.js +++ /dev/null @@ -1,16 +0,0 @@ -module.exports = ByteCounter; - -var Writable = require('readable-stream').Writable; -var util = require('util'); - -util.inherits(ByteCounter, Writable); -function ByteCounter(options) { - Writable.call(this, options); - this.bytes = 0; -} - -ByteCounter.prototype._write = function(chunk, encoding, cb) { - this.bytes += chunk.length; - this.emit('progress'); - cb(); -}; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/package.json b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/package.json deleted file mode 100644 index 1453933a1..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "stream-counter", - "version": "0.2.0", - "description": "keeps track of how many bytes have been written to a stream", - "main": "index.js", - "scripts": { - "test": "node test/test.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/superjoe30/node-stream-counter.git" - }, - "author": { - "name": "Andrew Kelley", - "email": "superjoe30@gmail.com" - }, - "license": "BSD", - "engines": { - "node": ">=0.8.0" - }, - "dependencies": { - "readable-stream": "~1.1.8" - }, - "readme": "# stream-counter\n\nKeep track of how many bytes have been written to a stream.\n\n## Usage\n\n```js\nvar StreamCounter = require('stream-counter');\nvar counter = new StreamCounter();\ncounter.on('progress', function() {\n console.log(\"progress\", counter.bytes);\n});\nfs.createReadStream('foo.txt').pipe(counter);\n```\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/superjoe30/node-stream-counter/issues" - }, - "homepage": "https://github.com/superjoe30/node-stream-counter", - "_id": "stream-counter@0.2.0", - "_from": "stream-counter@~0.2.0" -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/test/test.js b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/test/test.js deleted file mode 100644 index 0da95660a..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/test/test.js +++ /dev/null @@ -1,20 +0,0 @@ -var ByteCounter = require('../'); -var fs = require('fs'); -var path = require('path'); -var assert = require('assert'); - -var counter = new ByteCounter(); -var remainingTests = 2; -counter.once('progress', function() { - assert.strictEqual(counter.bytes, 5); - remainingTests -= 1; -}); -var is = fs.createReadStream(path.join(__dirname, 'test.txt')); -is.pipe(counter); -is.on('end', function() { - remainingTests -= 1; - assert.strictEqual(counter.bytes, 5); -}); -process.on('exit', function() { - assert.strictEqual(remainingTests, 0); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/test/test.txt b/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/test/test.txt deleted file mode 100644 index 81c545efe..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/node_modules/stream-counter/test/test.txt +++ /dev/null @@ -1 +0,0 @@ -1234 diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/package.json b/node_modules/express/node_modules/connect/node_modules/multiparty/package.json deleted file mode 100644 index 865cb96ff..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "multiparty", - "version": "2.2.0", - "description": "multipart/form-data parser which supports streaming", - "repository": { - "type": "git", - "url": "git@github.com:superjoe30/node-multiparty.git" - }, - "keywords": [ - "file", - "upload", - "formidable", - "stream", - "s3" - ], - "devDependencies": { - "findit": "0.1.1", - "hashish": "0.0.4", - "mocha": "~1.8.2", - "request": "~2.16.6", - "mkdirp": "~0.3.5", - "superagent": "~0.14.1" - }, - "scripts": { - "test": "ulimit -n 500 && mocha --timeout 4000 --reporter spec --recursive test/test.js" - }, - "engines": { - "node": ">=0.8.0" - }, - "license": "MIT", - "dependencies": { - "readable-stream": "~1.1.9", - "stream-counter": "~0.2.0" - }, - "readme": "[![Build Status](https://travis-ci.org/superjoe30/node-multiparty.png?branch=master)](https://travis-ci.org/superjoe30/node-multiparty)\n# multiparty\n\nParse http requests with content-type `multipart/form-data`, also known as file uploads.\n\nSee also [busboy](https://github.com/mscdex/busboy) - a\n[faster](https://github.com/mscdex/dicer/wiki/Benchmarks) alternative\nwhich may be worth looking into.\n\n### Why the fork?\n\n * This module uses the Node.js v0.10 streams properly, *even in Node.js v0.8*\n * It will not create a temp file for you unless you want it to.\n * Counts bytes and does math to help you figure out the `Content-Length` of\n each part.\n * You can easily stream uploads to s3 with\n [knox](https://github.com/LearnBoost/knox), for [example](examples/s3.js).\n * Less bugs. This code is simpler, has all deprecated functionality removed,\n has cleaner tests, and does not try to do anything beyond multipart stream\n parsing.\n\n## Installation\n\n```\nnpm install multiparty\n```\n\n## Usage\n\n * See [examples](examples).\n\nParse an incoming `multipart/form-data` request.\n\n```js\nvar multiparty = require('multiparty')\n , http = require('http')\n , util = require('util')\n\nhttp.createServer(function(req, res) {\n if (req.url === '/upload' && req.method === 'POST') {\n // parse a file upload\n var form = new multiparty.Form();\n\n form.parse(req, function(err, fields, files) {\n res.writeHead(200, {'content-type': 'text/plain'});\n res.write('received upload:\\n\\n');\n res.end(util.inspect({fields: fields, files: files}));\n });\n\n return;\n }\n\n // show a file upload form\n res.writeHead(200, {'content-type': 'text/html'});\n res.end(\n '
    '+\n '
    '+\n '
    '+\n ''+\n '
    '\n );\n}).listen(8080);\n```\n\n## API\n\n### multiparty.Form\n```js\nvar form = new multiparty.Form(options)\n```\nCreates a new form. Options:\n\n * `encoding` - sets encoding for the incoming form fields. Defaults to `utf8`.\n * `maxFieldSize` - Limits the amount of memory a field (not a file) can\n allocate in bytes. If this value is exceeded, an `error` event is emitted.\n The default size is 2MB.\n * `maxFields` - Limits the number of fields that will be parsed before\n emitting an `error` event. A file counts as a field in this case.\n Defaults to 1000.\n * `autoFields` - Enables `field` events. This is automatically set to `true`\n if you add a `field` listener.\n * `autoFiles` - Enables `file` events. This is automatically set to `true`\n if you add a `file` listener.\n * `uploadDir` - Only relevant when `autoFiles` is `true`. The directory for\n placing file uploads in. You can move them later using `fs.rename()`.\n Defaults to `os.tmpDir()`.\n * `hash` - Only relevant when `autoFiles` is `true`. If you want checksums\n calculated for incoming files, set this to either `sha1` or `md5`.\n Defaults to off.\n\n#### form.parse(request, [cb])\n\nParses an incoming node.js `request` containing form data. If `cb` is\nprovided, `autoFields` and `autoFiles` are set to `true` and all fields and\nfiles are collected and passed to the callback:\n\n```js\nform.parse(req, function(err, fieldsObject, filesObject, fieldsList, filesList) {\n // ...\n});\n```\n\nIt is often convenient to access a field or file by name. In this situation,\nuse `fieldsObject` or `filesObject`. However sometimes, as in the case of a\n`` the multipart stream will contain\nmultiple files of the same input name, and you are interested in all of them.\nIn this case, use `filesList`.\n\nAnother example is when you do not care what the field name of a file is; you\nare merely interested in a single upload. In this case, set `maxFields` to 1\n(assuming no other fields expected besides the file) and use `filesList[0]`.\n\n#### form.bytesReceived\n\nThe amount of bytes received for this form so far.\n\n#### form.bytesExpected\n\nThe expected number of bytes in this form.\n\n### Events\n\n#### 'error' (err)\n\nYou definitely want to handle this event. If not your server *will* crash when\nusers submit bogus multipart requests!\n\n#### 'part' (part)\n\nEmitted when a part is encountered in the request. `part` is a\n`ReadableStream`. It also has the following properties:\n\n * `headers` - the headers for this part. For example, you may be interested\n in `content-type`.\n * `name` - the field name for this part\n * `filename` - only if the part is an incoming file\n * `byteOffset` - the byte offset of this part in the request body\n * `byteCount` - assuming that this is the last part in the request,\n this is the size of this part in bytes. You could use this, for\n example, to set the `Content-Length` header if uploading to S3.\n If the part had a `Content-Length` header then that value is used\n here instead.\n\n#### 'aborted'\n\nEmitted when the request is aborted. This event will be followed shortly\nby an `error` event. In practice you do not need to handle this event.\n\n#### 'progress' (bytesReceived, bytesExpected)\n\n#### 'close'\n\nEmitted after all parts have been parsed and emitted. Not emitted if an `error`\nevent is emitted. This is typically when you would send your response.\n\n#### 'file' (name, file)\n\n**By default multiparty will not touch your hard drive.** But if you add this\nlistener, multiparty automatically sets `form.autoFiles` to `true` and will\nstream uploads to disk for you. \n\n * `name` - the field name for this file\n * `file` - an object with these properties:\n - `fieldName` - same as `name` - the field name for this file\n - `originalFilename` - the filename that the user reports for the file\n - `path` - the absolute path of the uploaded file on disk\n - `headers` - the HTTP headers that were sent along with this file\n - `size` - size of the file in bytes\n\nIf you set the `form.hash` option, then `file` will also contain a `hash`\nproperty which is the checksum of the file.\n\n#### 'field' (name, value)\n\n * `name` - field name\n * `value` - string field value\n\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/superjoe30/node-multiparty/issues" - }, - "homepage": "https://github.com/superjoe30/node-multiparty", - "_id": "multiparty@2.2.0", - "dist": { - "shasum": "671d6e5fb688c8168f4a0e501580acca1fc2019c" - }, - "_from": "multiparty@2.2.0", - "_resolved": "https://registry.npmjs.org/multiparty/-/multiparty-2.2.0.tgz" -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/bench-multipart-parser.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/bench-multipart-parser.js deleted file mode 100644 index ee5dbad4d..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/bench-multipart-parser.js +++ /dev/null @@ -1,76 +0,0 @@ -var assert = require('assert') - , Form = require('../').Form - , boundary = '-----------------------------168072824752491622650073' - , mb = 100 - , buffer = createMultipartBuffer(boundary, mb * 1024 * 1024) - -var callbacks = { - partBegin: -1, - partEnd: -1, - headerField: -1, - headerValue: -1, - partData: -1, - end: -1, -}; - -var form = new Form({ boundary: boundary }); - -hijack('onParseHeaderField', function() { - callbacks.headerField++; -}); - -hijack('onParseHeaderValue', function() { - callbacks.headerValue++; -}); - -hijack('onParsePartBegin', function() { - callbacks.partBegin++; -}); - -hijack('onParsePartData', function() { - callbacks.partData++; -}); - -hijack('onParsePartEnd', function() { - callbacks.partEnd++; -}); - -form.on('finish', function() { - callbacks.end++; -}); - -var start = new Date(); -form.write(buffer, function(err) { - var duration = new Date() - start; - assert.ifError(err); - var mbPerSec = (mb / (duration / 1000)).toFixed(2); - console.log(mbPerSec+' mb/sec'); -}); - -process.on('exit', function() { - for (var k in callbacks) { - assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]); - } -}); - -function createMultipartBuffer(boundary, size) { - var head = - '--'+boundary+'\r\n' + - 'content-disposition: form-data; name="field1"\r\n' + - '\r\n' - , tail = '\r\n--'+boundary+'--\r\n' - , buffer = new Buffer(size); - - buffer.write(head, 'ascii', 0); - buffer.write(tail, 'ascii', buffer.length - tail.length); - return buffer; -} - -function hijack(name, fn) { - var oldFn = form[name]; - form[name] = function() { - fn(); - return oldFn.apply(this, arguments); - }; -} - diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/beta-sticker-1.png b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/beta-sticker-1.png deleted file mode 100644 index 20b1a7f17..000000000 Binary files a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/beta-sticker-1.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/blank.gif b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/blank.gif deleted file mode 100644 index 75b945d25..000000000 Binary files a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/blank.gif and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/funkyfilename.txt b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/funkyfilename.txt deleted file mode 100644 index e7a4785e0..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/funkyfilename.txt +++ /dev/null @@ -1 +0,0 @@ -I am a text file with a funky name! diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/menu_separator.png b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/menu_separator.png deleted file mode 100644 index 1c16a71ed..000000000 Binary files a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/menu_separator.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/pf1y5.png b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/pf1y5.png deleted file mode 100644 index 44d601759..000000000 Binary files a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/pf1y5.png and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/plain.txt b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/plain.txt deleted file mode 100644 index 9b6903e26..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/file/plain.txt +++ /dev/null @@ -1 +0,0 @@ -I am a plain text file diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/beta-sticker-1.png.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/beta-sticker-1.png.http deleted file mode 100644 index 833b83ca9..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/beta-sticker-1.png.http +++ /dev/null @@ -1,12 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ -Content-Length: 2483 - ---\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ -Content-Disposition: form-data; name="sticker"; filename="beta-sticker-1.png" -Content-Type: image/png -Content-Transfer-Encoding: base64 - -iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABh5JREFUeNrMmHtIHEcYwGfv5SNwaovxEanEiJKqlYCCTRo1f0SvDeof1legEcE/YttQaNOiaQjYFFtpKaJILZU8SCRUWqlJGpoWepGLTXqUEnzFxCrnK9DEelbvvPOe/WacuY7r7HmGFjrwsbNzt7u//V7zfYvQ/2xI/9K1/NyvMP9PgCTuGmmL6/0ckD9UOGmbIExUsqMkAPHJjv5QwKRtgKioqDlh5+w/7IFeCuLlxCeA2zQ0IcCwh2qoaLH09fUdTElJ2e/1elU+n0/y+9fvPz4+fvfYsWN3YOoBcXPiocLghD4mBYHhQTCErqWlZU9FRcXJqKiowyqVSk/uSEH4o8fjWVlYWDB2d3e3d3R0WGB5jYqLg/NyGgsKxMNgkDB4451NTU3vxcXF1SlBKB0tFsuVxsbGjlu3bj2GJQeIk8K5RVBqBTMxrYRfuHAh9/jx4+ejo6MPS9I6f6hHPOC6rOLi4vyVlZXf7t27Z5c5/iZfkgMxxyUwFy9ezC0tLe3V6XRJ/MOCAYjWwsLCni0oKCh98uSJaWhoyMZFn0/uT2qBqYi/1NbWxjc0NJwPFUYExc/B53R5eXk5ZrN5YH5+3slFn5+D2uBDzG90IJETExOtzGdC9RelNf78wYMH3xQWFn4Ep0sgyyCr1NmJP6kEIa5tbW3dEx8fXxeKRoJpT76OR3p6enllZWUKTCOwNalFAglWDkTCvLq6+uR2YYKZSw4GQVKNfZQCafjkqhKYTBsTE3NY/uYi2Q4MP5KTkw9QGB3VEMv6G/YioqFLly5lazQavfytxobnUW+PWTGisIyNPEL3QYLB4PPIyMi4EydO7JUBbTIZ0RDYOFPkE8t/OdHczCK6Y/qdzP8BfUTW8Tj/uQndvT1F5vOzVvTLz1PwX4cQbt++fekURsNpSNLIw16v1z/HLsRRgecsSnovm8nxs5bvUe+NN1Bz47fkfBaAXj2aA2BWEsM/3hhFX1/5Fe3NTEAfvn8NXTO+tSH68IiNjU2Qw/AmCzg2XCQp+YyhJAu9c+pl9GJ+KmhiEt38bhjpoyJQRtYudA60k3dwD6o4mouKjmSiolcy0ArRqnXz3rT+knwFEShhNKLNlmmFP7Kf8XxuehHpj0QQmLdPGch/ioYyCSAe57pMaHnJgcprctDdwUkRjKi8CUTWhipvbm7uvlJo3zFNoHJDOznPeGEXqn+9EBUf+AQZXvqU+BEG/KCpHz2flYh+ALO9++ZX5L/Mj3gfevjw4ZRoP+PzD/b4HadPn844c+aMkb0F1DqIz9byzBvquXytvr6+7vr16+Ow9CfN2njjdfFAWpo9o2FnNmm12kQMw24gcvSnhbHb7Y+huHsNlhapLNHSxK3idlq287qhhrkKlSByOBzIZrPhGyCn04ncbjfRGAMV5ZlQxvDw8E+yYi1Q3qpleYjUQlNTU5aysrJqgNBhIAwGVSDCkFj48BVFULA1eCl7XV3dx1CKYK3YqKnY7u9Ti2royclJ76FDh1YhxefgsoFpCIOtra0RuGBQwYbRaLzc1dVlpjA2ZiqmKbWsDAmEYU9Pz8Tg4OCNoqKixNTU1BQostDq6iqBcrlcRBiYfEff1KBR+OnpabPBYOikWlnhtOOWm0zUffpnZ2ednZ2dJtCYMTs7+xkA2x0eHk6gsMYwFPYr/EC1Wo2LMEWzWa1WC1QRZ8FUVgpj42ohD3umWqHjRFxf5RkZGVkCNQ9CcTWQn5+flpSUtBOiMKAt7Fek/FSAmpmZMVdVVZ0dGxv7g4PhteMVlbBIofv0sh4Lbmhtb2+/Cbv1eFpaWmJCQsJODMO0hGGgUghAAay9v7//i5KSki9lmmG+4+Jg/MHaIH6f0dCkqaNFFc5VkViam5v319TUNEDdvRubEGsNYHGqsAwMDFxta2u7DdpdpA+3c+LgWiHfVkCiFnpDw0iLqwgqO6BVKoPo00K6WIDsOzE6OrpE395FzeLgxMn5jVe0dYTa26s5jfFg4VR0nAuwNtrFda1rgmToD6VzVWq3eTPyYAxOwwH5gvT2PiWY7X4fUgJTywp1fivyyL6E+Lb6XvQ0X9AkBeeXZED+p/k+9LcAAwAXm3hBLzoZPAAAAABJRU5ErkJggg== ---\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/binaryfile.tar.gz.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/binaryfile.tar.gz.http deleted file mode 100644 index 4f4fadb04..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/binaryfile.tar.gz.http +++ /dev/null @@ -1,12 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ -Content-Length: 676 - ---\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ -Content-Disposition: form-data; name="file"; filename="binaryfile.tar.gz" -Content-Type: application/x-gzip -Content-Transfer-Encoding: base64 - -H4sIAGiNIU8AA+3R0W6CMBQGYK59iobLZantRDG73osUOGqnFNJWM2N897UghG1ZdmWWLf93U/jP4bRAq8q92hJ/dY1J7kQEqyyLq8yXYrp2ltkqkTKXYiEykYc++ZTLVcLEvQ40dXReWcYSV1pdnL/v+6n+R11mjKVG1ZQ+s3TT2FpXqjhQ+hjzE1mnGxNLkgu+7tOKWjIVmVKTC6XL9ZaeXj4VQhwKWzL+cI4zwgQuuhkh3mhTad/Hkssh3im3027X54JnQ360R/M19OT8kC7SEN7Ooi2VvrEfznHQRWzl83gxttZKmzGehzPRW/+W8X+3fvL8sFet9sS6m3EIma02071MU3Uf9KHrmV1/+y8DAAAAAAAAAAAAAAAAAAAAAMB/9A6txIuJACgAAA== ---\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/blank.gif.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/blank.gif.http deleted file mode 100644 index 7426f5b65..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/blank.gif.http +++ /dev/null @@ -1,12 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ -Content-Length: 323 - ---\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ -Content-Disposition: form-data; name="file"; filename="blank.gif" -Content-Type: image/gif -Content-Transfer-Encoding: base64 - -R0lGODlhAQABAJH/AP///wAAAMDAwAAAACH5BAEAAAIALAAAAAABAAEAAAICVAEAOw== ---\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/menu_seperator.png.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/menu_seperator.png.http deleted file mode 100644 index d08fd37e2..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/menu_seperator.png.http +++ /dev/null @@ -1,12 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ -Content-Length: 1509 - ---\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ -Content-Disposition: form-data; name="image"; filename="menu_separator.png" -Content-Type: image/png -Content-Transfer-Encoding: base64 - -iVBORw0KGgoAAAANSUhEUgAAAAIAAAAYCAIAAABfmbuOAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MDcxODNBNzJERDcyMTFFMUFBOEVFNDQzOTA0MDJDMjQiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MDcxODNBNzNERDcyMTFFMUFBOEVFNDQzOTA0MDJDMjQiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDowNzE4M0E3MERENzIxMUUxQUE4RUU0NDM5MDQwMkMyNCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDowNzE4M0E3MURENzIxMUUxQUE4RUU0NDM5MDQwMkMyNCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pmvhbb8AAAAXSURBVHjaYnHk9PON8WJiAIPBSwEEGAAPrgG+VozFWgAAAABJRU5ErkJggg== ---\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/pf1y5.png.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/pf1y5.png.http deleted file mode 100644 index 20c2c2dfc..000000000 Binary files a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/pf1y5.png.http and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/plain.txt.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/plain.txt.http deleted file mode 100644 index 5e85ad6bb..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/encoding/plain.txt.http +++ /dev/null @@ -1,13 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=----TLV0SrKD4z1TRxRhAPUvZ -Content-Length: 221 - -------TLV0SrKD4z1TRxRhAPUvZ -Content-Disposition: form-data; name="file"; filename="plain.txt" -Content-Type: text/plain -Content-Transfer-Encoding: 7bit - -I am a plain text file - -------TLV0SrKD4z1TRxRhAPUvZ-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/no-filename/filename-name.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/no-filename/filename-name.http deleted file mode 100644 index 43672a329..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/no-filename/filename-name.http +++ /dev/null @@ -1,13 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=----WebKitFormBoundarytyE4wkKlZ5CQJVTG -Content-Length: 1000 - -------WebKitFormBoundarytyE4wkKlZ5CQJVTG -Content-Disposition: form-data; filename="plain.txt"; name="upload" -Content-Type: text/plain - -I am a plain text file - -------WebKitFormBoundarytyE4wkKlZ5CQJVTG-- - diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/no-filename/generic.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/no-filename/generic.http deleted file mode 100644 index e0dee27c0..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/no-filename/generic.http +++ /dev/null @@ -1,13 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=----WebKitFormBoundarytyE4wkKlZ5CQJVTG -Content-Length: 1000 - -------WebKitFormBoundarytyE4wkKlZ5CQJVTG -Content-Disposition: form-data; name="upload"; filename="" -Content-Type: text/plain - -I am a plain text file - -------WebKitFormBoundarytyE4wkKlZ5CQJVTG-- - diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/preamble/crlf.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/preamble/crlf.http deleted file mode 100644 index 1d5f7095b..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/preamble/crlf.http +++ /dev/null @@ -1,13 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=----TLV0SrKD4z1TRxRhAPUvZ -Content-Length: 184 - - -------TLV0SrKD4z1TRxRhAPUvZ -Content-Disposition: form-data; name="upload"; filename="plain.txt" -Content-Type: text/plain - -I am a plain text file - -------TLV0SrKD4z1TRxRhAPUvZ-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/preamble/preamble.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/preamble/preamble.http deleted file mode 100644 index d14d4330f..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/preamble/preamble.http +++ /dev/null @@ -1,13 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=----TLV0SrKD4z1TRxRhAPUvZ -Content-Length: 226 - -This is a preamble which should be ignored -------TLV0SrKD4z1TRxRhAPUvZ -Content-Disposition: form-data; name="upload"; filename="plain.txt" -Content-Type: text/plain - -I am a plain text file - -------TLV0SrKD4z1TRxRhAPUvZ-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/info.md b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/info.md deleted file mode 100644 index 3c9dbe3dd..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/info.md +++ /dev/null @@ -1,3 +0,0 @@ -* Opera does not allow submitting this file, it shows a warning to the - user that the file could not be found instead. Tested in 9.8, 11.51 on OSX. - Reported to Opera on 08.09.2011 (tracking email DSK-346009@bugs.opera.com). diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-chrome-13.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-chrome-13.http deleted file mode 100644 index 4ef391729..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-chrome-13.http +++ /dev/null @@ -1,26 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Connection: keep-alive -Referer: http://localhost:8080/ -Content-Length: 383 -Cache-Control: max-age=0 -Origin: http://localhost:8080 -User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.220 Safari/535.1 -Content-Type: multipart/form-data; boundary=----WebKitFormBoundarytyE4wkKlZ5CQJVTG -Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 -Accept-Encoding: gzip,deflate,sdch -Accept-Language: en-US,en;q=0.8 -Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 -Cookie: jqCookieJar_tablesorter=%7B%22showListTable%22%3A%5B%5B5%2C1%5D%2C%5B1%2C0%5D%5D%7D - -------WebKitFormBoundarytyE4wkKlZ5CQJVTG -Content-Disposition: form-data; name="title" - -Weird filename -------WebKitFormBoundarytyE4wkKlZ5CQJVTG -Content-Disposition: form-data; name="upload"; filename=": \ ? % * | %22 < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt" -Content-Type: text/plain - -I am a text file with a funky name! - -------WebKitFormBoundarytyE4wkKlZ5CQJVTG-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-firefox-3.6.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-firefox-3.6.http deleted file mode 100644 index bf49f85f9..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-firefox-3.6.http +++ /dev/null @@ -1,24 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.22) Gecko/20110902 Firefox/3.6.22 -Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 -Accept-Language: en-us,en;q=0.5 -Accept-Encoding: gzip,deflate -Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 -Keep-Alive: 115 -Connection: keep-alive -Referer: http://localhost:8080/ -Content-Type: multipart/form-data; boundary=---------------------------9849436581144108930470211272 -Content-Length: 438 - ------------------------------9849436581144108930470211272 -Content-Disposition: form-data; name="title" - -Weird filename ------------------------------9849436581144108930470211272 -Content-Disposition: form-data; name="upload"; filename=": \ ? % * | " < > . ☃ ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt" -Content-Type: text/plain - -I am a text file with a funky name! - ------------------------------9849436581144108930470211272-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-safari-5.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-safari-5.http deleted file mode 100644 index ff158a43c..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/osx-safari-5.http +++ /dev/null @@ -1,23 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Origin: http://localhost:8080 -Content-Length: 383 -User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1 -Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryQJZ1gvhvdgfisJPJ -Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 -Referer: http://localhost:8080/ -Accept-Language: en-us -Accept-Encoding: gzip, deflate -Connection: keep-alive - -------WebKitFormBoundaryQJZ1gvhvdgfisJPJ -Content-Disposition: form-data; name="title" - -Weird filename -------WebKitFormBoundaryQJZ1gvhvdgfisJPJ -Content-Disposition: form-data; name="upload"; filename=": \ ? % * | %22 < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt" -Content-Type: text/plain - -I am a text file with a funky name! - -------WebKitFormBoundaryQJZ1gvhvdgfisJPJ-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-chrome-12.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-chrome-12.http deleted file mode 100644 index f0fc533a4..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-chrome-12.http +++ /dev/null @@ -1,24 +0,0 @@ -POST /upload HTTP/1.1 -Host: 192.168.56.1:8080 -Connection: keep-alive -Referer: http://192.168.56.1:8080/ -Content-Length: 344 -Cache-Control: max-age=0 -Origin: http://192.168.56.1:8080 -User-Agent: Mozilla/5.0 (Windows NT 5.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30 -Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryEvqBNplR3ByrwQPa -Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 -Accept-Encoding: gzip,deflate,sdch -Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4 -Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 - -------WebKitFormBoundaryEvqBNplR3ByrwQPa -Content-Disposition: form-data; name="title" - -Weird filename -------WebKitFormBoundaryEvqBNplR3ByrwQPa -Content-Disposition: form-data; name="upload"; filename=" ? % * | %22 < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt" -Content-Type: text/plain - - -------WebKitFormBoundaryEvqBNplR3ByrwQPa-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-ie-7.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-ie-7.http deleted file mode 100644 index 2e2c61c7f..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-ie-7.http +++ /dev/null @@ -1,22 +0,0 @@ -POST /upload HTTP/1.1 -Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, */* -Referer: http://192.168.56.1:8080/ -Accept-Language: de -User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1) -Content-Type: multipart/form-data; boundary=---------------------------7db1fe232017c -Accept-Encoding: gzip, deflate -Host: 192.168.56.1:8080 -Content-Length: 368 -Connection: Keep-Alive -Cache-Control: no-cache - ------------------------------7db1fe232017c -Content-Disposition: form-data; name="title" - -Weird filename ------------------------------7db1fe232017c -Content-Disposition: form-data; name="upload"; filename=" ? % * | " < > . ☃ ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt" -Content-Type: application/octet-stream - - ------------------------------7db1fe232017c-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-ie-8.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-ie-8.http deleted file mode 100644 index e2b94fae2..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-ie-8.http +++ /dev/null @@ -1,22 +0,0 @@ -POST /upload HTTP/1.1 -Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, */* -Referer: http://192.168.56.1:8080/ -Accept-Language: de -User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0) -Content-Type: multipart/form-data; boundary=---------------------------7db3a8372017c -Accept-Encoding: gzip, deflate -Host: 192.168.56.1:8080 -Content-Length: 368 -Connection: Keep-Alive -Cache-Control: no-cache - ------------------------------7db3a8372017c -Content-Disposition: form-data; name="title" - -Weird filename ------------------------------7db3a8372017c -Content-Disposition: form-data; name="upload"; filename=" ? % * | " < > . ☃ ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt" -Content-Type: application/octet-stream - - ------------------------------7db3a8372017c-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-safari-5.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-safari-5.http deleted file mode 100644 index 6379ac017..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/special-chars-in-filename/xp-safari-5.http +++ /dev/null @@ -1,22 +0,0 @@ -POST /upload HTTP/1.1 -Host: 192.168.56.1:8080 -Referer: http://192.168.56.1:8080/ -Accept: application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 -Accept-Language: en-US -Origin: http://192.168.56.1:8080 -User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4 -Accept-Encoding: gzip, deflate -Content-Type: multipart/form-data; boundary=----WebKitFormBoundarykmaWSUbu697WN9TM -Content-Length: 344 -Connection: keep-alive - -------WebKitFormBoundarykmaWSUbu697WN9TM -Content-Disposition: form-data; name="title" - -Weird filename -------WebKitFormBoundarykmaWSUbu697WN9TM -Content-Disposition: form-data; name="upload"; filename=" ? % * | %22 < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt" -Content-Type: text/plain - - -------WebKitFormBoundarykmaWSUbu697WN9TM-- diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/workarounds/missing-hyphens1.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/workarounds/missing-hyphens1.http deleted file mode 100644 index 282689032..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/workarounds/missing-hyphens1.http +++ /dev/null @@ -1,12 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=----TLV0SrKD4z1TRxRhAPUvZ -Content-Length: 178 - -------TLV0SrKD4z1TRxRhAPUvZ -Content-Disposition: form-data; name="upload"; filename="plain.txt" -Content-Type: text/plain - -I am a plain text file - -------TLV0SrKD4z1TRxRhAPUvZ diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/workarounds/missing-hyphens2.http b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/workarounds/missing-hyphens2.http deleted file mode 100644 index 8e1819471..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/http/workarounds/missing-hyphens2.http +++ /dev/null @@ -1,12 +0,0 @@ -POST /upload HTTP/1.1 -Host: localhost:8080 -Content-Type: multipart/form-data; boundary=----TLV0SrKD4z1TRxRhAPUvZ -Content-Length: 180 - -------TLV0SrKD4z1TRxRhAPUvZ -Content-Disposition: form-data; name="upload"; filename="plain.txt" -Content-Type: text/plain - -I am a plain text file - -------TLV0SrKD4z1TRxRhAPUvZ diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/encoding.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/encoding.js deleted file mode 100644 index 1ade96568..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/encoding.js +++ /dev/null @@ -1,69 +0,0 @@ -module.exports['menu_seperator.png.http'] = [ - { - type: 'file', - name: 'image', - filename: 'menu_separator.png', - fixture: 'menu_separator.png', - sha1: 'c845ca3ea794be298f2a1b79769b71939eaf4e54', - size: 931, - } -]; - -module.exports['beta-sticker-1.png.http'] = [ - { - type: 'file', - name: 'sticker', - filename: 'beta-sticker-1.png', - fixture: 'beta-sticker-1.png', - sha1: '6abbcffd12b4ada5a6a084fe9e4584f846331bc4', - size: 1660, - } -]; - -module.exports['blank.gif.http'] = [ - { - type: 'file', - name: 'file', - filename: 'blank.gif', - fixture: 'blank.gif', - sha1: 'a1fdee122b95748d81cee426d717c05b5174fe96', - size: 49, - } -]; - -module.exports['binaryfile.tar.gz.http'] = [ - { - type: 'file', - name: 'file', - filename: 'binaryfile.tar.gz', - fixture: 'binaryfile.tar.gz', - sha1: 'cfabe13b348e5e69287d677860880c52a69d2155', - size: 301, - } -]; - -module.exports['plain.txt.http'] = [ - { - type: 'file', - name: 'file', - filename: 'plain.txt', - fixture: 'plain.txt', - sha1: 'b31d07bac24ac32734de88b3687dddb10e976872', - size: 23, - } -]; - -module.exports['pf1y5.png.http'] = [ - { - type: 'field', - name: 'path', - }, - { - type: 'file', - name: 'upload', - filename: 'pf1y5.png', - fixture: 'pf1y5.png', - sha1: '805cc640c5b182e86f2b5c8ebf34ecf063cd34fd', - size: 768323, - } -]; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/no-filename.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/no-filename.js deleted file mode 100644 index f03b4f01d..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/no-filename.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports['generic.http'] = [ - {type: 'file', name: 'upload', filename: '', fixture: 'plain.txt', - sha1: 'b31d07bac24ac32734de88b3687dddb10e976872'}, -]; - -module.exports['filename-name.http'] = [ - {type: 'file', name: 'upload', filename: 'plain.txt', fixture: 'plain.txt', - sha1: 'b31d07bac24ac32734de88b3687dddb10e976872'}, -]; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/preamble.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/preamble.js deleted file mode 100644 index d2e4cfdb2..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/preamble.js +++ /dev/null @@ -1,9 +0,0 @@ -module.exports['crlf.http'] = [ - {type: 'file', name: 'upload', filename: 'plain.txt', fixture: 'plain.txt', - sha1: 'b31d07bac24ac32734de88b3687dddb10e976872'}, -]; - -module.exports['preamble.http'] = [ - {type: 'file', name: 'upload', filename: 'plain.txt', fixture: 'plain.txt', - sha1: 'b31d07bac24ac32734de88b3687dddb10e976872'}, -]; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/special-chars-in-filename.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/special-chars-in-filename.js deleted file mode 100644 index aa0b79f34..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/special-chars-in-filename.js +++ /dev/null @@ -1,30 +0,0 @@ -var properFilename = 'funkyfilename.txt'; - -function expect(filename) { - return [ - { - type: 'field', - name: 'title', - value: 'Weird filename', - }, - { - type: 'file', - name: 'upload', - filename: filename, - fixture: properFilename, - }, - ]; -} - -var webkit = " ? % * | \" < > . ? ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; -var ffOrIe = " ? % * | \" < > . ☃ ; ' @ # $ ^ & ( ) - _ = + { } [ ] ` ~.txt"; - -module.exports = { - 'osx-chrome-13.http' : expect(webkit), - 'osx-firefox-3.6.http' : expect(ffOrIe), - 'osx-safari-5.http' : expect(webkit), - 'xp-chrome-12.http' : expect(webkit), - 'xp-ie-7.http' : expect(ffOrIe), - 'xp-ie-8.http' : expect(ffOrIe), - 'xp-safari-5.http' : expect(webkit), -}; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/workarounds.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/workarounds.js deleted file mode 100644 index e59c5b265..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/js/workarounds.js +++ /dev/null @@ -1,8 +0,0 @@ -module.exports['missing-hyphens1.http'] = [ - {type: 'file', name: 'upload', filename: 'plain.txt', fixture: 'plain.txt', - sha1: 'b31d07bac24ac32734de88b3687dddb10e976872'}, -]; -module.exports['missing-hyphens2.http'] = [ - {type: 'file', name: 'upload', filename: 'plain.txt', fixture: 'plain.txt', - sha1: 'b31d07bac24ac32734de88b3687dddb10e976872'}, -]; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/multi_video.upload b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/multi_video.upload deleted file mode 100644 index 9c82ba366..000000000 Binary files a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/multi_video.upload and /dev/null differ diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/multipart.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/multipart.js deleted file mode 100644 index a4761699e..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/fixture/multipart.js +++ /dev/null @@ -1,72 +0,0 @@ -exports['rfc1867'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; - -exports['noTrailing\r\n'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--', - parts: - [ { headers: { - 'content-disposition': 'form-data; name="field1"', - }, - data: 'Joe Blow\r\nalmost tricked you!', - }, - { headers: { - 'content-disposition': 'form-data; name="pics"; filename="file1.txt"', - 'Content-Type': 'text/plain', - }, - data: '... contents of file1.txt ...\r', - } - ] - }; - -exports['emptyHeader'] = - { boundary: 'AaB03x', - raw: - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="field1"\r\n'+ - ': foo\r\n'+ - '\r\n'+ - 'Joe Blow\r\nalmost tricked you!\r\n'+ - '--AaB03x\r\n'+ - 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n'+ - 'Content-Type: text/plain\r\n'+ - '\r\n'+ - '... contents of file1.txt ...\r\r\n'+ - '--AaB03x--\r\n', - expectError: true, - }; diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/record.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/record.js deleted file mode 100644 index 9f1cef86f..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/record.js +++ /dev/null @@ -1,47 +0,0 @@ -var http = require('http'); -var fs = require('fs'); -var connections = 0; - -var server = http.createServer(function(req, res) { - var socket = req.socket; - console.log('Request: %s %s -> %s', req.method, req.url, socket.filename); - - req.on('end', function() { - if (req.url !== '/') { - res.end(JSON.stringify({ - method: req.method, - url: req.url, - filename: socket.filename, - })); - return; - } - - res.writeHead(200, {'content-type': 'text/html'}); - res.end( - '
    '+ - '
    '+ - '
    '+ - ''+ - '
    ' - ); - }); -}); - -server.on('connection', function(socket) { - connections++; - - socket.id = connections; - socket.filename = 'connection-' + socket.id + '.http'; - socket.file = fs.createWriteStream(socket.filename); - socket.pipe(socket.file); - - console.log('--> %s', socket.filename); - socket.on('close', function() { - console.log('<-- %s', socket.filename); - }); -}); - -var port = process.env.PORT || 8080; -server.listen(port, function() { - console.log('Recording connections on port %s', port); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-connection-aborted.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-connection-aborted.js deleted file mode 100644 index bd83e1d6b..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-connection-aborted.js +++ /dev/null @@ -1,27 +0,0 @@ -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var multiparty = require('../../'); - -var server = http.createServer(function (req, res) { - var form = new multiparty.Form(); - var aborted_received = false; - form.on('aborted', function () { - aborted_received = true; - }); - form.on('error', function () { - assert(aborted_received, 'Error event should follow aborted'); - server.close(); - }); - form.on('end', function () { - throw new Error('Unexpected "end" event'); - }); - form.parse(req); -}).listen(0, 'localhost', function () { - var client = net.connect(server.address().port); - client.write( - "POST / HTTP/1.1\r\n" + - "Content-Length: 70\r\n" + - "Content-Type: multipart/form-data; boundary=foo\r\n\r\n"); - client.end(); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-content-transfer-encoding.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-content-transfer-encoding.js deleted file mode 100644 index 35e5a1f84..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-content-transfer-encoding.js +++ /dev/null @@ -1,52 +0,0 @@ -var assert = require('assert') - , multiparty = require('../../') - , http = require('http') - , path = require('path') - , TMP_PATH = path.join(__dirname, '..', 'tmp') - -var server = http.createServer(function(req, res) { - var form = new multiparty.Form(); - form.uploadDir = TMP_PATH; - form.on('close', function () { - throw new Error('Unexpected "close" event'); - }); - form.on('end', function () { - throw new Error('Unexpected "end" event'); - }); - form.on('error', function (e) { - res.writeHead(500); - res.end(e.message); - }); - form.parse(req); -}); - -server.listen(0, function() { - var body = - '--foo\r\n' + - 'Content-Disposition: form-data; name="file1"; filename="file1"\r\n' + - 'Content-Type: application/octet-stream\r\n' + - '\r\nThis is the first file\r\n' + - '--foo\r\n' + - 'Content-Type: application/octet-stream\r\n' + - 'Content-Disposition: form-data; name="file2"; filename="file2"\r\n' + - 'Content-Transfer-Encoding: unknown\r\n' + - '\r\nThis is the second file\r\n' + - '--foo--\r\n'; - - var req = http.request({ - method: 'POST', - port: server.address().port, - headers: { - 'Content-Length': body.length, - 'Content-Type': 'multipart/form-data; boundary=foo' - } - }); - req.on('response', function (res) { - assert.equal(res.statusCode, 500); - res.on('data', function () {}); - res.on('end', function () { - server.close(); - }); - }); - req.end(body); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-invalid.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-invalid.js deleted file mode 100644 index ede541da5..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-invalid.js +++ /dev/null @@ -1,35 +0,0 @@ -var superagent = require('superagent') - , multiparty = require('../../') - , http = require('http') - -var server = http.createServer(function(req, resp) { - var form = new multiparty.Form(); - - var errCount = 0; - form.on('error', function(err) { - errCount += 1; - resp.end(); - }); - form.on('file', function(name, file) { - }); - form.on('field', function(name, file) { - }); - - form.parse(req); -}); -server.listen(function() { - var url = 'http://localhost:' + server.address().port + '/' - var req = superagent.post(url) - req.set('Content-Type', 'multipart/form-data; boundary=foo') - req.write('--foo\r\n') - req.write('Content-filename="foo.txt"\r\n') - req.write('\r\n') - req.write('some text here') - req.write('Content-Disposition: form-data; name="text"; filename="bar.txt"\r\n') - req.write('\r\n') - req.write('some more text stuff') - req.write('\r\n--foo--') - req.end(function(err, resp) { - server.close(); - }); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-15.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-15.js deleted file mode 100644 index 43982fa7a..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-15.js +++ /dev/null @@ -1,88 +0,0 @@ -var http = require('http') - , multiparty = require('../../') - , assert = require('assert') - , superagent = require('superagent') - , path = require('path') - -var server = http.createServer(function(req, res) { - assert.strictEqual(req.url, '/upload'); - assert.strictEqual(req.method, 'POST'); - - var form = new multiparty.Form({autoFields:true,autoFiles:true}); - - form.on('error', function(err) { - console.log(err); - }); - - form.on('close', function() { - }); - - var fileCount = 0; - form.on('file', function(name, file) { - fileCount += 1; - }); - - form.parse(req, function(err, fields, files) { - var objFileCount = 0; - for (var file in files) { - objFileCount += 1; - } - // multiparty does NOT try to do intelligent things based on - // the part name. - assert.strictEqual(fileCount, 2); - assert.strictEqual(objFileCount, 1); - res.end(); - }); -}); -server.listen(function() { - var url = 'http://localhost:' + server.address().port + '/upload'; - var req = superagent.post(url); - req.attach('files[]', fixture('pf1y5.png'), 'SOG2.JPG'); - req.attach('files[]', fixture('binaryfile.tar.gz'), 'BenF364_LIB353.zip'); - - // Get the existing boundary. - var contentType = req.get('content-type'); - var split = contentType.split(' '); - - // Set the content-type. - req.set('content-type', split.join('')); - - req.end(function(err, resp) { - assert.ifError(err); - resp.on('end', function() { - server.close(); - }); - }); - - // No space. - createRequest(''); - - // Single space. - createRequest(' '); - - // Multiple spaces. - createRequest(' '); -}); - -function createRequest(separator) { - var url = 'http://localhost:' + server.address().port + '/upload'; - var req = superagent.post(url); - req.attach('files[]', fixture('pf1y5.png'), 'SOG2.JPG'); - req.attach('files[]', fixture('binaryfile.tar.gz'), 'BenF364_LIB353.zip'); - - // Get the existing boundary. - var contentType = req.get('content-type'); - var split = contentType.split(' '); - - // Set the content-type. - req.set('content-type', split.join(separator)); - - req.end(function(err, resp) { - assert.ifError(err); - // We don't close the server, to allow other requests to pass. - }); -} - -function fixture(name) { - return path.join(__dirname, '..', 'fixture', 'file', name) -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-19.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-19.js deleted file mode 100644 index d7da0cfb4..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-19.js +++ /dev/null @@ -1,44 +0,0 @@ -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var multiparty = require('../../'); - -var client; -var server = http.createServer(function (req, res) { - var form = new multiparty.Form({maxFields: 1}); - form.on('aborted', function () { - throw new Error("did not expect aborted"); - }); - var first = true; - form.on('error', function (err) { - assert.ok(first); - first = false; - client.end(); - assert.ok(/maxFields/.test(err.message)); - server.close(); - }); - form.on('end', function () { - throw new Error('Unexpected "end" event'); - }); - form.parse(req); -}); -server.listen(function() { - client = net.connect(server.address().port); - - client.write("POST /upload HTTP/1.1\r\n" + - "Content-Length: 728\r\n" + - "Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "Content-Disposition: form-data; name=\"title\"\r\n" + - "\r\n" + - "foofoo" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "Content-Disposition: form-data; name=\"upload\"; filename=\"blah1.txt\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "hi1\r\n" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n"); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-21.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-21.js deleted file mode 100644 index 155fba050..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-21.js +++ /dev/null @@ -1,66 +0,0 @@ -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var multiparty = require('../../'); - -var client; -var server = http.createServer(function(req, res) { - var form = new multiparty.Form(); - - form.parse(req, function(err, fieldsTable, filesTable, fieldsList, filesList) { - if (err) { - console.error(err.stack); - return; - } - assert.strictEqual(fieldsList.length, 1); - assert.strictEqual(fieldsList[0].name, "title"); - assert.strictEqual(fieldsList[0].value, "foofoo"); - assert.strictEqual(filesList.length, 4); - assert.strictEqual(filesList[0].fieldName, "upload"); - assert.strictEqual(filesList[1].fieldName, "upload"); - assert.strictEqual(filesList[2].fieldName, "upload"); - assert.strictEqual(filesList[3].fieldName, "upload"); - res.end(); - client.end(); - server.close(); - }); -}); -server.listen(function() { - client = net.connect(server.address().port); - - client.write("POST /upload HTTP/1.1\r\n" + - "Content-Length: 728\r\n" + - "Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "Content-Disposition: form-data; name=\"title\"\r\n" + - "\r\n" + - "foofoo" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "Content-Disposition: form-data; name=\"upload\"; filename=\"blah1.txt\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "hi1\r\n" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "Content-Disposition: form-data; name=\"upload\"; filename=\"blah2.txt\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "hi2\r\n" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "Content-Disposition: form-data; name=\"upload\"; filename=\"blah3.txt\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "hi3\r\n" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "Content-Disposition: form-data; name=\"upload\"; filename=\"blah4.txt\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "hi4\r\n" + - "\r\n" + - "------WebKitFormBoundaryvfUZhxgsZDO7FXLF--\r\n" - ); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-4.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-4.js deleted file mode 100644 index 66b2a6900..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-4.js +++ /dev/null @@ -1,51 +0,0 @@ -var http = require('http') - , multiparty = require('../../') - , assert = require('assert') - , superagent = require('superagent') - , path = require('path') - -var server = http.createServer(function(req, res) { - assert.strictEqual(req.url, '/upload'); - assert.strictEqual(req.method, 'POST'); - - var form = new multiparty.Form({autoFields:true,autoFiles:true}); - - form.on('error', function(err) { - console.log(err); - }); - - form.on('close', function() { - }); - - var fileCount = 0; - form.on('file', function(name, file) { - fileCount += 1; - }); - - form.parse(req, function(err, fields, files) { - var objFileCount = 0; - for (var file in files) { - objFileCount += 1; - } - // multiparty does NOT try to do intelligent things based on - // the part name. - assert.strictEqual(fileCount, 2); - assert.strictEqual(objFileCount, 1); - res.end(); - }); -}); -server.listen(function() { - var url = 'http://localhost:' + server.address().port + '/upload'; - var req = superagent.post(url); - req.attach('files[]', fixture('pf1y5.png'), 'SOG2.JPG'); - req.attach('files[]', fixture('binaryfile.tar.gz'), 'BenF364_LIB353.zip'); - req.end(function(err, resp) { - assert.ifError(err); - resp.on('end', function() { - server.close(); - }); - }); -}); -function fixture(name) { - return path.join(__dirname, '..', 'fixture', 'file', name) -} diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-46.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-46.js deleted file mode 100644 index 676b87094..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-46.js +++ /dev/null @@ -1,49 +0,0 @@ -var http = require('http'), - multiparty = require('../../'), - request = require('request'), - assert = require('assert'); - -var host = 'localhost'; - -var index = [ - '
    ', - ' ', - ' ', - '
    ' -].join("\n"); - -var server = http.createServer(function(req, res) { - - // Show a form for testing purposes. - if (req.method === 'GET') { - res.writeHead(200, {'content-type': 'text/html'}); - res.end(index); - return; - } - - // Parse form and write results to response. - var form = new multiparty.Form(); - form.parse(req, function(err, fields, files) { - res.writeHead(200, {'content-type': 'text/plain'}); - res.write(JSON.stringify({err: err, fields: fields, files: files})); - res.end(); - }); - -}).listen(0, host, function() { - - //console.log("Server up and running..."); - - var server = this, - url = 'http://' + host + ':' + server.address().port; - - var parts = [ - {'Content-Disposition': 'form-data; name="foo"', 'body': 'bar'} - ] - - var req = request({method: 'POST', url: url, multipart: parts}, function(e, res, body) { - var obj = JSON.parse(body); - assert.equal("bar", obj.fields.foo); - server.close(); - }); - -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-5.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-5.js deleted file mode 100644 index 80eadf20d..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/standalone/test-issue-5.js +++ /dev/null @@ -1,39 +0,0 @@ -var assert = require('assert'); -var http = require('http'); -var net = require('net'); -var multiparty = require('../../'); - -var client; -var attachmentCount = 510; -var server = http.createServer(function(req, res) { - var form = new multiparty.Form({maxFields: 10000}); - - form.parse(req, function(err, fieldsTable, filesTable, fieldsList, filesList) { - assert.strictEqual(err.code, "EMFILE"); - res.end(); - client.end(); - server.close(); - }); -}); -server.listen(function() { - client = net.connect(server.address().port); - - var boundary = "------WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n"; - var oneAttachment = boundary + - "Content-Disposition: form-data; name=\"upload\"; filename=\"blah1.txt\"\r\n" + - "Content-Type: text/plain\r\n" + - "\r\n" + - "hi1\r\n" + - "\r\n"; - var payloadSize = oneAttachment.length * attachmentCount + boundary.length; - - client.write("POST /upload HTTP/1.1\r\n" + - "Content-Length: " + payloadSize + "\r\n" + - "Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryvfUZhxgsZDO7FXLF\r\n" + - "\r\n"); - - for (var i = 0; i < attachmentCount; i += 1) { - client.write(oneAttachment); - } - client.write(boundary); -}); diff --git a/node_modules/express/node_modules/connect/node_modules/multiparty/test/test.js b/node_modules/express/node_modules/connect/node_modules/multiparty/test/test.js deleted file mode 100644 index 199d5cddc..000000000 --- a/node_modules/express/node_modules/connect/node_modules/multiparty/test/test.js +++ /dev/null @@ -1,117 +0,0 @@ -var spawn = require('child_process').spawn - , findit = require('findit') - , path = require('path') - , hashish = require('hashish') - , fs = require('fs') - , http = require('http') - , net = require('net') - , assert = require('assert') - , multiparty = require('../') - , mkdirp = require('mkdirp') - , STANDALONE_PATH = path.join(__dirname, 'standalone') - , server = http.createServer() - , PORT = 13532 - , FIXTURE_PATH = path.join(__dirname, 'fixture') - , TMP_PATH = path.join(__dirname, 'tmp') - -mkdirp.sync(TMP_PATH); - -describe("fixtures", function() { - before(function(done) { - server.listen(PORT, done); - }); - var fixtures = []; - findit - .sync(path.join(FIXTURE_PATH, 'js')) - .forEach(function(jsPath) { - if (!/\.js$/.test(jsPath)) return; - var group = path.basename(jsPath, '.js'); - hashish.forEach(require(jsPath), function(fixture, name) { - it(group + '/' + name, createTest({ - name : group + '/' + name, - fixture : fixture, - })); - }); - }); -}); - -describe("standalone", function() { - findit - .sync(STANDALONE_PATH) - .forEach(function(jsPath) { - if (!/\.js$/.test(jsPath)) return; - it(path.basename(jsPath, '.js'), function(done) { - var child = spawn(process.execPath, [jsPath], { stdio: 'inherit' }); - child.on('error', function(err) { - done(err); - }); - child.on('exit', function(code) { - if (code) return done(new Error("exited with code " + code)); - done(); - }); - }); - }); -}); - -function createTest(fixture) { - var name = fixture.name; - fixture = fixture.fixture; - return function(done) { - uploadFixture(name, function(err, parts) { - if (err) return done(err); - fixture.forEach(function(expectedPart, i) { - var parsedPart = parts[i]; - assert.equal(parsedPart.type, expectedPart.type); - assert.equal(parsedPart.name, expectedPart.name); - - if (parsedPart.type === 'file') { - var file = parsedPart.value; - assert.equal(file.originalFilename, expectedPart.filename); - if(expectedPart.sha1) assert.strictEqual(file.hash, expectedPart.sha1); - if(expectedPart.size) assert.strictEqual(file.size, expectedPart.size); - } - }); - done(); - }); - }; - -} - -function uploadFixture(name, cb) { - server.once('request', function(req, res) { - var parts = []; - var form = new multiparty.Form({ - autoFields: true, - autoFiles: true, - }); - form.uploadDir = TMP_PATH; - form.hash = "sha1"; - - form.on('error', callback); - form.on('file', function(name, value) { - parts.push({type: 'file', name: name, value: value}); - }); - form.on('field', function(name, value) { - parts.push({type: 'field', name: name, value: value}); - }); - form.on('close', function() { - res.end('OK'); - callback(null, parts); - }); - form.parse(req); - - function callback() { - var realCallback = cb; - cb = function() {}; - realCallback.apply(null, arguments); - } - }); - - var socket = net.createConnection(PORT); - var file = fs.createReadStream(FIXTURE_PATH + '/http/' + name); - - file.pipe(socket, {end: false}); - socket.on('data', function () { - socket.end(); - }); -} diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/LICENSE b/node_modules/express/node_modules/connect/node_modules/negotiator/LICENSE deleted file mode 100644 index 42ca2e7d7..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Original "Negotiator" program Copyright Federico Romero -Port to JavaScript Copyright Isaac Z. Schlueter - -All rights reserved. - -MIT License - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/examples/accept.js b/node_modules/express/node_modules/connect/node_modules/negotiator/examples/accept.js deleted file mode 100644 index 2a1803918..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/examples/accept.js +++ /dev/null @@ -1,47 +0,0 @@ -(function() { - var Negotiator, availableMediaTypes, http, key, representations, server, val; - - Negotiator = require('../lib/negotiator').Negotiator; - - http = require('http'); - - representations = { - 'text/html': '

    Hello world!

    ', - 'text/plain': 'Hello World!', - 'application/json': JSON.stringify({ - hello: 'world!' - }) - }; - - availableMediaTypes = (function() { - var _results; - _results = []; - for (key in representations) { - val = representations[key]; - _results.push(key); - } - return _results; - })(); - - server = http.createServer(function(req, res) { - var mediaType, negotiator; - negotiator = new Negotiator(req); - console.log("Accept: " + req.headers['accept']); - console.log("Preferred: " + (negotiator.preferredMediaTypes())); - console.log("Possible: " + (negotiator.preferredMediaTypes(availableMediaTypes))); - mediaType = negotiator.preferredMediaType(availableMediaTypes); - console.log("Selected: " + mediaType); - if (mediaType) { - res.writeHead(200, { - 'Content-Type': mediaType - }); - return res.end(representations[mediaType]); - } else { - res.writeHead(406); - return res.end(); - } - }); - - server.listen(8080); - -}).call(this); diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/examples/charset.js b/node_modules/express/node_modules/connect/node_modules/negotiator/examples/charset.js deleted file mode 100644 index 6455effaf..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/examples/charset.js +++ /dev/null @@ -1,52 +0,0 @@ -(function() { - var Buffer, Iconv, Negotiator, availableCharsets, http, iconv, key, message, messages, server, val; - - Negotiator = require('../lib/negotiator').Negotiator; - - http = require('http'); - - Buffer = require('buffer').Buffer; - - Iconv = require('iconv').Iconv; - - iconv = new Iconv('UTF-8', 'ISO-8859-1'); - - message = "ë"; - - messages = { - 'utf-8': message, - 'iso-8859-1': iconv.convert(new Buffer(message)) - }; - - availableCharsets = (function() { - var _results; - _results = []; - for (key in messages) { - val = messages[key]; - _results.push(key); - } - return _results; - })(); - - server = http.createServer(function(req, res) { - var charset, negotiator; - negotiator = new Negotiator(req); - console.log("Accept-Charset: " + req.headers['accept-charset']); - console.log("Preferred: " + (negotiator.preferredCharsets())); - console.log("Possible: " + (negotiator.preferredCharsets(availableCharsets))); - charset = negotiator.preferredCharset(availableCharsets); - console.log("Selected: " + charset); - if (charset) { - res.writeHead(200, { - 'Content-Type': "text/html; charset=" + charset - }); - return res.end(messages[charset]); - } else { - res.writeHead(406); - return res.end(); - } - }); - - server.listen(8080); - -}).call(this); diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/examples/encoding.js b/node_modules/express/node_modules/connect/node_modules/negotiator/examples/encoding.js deleted file mode 100644 index a02d0f46d..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/examples/encoding.js +++ /dev/null @@ -1,48 +0,0 @@ -(function() { - var Negotiator, gbuf, http, messages; - - Negotiator = require('../lib/negotiator').Negotiator; - - http = require('http'); - - gbuf = require('gzip-buffer'); - - messages = { - identity: 'Hello World' - }; - - gbuf.gzip(messages.identity, function(zipped) { - var availableEncodings, key, server, val; - messages.gzip = zipped; - availableEncodings = (function() { - var _results; - _results = []; - for (key in messages) { - val = messages[key]; - _results.push(key); - } - return _results; - })(); - console.log(availableEncodings); - server = http.createServer(function(req, res) { - var encoding, negotiator; - negotiator = new Negotiator(req); - console.log("Accept-Encoding: " + req.headers['accept-encoding']); - console.log("Preferred: " + (negotiator.preferredEncodings())); - console.log("Possible: " + (negotiator.preferredEncodings(availableEncodings))); - encoding = negotiator.preferredEncoding(availableEncodings); - console.log("Selected: " + encoding); - if (encoding) { - res.writeHead(200, { - 'Content-Encoding': encoding - }); - return res.end(messages[encoding]); - } else { - res.writeHead(406); - return res.end(); - } - }); - return server.listen(8080); - }); - -}).call(this); diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/examples/language.js b/node_modules/express/node_modules/connect/node_modules/negotiator/examples/language.js deleted file mode 100644 index f161743f9..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/examples/language.js +++ /dev/null @@ -1,44 +0,0 @@ -(function() { - var Negotiator, availableLanguages, http, key, messages, server, val; - - Negotiator = require('../lib/negotiator').Negotiator; - - http = require('http'); - - messages = { - es: "¡Hola Mundo!", - en: "Hello World!" - }; - - availableLanguages = (function() { - var _results; - _results = []; - for (key in messages) { - val = messages[key]; - _results.push(key); - } - return _results; - })(); - - server = http.createServer(function(req, res) { - var language, negotiator; - negotiator = new Negotiator(req); - console.log("Accept-Language: " + req.headers['accept-language']); - console.log("Preferred: " + (negotiator.preferredLanguages())); - console.log("Possible: " + (negotiator.preferredLanguages(availableLanguages))); - language = negotiator.preferredLanguage(availableLanguages); - console.log("Selected: " + language); - if (language) { - res.writeHead(200, { - 'Content-Language': language - }); - return res.end(messages[language]); - } else { - res.writeHead(406); - return res.end(); - } - }); - - server.listen(8080); - -}).call(this); diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/charset.js b/node_modules/express/node_modules/connect/node_modules/negotiator/lib/charset.js deleted file mode 100644 index 330045722..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/charset.js +++ /dev/null @@ -1,71 +0,0 @@ -module.exports = preferredCharsets; -preferredCharsets.preferredCharsets = preferredCharsets; - -function parseAcceptCharset(accept) { - return accept.split(',').map(function(e) { - return parseCharset(e.trim()); - }).filter(function(e) { - return e && e.q > 0; - }); -} - -function parseCharset(s) { - var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); - if (!match) return null; - - var charset = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';') - for (var i = 0; i < params.length; i ++) { - var p = params[i].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } - } - } - - return { - charset: charset, - q: q - }; -} - -function getCharsetPriority(charset, accepted) { - return (accepted.filter(function(a) { - return specify(charset, a); - }).sort(function (a, b) { - // revsort - return a.q === b.q ? 0 : a.q > b.q ? -1 : 1; - })[0] || {q:0}).q; -} - -function specify(charset, spec) { - if (spec.charset === '*' || spec.charset === charset) { - return spec; - } -}; - -function preferredCharsets(accept, provided) { - accept = parseAcceptCharset(accept || ''); - if (provided) { - return provided.map(function(type) { - return [type, getCharsetPriority(type, accept)]; - }).filter(function(pair) { - return pair[1] > 0; - }).sort(function(a, b) { - // revsort - return a[1] === b[1] ? 0 : a[1] > b[1] ? -1 : 1; - }).map(function(pair) { - return pair[0]; - }); - } else { - return accept.sort(function (a, b) { - // revsort - return a.q < b.q ? 1 : -1; - }).map(function(type) { - return type.charset; - }); - } -} diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/encoding.js b/node_modules/express/node_modules/connect/node_modules/negotiator/lib/encoding.js deleted file mode 100644 index b4fc889f7..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/encoding.js +++ /dev/null @@ -1,89 +0,0 @@ -module.exports = preferredEncodings; -preferredEncodings.preferredEncodings = preferredEncodings; - -function parseAcceptEncoding(accept) { - var acceptableEncodings; - - if (accept) { - acceptableEncodings = accept.split(',').map(function(e) { - return parseEncoding(e.trim()); - }); - } else { - acceptableEncodings = []; - } - - if (!acceptableEncodings.some(function(e) { - return e && e.encoding === 'identity'; - })) { - acceptableEncodings.push({ - encoding: 'identity', - q: 0.1 - }); - } - - return acceptableEncodings.filter(function(e) { - return e && e.q > 0; - }); -} - -function parseEncoding(s) { - var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/); - - if (!match) return null; - - var encoding = match[1]; - var q = 1; - if (match[2]) { - var params = match[2].split(';'); - for (var i = 0; i < params.length; i ++) { - var p = params[i].trim().split('='); - if (p[0] === 'q') { - q = parseFloat(p[1]); - break; - } - } - } - - return { - encoding: encoding, - q: q - }; -} - -function getEncodingPriority(encoding, accepted) { - return (accepted.filter(function(a) { - return specify(encoding, a); - }).sort(function (a, b) { - // revsort - return a.q === b.q ? 0 : a.q > b.q ? -1 : 1; - })[0] || {q:0}).q; -} - -function specify(encoding, spec) { - if (spec.encoding === '*' || spec.encoding === encoding) { - return spec; - } -} - -function preferredEncodings(accept, provided) { - accept = parseAcceptEncoding(accept || ''); - if (provided) { - return provided.map(function(type) { - return [type, getEncodingPriority(type, accept)]; - }).filter(function(pair) { - return pair[1] > 0; - }).sort(function(a, b) { - // revsort - return a[1] === b[1] ? 0 : a[1] > b[1] ? -1 : 1; - }).map(function(pair) { - return pair[0]; - }); - } else { - return accept.sort(function (a, b) { - // revsort - return a.q < b.q ? 1 : -1; - }).map(function(type) { - return type.encoding; - }); - } -} diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/language.js b/node_modules/express/node_modules/connect/node_modules/negotiator/lib/language.js deleted file mode 100644 index 432b7026f..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/language.js +++ /dev/null @@ -1,92 +0,0 @@ -module.exports = preferredLanguages; -preferredLanguages.preferredLanguages = preferredLanguages; - -function parseAcceptLanguage(accept) { - return accept.split(',').map(function(e) { - return parseLanguage(e.trim()); - }).filter(function(e) { - return e && e.q > 0; - }); -} - -function parseLanguage(s) { - var match = s.match(/^\s*(\S+?)(?:-(\S+?))?\s*(?:;(.*))?$/); - if (!match) return null; - - var prefix = match[1], - suffix = match[2], - full = prefix; - - if (suffix) full += "-" + suffix; - - var q = 1; - if (match[3]) { - var params = match[3].split(';') - for (var i = 0; i < params.length; i ++) { - var p = params[i].split('='); - if (p[0] === 'q') q = parseFloat(p[1]); - } - } - - return { - prefix: prefix, - suffix: suffix, - q: q, - full: full - }; -} - -function getLanguagePriority(language, accepted) { - var match = getClosestMatch(language, accepted); - return match ? match.q : 0; -} - -function getClosestMatch(language, accepted) { - var parsed = parseLanguage(language); - - var matches = accepted.filter(function(a) { - return a.full === parsed.full; - }); - if (matches.length) return matches[0]; - - matches = accepted.filter(function(a) { - return a.prefix === parsed.prefix && !a.suffix; - }); - if (matches.length) return matches[0]; - - matches = accepted.filter(function(a) { - return a.prefix === parsed.prefix; - }); - if (matches.length) return matches[0]; - - matches = accepted.filter(function(a) { - return a.prefix === '*'; - }); - return matches[0]; -} - -function preferredLanguages(accept, provided) { - accept = parseAcceptLanguage(accept || ''); - if (provided) { - - var ret = provided.map(function(type) { - return [type, getLanguagePriority(type, accept)]; - }).filter(function(pair) { - return pair[1] > 0; - }).sort(function(a, b) { - // revsort - return a[1] === b[1] ? 0 : a[1] > b[1] ? -1 : 1; - }).map(function(pair) { - return pair[0]; - }); - return ret; - - } else { - return accept.sort(function (a, b) { - // revsort - return a.q < b.q ? 1 : -1; - }).map(function(type) { - return type.full; - }); - } -} diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/mediaType.js b/node_modules/express/node_modules/connect/node_modules/negotiator/lib/mediaType.js deleted file mode 100644 index 3dc017fd1..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/mediaType.js +++ /dev/null @@ -1,101 +0,0 @@ -module.exports = preferredMediaTypes; -preferredMediaTypes.preferredMediaTypes = preferredMediaTypes; - -function parseAccept(accept) { - return accept.split(',').map(function(e) { - return parseMediaType(e.trim()); - }).filter(function(e) { - return e && e.q > 0; - }); -}; - -function parseMediaType(s) { - var match = s.match(/\s*(\S+)\/([^;\s]+)\s*(?:;(.*))?/); - if (!match) return null; - - var type = match[1], - subtype = match[2], - full = "" + type + "/" + subtype, - params = {}, - q = 1; - - if (match[3]) { - params = match[3].split(';').map(function(s) { - return s.trim().split('='); - }).reduce(function (set, p) { - set[p[0]] = p[1]; - return set - }, params); - - if (params.q != null) { - q = parseFloat(params.q); - delete params.q; - } - } - - return { - type: type, - subtype: subtype, - params: params, - q: q, - full: full - }; -} - -function getMediaTypePriority(type, accepted) { - return (accepted.filter(function(a) { - return specify(type, a); - }).sort(function (a, b) { - // revsort - return a.q > b.q ? -1 : 1; - })[0] || {q:0}).q; -} - -function specifies(spec, type) { - return spec === '*' || spec === type; -} - -function specify(type, spec) { - var p = parseMediaType(type); - - if (spec.params) { - var keys = Object.keys(spec.params); - if (keys.some(function (k) { - return !specifies(spec.params[k], p.params[k]); - })) { - // some didn't specify. - return null; - } - } - - if (specifies(spec.type, p.type) && - specifies(spec.subtype, p.subtype)) { - return spec; - } -} - -function preferredMediaTypes(accept, provided) { - accept = parseAccept(accept || ''); - if (provided) { - return provided.map(function(type) { - return [type, getMediaTypePriority(type, accept)]; - }).filter(function(pair) { - return pair[1] > 0; - }).sort(function(a, b) { - // revsort - return a[1] === b[1] ? 0 : a[1] > b[1] ? -1 : 1; - }).map(function(pair) { - return pair[0]; - }); - - } else { - return accept.sort(function (a, b) { - // revsort - return a.q < b.q ? 1 : -1; - }).map(function(type) { - return type.full; - }); - } -} - - diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/negotiator.js b/node_modules/express/node_modules/connect/node_modules/negotiator/lib/negotiator.js deleted file mode 100644 index fe0e58a57..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/lib/negotiator.js +++ /dev/null @@ -1,29 +0,0 @@ -module.exports = Negotiator; -Negotiator.Negotiator = Negotiator; - -function Negotiator(request) { - if (!(this instanceof Negotiator)) return new Negotiator(request); - this.request = request; -} - -var set = { preferredCharset: [require('./charset.js'), 'accept-charset'], - preferredEncoding: [require('./encoding.js'), 'accept-encoding'], - preferredLanguage: [require('./language.js'), 'accept-language'], - preferredMediaType: [require('./mediaType.js'), 'accept'] }; - -Object.keys(set).forEach(function (k) { - var mh = set[k], - method = mh[0], - header = mh[1], - singular = k, - plural = k + 's'; - - Negotiator.prototype[plural] = function (available) { - return method(this.request.headers[header], available); - }; - - Negotiator.prototype[singular] = function(available) { - var set = this[plural](available); - if (set) return set[0]; - }; -}) diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/package.json b/node_modules/express/node_modules/connect/node_modules/negotiator/package.json deleted file mode 100644 index 18fc25e2b..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "negotiator", - "description": "HTTP content negotiation", - "version": "0.3.0", - "author": { - "name": "Federico Romero", - "email": "federico.romero@outboxlabs.com" - }, - "contributors": [ - { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - } - ], - "repository": { - "type": "git", - "url": "git://github.com/federomero/negotiator.git" - }, - "keywords": [ - "http", - "content negotiation", - "accept", - "accept-language", - "accept-encoding", - "accept-charset" - ], - "engine": "node >= 0.6", - "license": "MIT", - "devDependencies": { - "nodeunit": "0.6.x" - }, - "scripts": { - "test": "nodeunit test" - }, - "optionalDependencies": {}, - "engines": { - "node": "*" - }, - "main": "lib/negotiator.js", - "readme": "# Negotiator\n\nAn HTTP content negotiator for node.js written in javascript.\n\n# Accept Negotiation\n\n Negotiator = require('negotiator')\n\n availableMediaTypes = ['text/html', 'text/plain', 'application/json']\n\n // The negotiator constructor receives a request object\n negotiator = new Negotiator(request)\n\n // Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8'\n\n negotiator.preferredMediaTypes()\n // -> ['text/html', 'image/jpeg', 'application/*']\n\n negotiator.preferredMediaTypes(availableMediaTypes)\n // -> ['text/html', 'application/json']\n\n negotiator.preferredMediaType(availableMediaTypes)\n // -> 'text/html'\n\nYou can check a working example at `examples/accept.js`.\n\n## Methods\n\n`preferredMediaTypes(availableMediaTypes)`:\n\nReturns an array of preferred media types ordered by priority from a list of available media types.\n\n`preferredMediaType(availableMediaType)`:\n\nReturns the top preferred media type from a list of available media types.\n\n# Accept-Language Negotiation\n\n Negotiator = require('negotiator')\n\n negotiator = new Negotiator(request)\n\n availableLanguages = 'en', 'es', 'fr'\n\n // Let's say Accept-Language header is 'en;q=0.8, es, pt'\n\n negotiator.preferredLanguages()\n // -> ['es', 'pt', 'en']\n\n negotiator.preferredLanguages(availableLanguages)\n // -> ['es', 'en']\n\n language = negotiator.preferredLanguage(availableLanguages)\n // -> 'es'\n\nYou can check a working example at `examples/language.js`.\n\n## Methods\n\n`preferredLanguages(availableLanguages)`:\n\nReturns an array of preferred languages ordered by priority from a list of available languages.\n\n`preferredLanguage(availableLanguages)`:\n\nReturns the top preferred language from a list of available languages.\n\n# Accept-Charset Negotiation\n\n Negotiator = require('negotiator')\n\n availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5']\n\n negotiator = new Negotiator(request)\n\n // Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2'\n\n negotiator.preferredCharsets()\n // -> ['utf-8', 'iso-8859-1', 'utf-7']\n\n negotiator.preferredCharsets(availableCharsets)\n // -> ['utf-8', 'iso-8859-1']\n\n negotiator.preferredCharset(availableCharsets)\n // -> 'utf-8'\n\nYou can check a working example at `examples/charset.js`.\n\n## Methods\n\n`preferredCharsets(availableCharsets)`:\n\nReturns an array of preferred charsets ordered by priority from a list of available charsets.\n\n`preferredCharset(availableCharsets)`:\n\nReturns the top preferred charset from a list of available charsets.\n\n# Accept-Encoding Negotiation\n\n Negotiator = require('negotiator').Negotiator\n\n availableEncodings = ['identity', 'gzip']\n\n negotiator = new Negotiator(request)\n\n // Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5'\n\n negotiator.preferredEncodings()\n // -> ['gzip', 'identity', 'compress']\n\n negotiator.preferredEncodings(availableEncodings)\n // -> ['gzip', 'identity']\n\n negotiator.preferredEncoding(availableEncodings)\n // -> 'gzip'\n\nYou can check a working example at `examples/encoding.js`.\n\n## Methods\n\n`preferredEncodings(availableEncodings)`:\n\nReturns an array of preferred encodings ordered by priority from a list of available encodings.\n\n`preferredEncoding(availableEncodings)`:\n\nReturns the top preferred encoding from a list of available encodings.\n\n# License\n\nMIT\n", - "readmeFilename": "readme.md", - "bugs": { - "url": "https://github.com/federomero/negotiator/issues" - }, - "homepage": "https://github.com/federomero/negotiator", - "dependencies": {}, - "_id": "negotiator@0.3.0", - "dist": { - "shasum": "76b4d7f976102e47fe0cc501ddab061f3a122d9f" - }, - "_from": "negotiator@0.3.0", - "_resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.3.0.tgz" -} diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/readme.md b/node_modules/express/node_modules/connect/node_modules/negotiator/readme.md deleted file mode 100644 index 0a077bbeb..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/readme.md +++ /dev/null @@ -1,132 +0,0 @@ -# Negotiator - -An HTTP content negotiator for node.js written in javascript. - -# Accept Negotiation - - Negotiator = require('negotiator') - - availableMediaTypes = ['text/html', 'text/plain', 'application/json'] - - // The negotiator constructor receives a request object - negotiator = new Negotiator(request) - - // Let's say Accept header is 'text/html, application/*;q=0.2, image/jpeg;q=0.8' - - negotiator.preferredMediaTypes() - // -> ['text/html', 'image/jpeg', 'application/*'] - - negotiator.preferredMediaTypes(availableMediaTypes) - // -> ['text/html', 'application/json'] - - negotiator.preferredMediaType(availableMediaTypes) - // -> 'text/html' - -You can check a working example at `examples/accept.js`. - -## Methods - -`preferredMediaTypes(availableMediaTypes)`: - -Returns an array of preferred media types ordered by priority from a list of available media types. - -`preferredMediaType(availableMediaType)`: - -Returns the top preferred media type from a list of available media types. - -# Accept-Language Negotiation - - Negotiator = require('negotiator') - - negotiator = new Negotiator(request) - - availableLanguages = 'en', 'es', 'fr' - - // Let's say Accept-Language header is 'en;q=0.8, es, pt' - - negotiator.preferredLanguages() - // -> ['es', 'pt', 'en'] - - negotiator.preferredLanguages(availableLanguages) - // -> ['es', 'en'] - - language = negotiator.preferredLanguage(availableLanguages) - // -> 'es' - -You can check a working example at `examples/language.js`. - -## Methods - -`preferredLanguages(availableLanguages)`: - -Returns an array of preferred languages ordered by priority from a list of available languages. - -`preferredLanguage(availableLanguages)`: - -Returns the top preferred language from a list of available languages. - -# Accept-Charset Negotiation - - Negotiator = require('negotiator') - - availableCharsets = ['utf-8', 'iso-8859-1', 'iso-8859-5'] - - negotiator = new Negotiator(request) - - // Let's say Accept-Charset header is 'utf-8, iso-8859-1;q=0.8, utf-7;q=0.2' - - negotiator.preferredCharsets() - // -> ['utf-8', 'iso-8859-1', 'utf-7'] - - negotiator.preferredCharsets(availableCharsets) - // -> ['utf-8', 'iso-8859-1'] - - negotiator.preferredCharset(availableCharsets) - // -> 'utf-8' - -You can check a working example at `examples/charset.js`. - -## Methods - -`preferredCharsets(availableCharsets)`: - -Returns an array of preferred charsets ordered by priority from a list of available charsets. - -`preferredCharset(availableCharsets)`: - -Returns the top preferred charset from a list of available charsets. - -# Accept-Encoding Negotiation - - Negotiator = require('negotiator').Negotiator - - availableEncodings = ['identity', 'gzip'] - - negotiator = new Negotiator(request) - - // Let's say Accept-Encoding header is 'gzip, compress;q=0.2, identity;q=0.5' - - negotiator.preferredEncodings() - // -> ['gzip', 'identity', 'compress'] - - negotiator.preferredEncodings(availableEncodings) - // -> ['gzip', 'identity'] - - negotiator.preferredEncoding(availableEncodings) - // -> 'gzip' - -You can check a working example at `examples/encoding.js`. - -## Methods - -`preferredEncodings(availableEncodings)`: - -Returns an array of preferred encodings ordered by priority from a list of available encodings. - -`preferredEncoding(availableEncodings)`: - -Returns the top preferred encoding from a list of available encodings. - -# License - -MIT diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/test/charset.js b/node_modules/express/node_modules/connect/node_modules/negotiator/test/charset.js deleted file mode 100644 index 79224a754..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/test/charset.js +++ /dev/null @@ -1,62 +0,0 @@ -(function() { - var configuration, preferredCharsets, testConfigurations, testCorrectCharset, _i, _len, - _this = this; - - preferredCharsets = require('../lib/charset').preferredCharsets; - - this["Should not return a charset when no charset is provided"] = function(test) { - test.deepEqual(preferredCharsets('*', []), []); - return test.done(); - }; - - this["Should not return a charset when no charset is acceptable"] = function(test) { - test.deepEqual(preferredCharsets('ISO-8859-1', ['utf-8']), []); - return test.done(); - }; - - this["Should not return a charset with q = 0"] = function(test) { - test.deepEqual(preferredCharsets('utf-8;q=0', ['utf-8']), []); - return test.done(); - }; - - testCorrectCharset = function(c) { - return _this["Should return " + c.selected + " for accept-charset header " + c.accept + " with provided charset " + c.provided] = function(test) { - test.deepEqual(preferredCharsets(c.accept, c.provided), c.selected); - return test.done(); - }; - }; - - testConfigurations = [ - { - accept: 'utf-8', - provided: ['utf-8'], - selected: ['utf-8'] - }, { - accept: '*', - provided: ['utf-8'], - selected: ['utf-8'] - }, { - accept: 'utf-8', - provided: ['utf-8', 'ISO-8859-1'], - selected: ['utf-8'] - }, { - accept: 'utf-8, ISO-8859-1', - provided: ['utf-8'], - selected: ['utf-8'] - }, { - accept: 'utf-8;q=0.8, ISO-8859-1', - provided: ['utf-8', 'ISO-8859-1'], - selected: ['ISO-8859-1', 'utf-8'] - }, { - accept: 'utf-8;q=0.8, ISO-8859-1', - provided: null, - selected: ['ISO-8859-1', 'utf-8'] - } - ]; - - for (_i = 0, _len = testConfigurations.length; _i < _len; _i++) { - configuration = testConfigurations[_i]; - testCorrectCharset(configuration); - } - -}).call(this); diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/test/encoding.js b/node_modules/express/node_modules/connect/node_modules/negotiator/test/encoding.js deleted file mode 100644 index 7859d5e45..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/test/encoding.js +++ /dev/null @@ -1,70 +0,0 @@ -(function() { - var configuration, preferredEncodings, testConfigurations, testCorrectEncoding, _i, _len, - _this = this; - - preferredEncodings = require('../lib/encoding').preferredEncodings; - - this["Should return identity encoding when no encoding is provided"] = function(test) { - test.deepEqual(preferredEncodings(null), ['identity']); - return test.done(); - }; - - this["Should include the identity encoding even if not explicity listed"] = function(test) { - test.ok(preferredEncodings('gzip').indexOf('identity') !== -1); - return test.done(); - }; - - this["Should not return identity encoding if q = 0"] = function(test) { - test.ok(preferredEncodings('identity;q=0').indexOf('identity') === -1); - return test.done(); - }; - - testCorrectEncoding = function(c) { - return _this["Should return " + c.selected + " for accept-encoding header " + c.accept + " with provided encoding " + c.provided] = function(test) { - test.deepEqual(preferredEncodings(c.accept, c.provided), c.selected); - return test.done(); - }; - }; - - testConfigurations = [ - { - accept: 'gzip', - provided: ['identity', 'gzip'], - selected: ['gzip', 'identity'] - }, { - accept: 'gzip, compress', - provided: ['compress'], - selected: ['compress'] - }, { - accept: 'deflate', - provided: ['gzip', 'identity'], - selected: ['identity'] - }, { - accept: '*', - provided: ['identity', 'gzip'], - selected: ['identity', 'gzip'] - }, { - accept: 'gzip, compress', - provided: ['compress', 'identity'], - selected: ['compress', 'identity'] - }, { - accept: 'gzip;q=0.8, identity;q=0.5, *;q=0.3', - provided: ['identity', 'gzip', 'compress'], - selected: ['gzip', 'identity', 'compress'] - }, { - accept: 'gzip;q=0.8, compress', - provided: ['gzip', 'compress'], - selected: ['compress', 'gzip'] - }, { - accept: 'gzip;q=0.8, compress', - provided: null, - selected: ['compress', 'gzip', 'identity'] - } - ]; - - for (_i = 0, _len = testConfigurations.length; _i < _len; _i++) { - configuration = testConfigurations[_i]; - testCorrectEncoding(configuration); - } - -}).call(this); diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/test/language.js b/node_modules/express/node_modules/connect/node_modules/negotiator/test/language.js deleted file mode 100644 index d98f26de2..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/test/language.js +++ /dev/null @@ -1,70 +0,0 @@ -(function() { - var configuration, preferredLanguages, testConfigurations, testCorrectType, _i, _len, - _this = this; - - preferredLanguages = require('../lib/language').preferredLanguages; - - this["Should not return a language when no is provided"] = function(test) { - test.deepEqual(preferredLanguages('*', []), []); - return test.done(); - }; - - this["Should not return a language when no language is acceptable"] = function(test) { - test.deepEqual(preferredLanguages('en', ['es']), []); - return test.done(); - }; - - this["Should not return a language with q = 0"] = function(test) { - test.deepEqual(preferredLanguages('en;q=0', ['en']), []); - return test.done(); - }; - - testCorrectType = function(c) { - return _this["Should return " + c.selected + " for accept-language header " + c.accept + " with provided language " + c.provided] = function(test) { - test.deepEqual(preferredLanguages(c.accept, c.provided), c.selected); - return test.done(); - }; - }; - - testConfigurations = [ - { - accept: 'en', - provided: ['en'], - selected: ['en'] - }, { - accept: '*', - provided: ['en'], - selected: ['en'] - }, { - accept: 'en-US, en;q=0.8', - provided: ['en-US', 'en-GB'], - selected: ['en-US', 'en-GB'] - }, { - accept: 'en-US, en-GB', - provided: ['en-US'], - selected: ['en-US'] - }, { - accept: 'en', - provided: ['en-US'], - selected: ['en-US'] - }, { - accept: 'en;q=0.8, es', - provided: ['en', 'es'], - selected: ['es', 'en'] - }, { - accept: 'en-US;q=0.8, es', - provided: ['en', 'es'], - selected: ['es', 'en'] - }, { - accept: 'en-US;q=0.8, es', - provided: null, - selected: ['es', 'en-US'] - } - ]; - - for (_i = 0, _len = testConfigurations.length; _i < _len; _i++) { - configuration = testConfigurations[_i]; - testCorrectType(configuration); - } - -}).call(this); diff --git a/node_modules/express/node_modules/connect/node_modules/negotiator/test/mediaType.js b/node_modules/express/node_modules/connect/node_modules/negotiator/test/mediaType.js deleted file mode 100644 index 08e492311..000000000 --- a/node_modules/express/node_modules/connect/node_modules/negotiator/test/mediaType.js +++ /dev/null @@ -1,70 +0,0 @@ -(function() { - var configuration, preferredMediaTypes, testConfigurations, testCorrectType, _i, _len, - _this = this; - - preferredMediaTypes = require('../lib/mediaType').preferredMediaTypes; - - this["Should not return a media type when no media type provided"] = function(test) { - test.deepEqual(preferredMediaTypes('*/*', []), []); - return test.done(); - }; - - this["Should not return a media type when no media type is acceptable"] = function(test) { - test.deepEqual(preferredMediaTypes('application/json', ['text/html']), []); - return test.done(); - }; - - this["Should not return a media type with q = 0"] = function(test) { - test.deepEqual(preferredMediaTypes('text/html;q=0', ['text/html']), []); - return test.done(); - }; - - testCorrectType = function(c) { - return _this["Should return " + c.selected + " for access header " + c.accept + " with provided types " + c.provided] = function(test) { - test.deepEqual(preferredMediaTypes(c.accept, c.provided), c.selected); - return test.done(); - }; - }; - - testConfigurations = [ - { - accept: 'text/html', - provided: ['text/html'], - selected: ['text/html'] - }, { - accept: '*/*', - provided: ['text/html'], - selected: ['text/html'] - }, { - accept: 'text/*', - provided: ['text/html'], - selected: ['text/html'] - }, { - accept: 'application/json, text/html', - provided: ['text/html'], - selected: ['text/html'] - }, { - accept: 'text/html;q=0.1', - provided: ['text/html'], - selected: ['text/html'] - }, { - accept: 'application/json, text/html', - provided: ['application/json', 'text/html'], - selected: ['application/json', 'text/html'] - }, { - accept: 'application/json;q=0.2, text/html', - provided: ['application/json', 'text/html'], - selected: ['text/html', 'application/json'] - }, { - accept: 'application/json;q=0.2, text/html', - provided: null, - selected: ['text/html', 'application/json'] - } - ]; - - for (_i = 0, _len = testConfigurations.length; _i < _len; _i++) { - configuration = testConfigurations[_i]; - testCorrectType(configuration); - } - -}).call(this); diff --git a/node_modules/express/node_modules/connect/node_modules/pause/.npmignore b/node_modules/express/node_modules/connect/node_modules/pause/.npmignore deleted file mode 100644 index f1250e584..000000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/express/node_modules/connect/node_modules/pause/History.md b/node_modules/express/node_modules/connect/node_modules/pause/History.md deleted file mode 100644 index c8aa68fa8..000000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/node_modules/connect/node_modules/pause/Makefile b/node_modules/express/node_modules/connect/node_modules/pause/Makefile deleted file mode 100644 index 4e9c8d36e..000000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/pause/Readme.md b/node_modules/express/node_modules/connect/node_modules/pause/Readme.md deleted file mode 100644 index 1cdd68a2a..000000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/Readme.md +++ /dev/null @@ -1,29 +0,0 @@ - -# pause - - Pause streams... - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/pause/index.js b/node_modules/express/node_modules/connect/node_modules/pause/index.js deleted file mode 100644 index 1b7b37948..000000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/index.js +++ /dev/null @@ -1,29 +0,0 @@ - -module.exports = function(obj){ - var onData - , onEnd - , events = []; - - // buffer data - obj.on('data', onData = function(data, encoding){ - events.push(['data', data, encoding]); - }); - - // buffer end - obj.on('end', onEnd = function(data, encoding){ - events.push(['end', data, encoding]); - }); - - return { - end: function(){ - obj.removeListener('data', onData); - obj.removeListener('end', onEnd); - }, - resume: function(){ - this.end(); - for (var i = 0, len = events.length; i < len; ++i) { - obj.emit.apply(obj, events[i]); - } - } - }; -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/pause/package.json b/node_modules/express/node_modules/connect/node_modules/pause/package.json deleted file mode 100644 index 045682778..000000000 --- a/node_modules/express/node_modules/connect/node_modules/pause/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "pause", - "version": "0.0.1", - "description": "Pause streams...", - "keywords": [], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "main": "index", - "readme": "\n# pause\n\n Pause streams...\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "pause@0.0.1", - "dist": { - "shasum": "6a6ba4ff6aed2c7a98f3781d8628af985898425b" - }, - "_from": "pause@0.0.1", - "_resolved": "https://registry.npmjs.org/pause/-/pause-0.0.1.tgz" -} diff --git a/node_modules/express/node_modules/connect/node_modules/qs/.gitmodules b/node_modules/express/node_modules/connect/node_modules/qs/.gitmodules deleted file mode 100644 index 49e31dac7..000000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/.gitmodules +++ /dev/null @@ -1,6 +0,0 @@ -[submodule "support/expresso"] - path = support/expresso - url = git://github.com/visionmedia/expresso.git -[submodule "support/should"] - path = support/should - url = git://github.com/visionmedia/should.js.git diff --git a/node_modules/express/node_modules/connect/node_modules/qs/.npmignore b/node_modules/express/node_modules/connect/node_modules/qs/.npmignore deleted file mode 100644 index e85ce2afa..000000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/.npmignore +++ /dev/null @@ -1,7 +0,0 @@ -test -.travis.yml -benchmark.js -component.json -examples.js -History.md -Makefile diff --git a/node_modules/express/node_modules/connect/node_modules/qs/Readme.md b/node_modules/express/node_modules/connect/node_modules/qs/Readme.md deleted file mode 100644 index 27e54a4af..000000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/Readme.md +++ /dev/null @@ -1,58 +0,0 @@ -# node-querystring - - query string parser for node and the browser supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others. - -## Installation - - $ npm install qs - -## Examples - -```js -var qs = require('qs'); - -qs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com'); -// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } } - -qs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }}) -// => user[name]=Tobi&user[email]=tobi%40learnboost.com -``` - -## Testing - -Install dev dependencies: - - $ npm install -d - -and execute: - - $ make test - -browser: - - $ open test/browser/index.html - -## License - -(The MIT License) - -Copyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/qs/index.js b/node_modules/express/node_modules/connect/node_modules/qs/index.js deleted file mode 100644 index b05938acc..000000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/index.js +++ /dev/null @@ -1,366 +0,0 @@ -/** - * Object#toString() ref for stringify(). - */ - -var toString = Object.prototype.toString; - -/** - * Object#hasOwnProperty ref - */ - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -/** - * Array#indexOf shim. - */ - -var indexOf = typeof Array.prototype.indexOf === 'function' - ? function(arr, el) { return arr.indexOf(el); } - : function(arr, el) { - for (var i = 0; i < arr.length; i++) { - if (arr[i] === el) return i; - } - return -1; - }; - -/** - * Array.isArray shim. - */ - -var isArray = Array.isArray || function(arr) { - return toString.call(arr) == '[object Array]'; -}; - -/** - * Object.keys shim. - */ - -var objectKeys = Object.keys || function(obj) { - var ret = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - ret.push(key); - } - } - return ret; -}; - -/** - * Array#forEach shim. - */ - -var forEach = typeof Array.prototype.forEach === 'function' - ? function(arr, fn) { return arr.forEach(fn); } - : function(arr, fn) { - for (var i = 0; i < arr.length; i++) fn(arr[i]); - }; - -/** - * Array#reduce shim. - */ - -var reduce = function(arr, fn, initial) { - if (typeof arr.reduce === 'function') return arr.reduce(fn, initial); - var res = initial; - for (var i = 0; i < arr.length; i++) res = fn(res, arr[i]); - return res; -}; - -/** - * Cache non-integer test regexp. - */ - -var isint = /^[0-9]+$/; - -function promote(parent, key) { - if (parent[key].length == 0) return parent[key] = {} - var t = {}; - for (var i in parent[key]) { - if (hasOwnProperty.call(parent[key], i)) { - t[i] = parent[key][i]; - } - } - parent[key] = t; - return t; -} - -function parse(parts, parent, key, val) { - var part = parts.shift(); - - // illegal - if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return; - - // end - if (!part) { - if (isArray(parent[key])) { - parent[key].push(val); - } else if ('object' == typeof parent[key]) { - parent[key] = val; - } else if ('undefined' == typeof parent[key]) { - parent[key] = val; - } else { - parent[key] = [parent[key], val]; - } - // array - } else { - var obj = parent[key] = parent[key] || []; - if (']' == part) { - if (isArray(obj)) { - if ('' != val) obj.push(val); - } else if ('object' == typeof obj) { - obj[objectKeys(obj).length] = val; - } else { - obj = parent[key] = [parent[key], val]; - } - // prop - } else if (~indexOf(part, ']')) { - part = part.substr(0, part.length - 1); - if (!isint.test(part) && isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - // key - } else { - if (!isint.test(part) && isArray(obj)) obj = promote(parent, key); - parse(parts, obj, part, val); - } - } -} - -/** - * Merge parent key/val pair. - */ - -function merge(parent, key, val){ - if (~indexOf(key, ']')) { - var parts = key.split('[') - , len = parts.length - , last = len - 1; - parse(parts, parent, 'base', val); - // optimize - } else { - if (!isint.test(key) && isArray(parent.base)) { - var t = {}; - for (var k in parent.base) t[k] = parent.base[k]; - parent.base = t; - } - set(parent.base, key, val); - } - - return parent; -} - -/** - * Compact sparse arrays. - */ - -function compact(obj) { - if ('object' != typeof obj) return obj; - - if (isArray(obj)) { - var ret = []; - - for (var i in obj) { - if (hasOwnProperty.call(obj, i)) { - ret.push(obj[i]); - } - } - - return ret; - } - - for (var key in obj) { - obj[key] = compact(obj[key]); - } - - return obj; -} - -/** - * Parse the given obj. - */ - -function parseObject(obj){ - var ret = { base: {} }; - - forEach(objectKeys(obj), function(name){ - merge(ret, name, obj[name]); - }); - - return compact(ret.base); -} - -/** - * Parse the given str. - */ - -function parseString(str){ - var ret = reduce(String(str).split('&'), function(ret, pair){ - var eql = indexOf(pair, '=') - , brace = lastBraceInKey(pair) - , key = pair.substr(0, brace || eql) - , val = pair.substr(brace || eql, pair.length) - , val = val.substr(indexOf(val, '=') + 1, val.length); - - // ?foo - if ('' == key) key = pair, val = ''; - if ('' == key) return ret; - - return merge(ret, decode(key), decode(val)); - }, { base: {} }).base; - - return compact(ret); -} - -/** - * Parse the given query `str` or `obj`, returning an object. - * - * @param {String} str | {Object} obj - * @return {Object} - * @api public - */ - -exports.parse = function(str){ - if (null == str || '' == str) return {}; - return 'object' == typeof str - ? parseObject(str) - : parseString(str); -}; - -/** - * Turn the given `obj` into a query string - * - * @param {Object} obj - * @return {String} - * @api public - */ - -var stringify = exports.stringify = function(obj, prefix) { - if (isArray(obj)) { - return stringifyArray(obj, prefix); - } else if ('[object Object]' == toString.call(obj)) { - return stringifyObject(obj, prefix); - } else if ('string' == typeof obj) { - return stringifyString(obj, prefix); - } else { - return prefix + '=' + encodeURIComponent(String(obj)); - } -}; - -/** - * Stringify the given `str`. - * - * @param {String} str - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyString(str, prefix) { - if (!prefix) throw new TypeError('stringify expects an object'); - return prefix + '=' + encodeURIComponent(str); -} - -/** - * Stringify the given `arr`. - * - * @param {Array} arr - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyArray(arr, prefix) { - var ret = []; - if (!prefix) throw new TypeError('stringify expects an object'); - for (var i = 0; i < arr.length; i++) { - ret.push(stringify(arr[i], prefix + '[' + i + ']')); - } - return ret.join('&'); -} - -/** - * Stringify the given `obj`. - * - * @param {Object} obj - * @param {String} prefix - * @return {String} - * @api private - */ - -function stringifyObject(obj, prefix) { - var ret = [] - , keys = objectKeys(obj) - , key; - - for (var i = 0, len = keys.length; i < len; ++i) { - key = keys[i]; - if ('' == key) continue; - if (null == obj[key]) { - ret.push(encodeURIComponent(key) + '='); - } else { - ret.push(stringify(obj[key], prefix - ? prefix + '[' + encodeURIComponent(key) + ']' - : encodeURIComponent(key))); - } - } - - return ret.join('&'); -} - -/** - * Set `obj`'s `key` to `val` respecting - * the weird and wonderful syntax of a qs, - * where "foo=bar&foo=baz" becomes an array. - * - * @param {Object} obj - * @param {String} key - * @param {String} val - * @api private - */ - -function set(obj, key, val) { - var v = obj[key]; - if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return; - if (undefined === v) { - obj[key] = val; - } else if (isArray(v)) { - v.push(val); - } else { - obj[key] = [v, val]; - } -} - -/** - * Locate last brace in `str` within the key. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function lastBraceInKey(str) { - var len = str.length - , brace - , c; - for (var i = 0; i < len; ++i) { - c = str[i]; - if (']' == c) brace = false; - if ('[' == c) brace = true; - if ('=' == c && !brace) return i; - } -} - -/** - * Decode `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -function decode(str) { - try { - return decodeURIComponent(str.replace(/\+/g, ' ')); - } catch (err) { - return str; - } -} diff --git a/node_modules/express/node_modules/connect/node_modules/qs/package.json b/node_modules/express/node_modules/connect/node_modules/qs/package.json deleted file mode 100644 index ae4f95a5b..000000000 --- a/node_modules/express/node_modules/connect/node_modules/qs/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "qs", - "description": "querystring parser", - "version": "0.6.6", - "keywords": [ - "query string", - "parser", - "component" - ], - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/node-querystring.git" - }, - "devDependencies": { - "mocha": "*", - "expect.js": "*" - }, - "scripts": { - "test": "make test" - }, - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "main": "index", - "engines": { - "node": "*" - }, - "readme": "# node-querystring\n\n query string parser for node and the browser supporting nesting, as it was removed from `0.3.x`, so this library provides the previous and commonly desired behaviour (and twice as fast). Used by [express](http://expressjs.com), [connect](http://senchalabs.github.com/connect) and others.\n\n## Installation\n\n $ npm install qs\n\n## Examples\n\n```js\nvar qs = require('qs');\n\nqs.parse('user[name][first]=Tobi&user[email]=tobi@learnboost.com');\n// => { user: { name: { first: 'Tobi' }, email: 'tobi@learnboost.com' } }\n\nqs.stringify({ user: { name: 'Tobi', email: 'tobi@learnboost.com' }})\n// => user[name]=Tobi&user[email]=tobi%40learnboost.com\n```\n\n## Testing\n\nInstall dev dependencies:\n\n $ npm install -d\n\nand execute:\n\n $ make test\n\nbrowser:\n\n $ open test/browser/index.html\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2010 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/node-querystring/issues" - }, - "homepage": "https://github.com/visionmedia/node-querystring", - "_id": "qs@0.6.6", - "dist": { - "shasum": "ea877bcb95c37f906a311d04885cf23c97c13998" - }, - "_from": "qs@0.6.6", - "_resolved": "https://registry.npmjs.org/qs/-/qs-0.6.6.tgz" -} diff --git a/node_modules/express/node_modules/connect/node_modules/raw-body/.npmignore b/node_modules/express/node_modules/connect/node_modules/raw-body/.npmignore deleted file mode 100644 index b59f7e3a9..000000000 --- a/node_modules/express/node_modules/connect/node_modules/raw-body/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test/ \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/raw-body/.travis.yml b/node_modules/express/node_modules/connect/node_modules/raw-body/.travis.yml deleted file mode 100644 index 595ded21d..000000000 --- a/node_modules/express/node_modules/connect/node_modules/raw-body/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -node_js: -- "0.8" -- "0.10" -- "0.11" -language: node_js -matrix: - allow_failures: - - node_js: "0.11" \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/raw-body/Makefile b/node_modules/express/node_modules/connect/node_modules/raw-body/Makefile deleted file mode 100644 index 642d6a64f..000000000 --- a/node_modules/express/node_modules/connect/node_modules/raw-body/Makefile +++ /dev/null @@ -1,13 +0,0 @@ -NODE ?= node -BIN = ./node_modules/.bin/ - -test: - @${NODE} ${BIN}mocha \ - --reporter spec \ - --bail \ - ./test/index.js - -clean: - @rm -rf node_modules - -.PHONY: test clean diff --git a/node_modules/express/node_modules/connect/node_modules/raw-body/README.md b/node_modules/express/node_modules/connect/node_modules/raw-body/README.md deleted file mode 100644 index 049ef6410..000000000 --- a/node_modules/express/node_modules/connect/node_modules/raw-body/README.md +++ /dev/null @@ -1,96 +0,0 @@ -# Raw Body [![Build Status](https://travis-ci.org/stream-utils/raw-body.png)](https://travis-ci.org/stream-utils/raw-body) - -Gets the entire buffer of a stream either as a `Buffer` or a string. -Validates the stream's length against an expected length and maximum limit. -Ideal for parsing request bodies. - -## API - -```js -var getRawBody = require('raw-body') - -app.use(function (req, res, next) { - getRawBody(req, { - length: req.headers['content-length'], - limit: '1mb', - encoding: 'utf8' - }, function (err, string) { - if (err) - return next(err) - - req.text = string - next() - }) -}) -``` - -or in a Koa generator: - -```js -app.use(function* (next) { - var string = yield getRawBody(this.req, { - length: this.length, - limit: '1mb', - encoding: 'utf8' - }) -}) -``` - -### getRawBody(stream, [options], [callback]) - -Returns a thunk for yielding with generators. - -Options: - -- `length` - The length length of the stream. - If the contents of the stream do not add up to this length, - an `400` error code is returned. -- `limit` - The byte limit of the body. - If the body ends up being larger than this limit, - a `413` error code is returned. -- `encoding` - The requested encoding. - By default, a `Buffer` instance will be returned. - Most likely, you want `utf8`. - You can use any type of encoding supported by [StringDecoder](http://nodejs.org/api/string_decoder.html). - You can also pass `true` which sets it to the default `utf8` - -`callback(err, res)`: - -- `err` - the following attributes will be defined if applicable: - - - `limit` - the limit in bytes - - `length` and `expected` - the expected length of the stream - - `received` - the received bytes - - `status` and `statusCode` - the corresponding status code for the error - - `type` - either `entity.too.large`, `request.size.invalid`, or `stream.encoding.set` - -- `res` - the result, either as a `String` if an encoding was set or a `Buffer` otherwise. - -If an error occurs, the stream will be paused, -and you are responsible for correctly disposing the stream. -For HTTP requests, no handling is required if you send a response. -For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks. - -## License - -The MIT License (MIT) - -Copyright (c) 2013 Jonathan Ong me@jongleberry.com - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express/node_modules/connect/node_modules/raw-body/index.js b/node_modules/express/node_modules/connect/node_modules/raw-body/index.js deleted file mode 100644 index b1798654d..000000000 --- a/node_modules/express/node_modules/connect/node_modules/raw-body/index.js +++ /dev/null @@ -1,160 +0,0 @@ -var StringDecoder = require('string_decoder').StringDecoder -var bytes = require('bytes') - -module.exports = function (stream, options, done) { - if (typeof options === 'function') { - done = options - options = {} - } else if (!options) { - options = {} - } - - // convert the limit to an integer - var limit = null - if (typeof options.limit === 'number') - limit = options.limit - if (typeof options.limit === 'string') - limit = bytes(options.limit) - - // convert the expected length to an integer - var length = null - if (!isNaN(options.length)) - length = parseInt(options.length, 10) - - // check the length and limit options. - // note: we intentionally leave the stream paused, - // so users should handle the stream themselves. - if (limit !== null && length !== null && length > limit) { - if (typeof stream.pause === 'function') - stream.pause() - - process.nextTick(function () { - var err = makeError('request entity too large', 'entity.too.large') - err.status = err.statusCode = 413 - err.length = err.expected = length - err.limit = limit - done(err) - }) - return defer - } - - var state = stream._readableState - // streams2+: assert the stream encoding is buffer. - if (state && state.encoding != null) { - if (typeof stream.pause === 'function') - stream.pause() - - process.nextTick(function () { - var err = makeError('stream encoding should not be set', - 'stream.encoding.set') - // developer error - err.status = err.statusCode = 500 - done(err) - }) - return defer - } - - var received = 0 - // note: we delegate any invalid encodings to the constructor - var decoder = options.encoding - ? new StringDecoder(options.encoding === true ? 'utf8' : options.encoding) - : null - var buffer = decoder - ? '' - : [] - - stream.on('data', onData) - stream.once('end', onEnd) - stream.once('error', onEnd) - stream.once('close', cleanup) - - return defer - - // yieldable support - function defer(fn) { - done = fn - } - - function onData(chunk) { - received += chunk.length - decoder - ? buffer += decoder.write(chunk) - : buffer.push(chunk) - - if (limit !== null && received > limit) { - if (typeof stream.pause === 'function') - stream.pause() - var err = makeError('request entity too large', 'entity.too.large') - err.status = err.statusCode = 413 - err.received = received - err.limit = limit - done(err) - cleanup() - } - } - - function onEnd(err) { - if (err) { - if (typeof stream.pause === 'function') - stream.pause() - done(err) - } else if (length !== null && received !== length) { - err = makeError('request size did not match content length', - 'request.size.invalid') - err.status = err.statusCode = 400 - err.received = received - err.length = err.expected = length - done(err) - } else { - done(null, decoder - ? buffer + endStringDecoder(decoder) - : Buffer.concat(buffer) - ) - } - - cleanup() - } - - function cleanup() { - received = buffer = null - - stream.removeListener('data', onData) - stream.removeListener('end', onEnd) - stream.removeListener('error', onEnd) - stream.removeListener('close', cleanup) - } -} - -// to create serializable errors you must re-set message so -// that it is enumerable and you must re configure the type -// property so that is writable and enumerable -function makeError(message, type) { - var error = new Error() - error.message = message - Object.defineProperty(error, 'type', { - value: type, - enumerable: true, - writable: true, - configurable: true - }) - return error -} - -// https://github.com/Raynos/body/blob/2512ced39e31776e5a2f7492b907330badac3a40/index.js#L72 -// bug fix for missing `StringDecoder.end` in v0.8.x -function endStringDecoder(decoder) { - if (decoder.end) { - return decoder.end() - } - - var res = "" - - if (decoder.charReceived) { - var cr = decoder.charReceived - var buf = decoder.charBuffer - var enc = decoder.encoding - res += buf.slice(0, cr).toString(enc) - } - - return res -} diff --git a/node_modules/express/node_modules/connect/node_modules/raw-body/package.json b/node_modules/express/node_modules/connect/node_modules/raw-body/package.json deleted file mode 100644 index e077c02c6..000000000 --- a/node_modules/express/node_modules/connect/node_modules/raw-body/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "raw-body", - "description": "Get and validate the raw body of a readable stream.", - "version": "1.1.2", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/stream-utils/raw-body.git" - }, - "bugs": { - "url": "https://github.com/stream-utils/raw-body/issues" - }, - "dependencies": { - "bytes": "~0.2.1" - }, - "devDependencies": { - "readable-stream": "~1.0.17", - "co": "2", - "gnode": "~0.0.4", - "mocha": "~1.14.0", - "through": "~2.3.4", - "request": "~2.27.0", - "assert-tap": "~0.1.4" - }, - "scripts": { - "test": "NODE=gnode make test && node ./test/acceptance.js" - }, - "engines": { - "node": ">= 0.8.0" - }, - "readme": "# Raw Body [![Build Status](https://travis-ci.org/stream-utils/raw-body.png)](https://travis-ci.org/stream-utils/raw-body)\n\nGets the entire buffer of a stream either as a `Buffer` or a string.\nValidates the stream's length against an expected length and maximum limit.\nIdeal for parsing request bodies.\n\n## API\n\n```js\nvar getRawBody = require('raw-body')\n\napp.use(function (req, res, next) {\n getRawBody(req, {\n length: req.headers['content-length'],\n limit: '1mb',\n encoding: 'utf8'\n }, function (err, string) {\n if (err)\n return next(err)\n\n req.text = string\n next()\n })\n})\n```\n\nor in a Koa generator:\n\n```js\napp.use(function* (next) {\n var string = yield getRawBody(this.req, {\n length: this.length,\n limit: '1mb',\n encoding: 'utf8'\n })\n})\n```\n\n### getRawBody(stream, [options], [callback])\n\nReturns a thunk for yielding with generators.\n\nOptions:\n\n- `length` - The length length of the stream.\n If the contents of the stream do not add up to this length,\n an `400` error code is returned.\n- `limit` - The byte limit of the body.\n If the body ends up being larger than this limit,\n a `413` error code is returned.\n- `encoding` - The requested encoding.\n By default, a `Buffer` instance will be returned.\n Most likely, you want `utf8`.\n You can use any type of encoding supported by [StringDecoder](http://nodejs.org/api/string_decoder.html).\n You can also pass `true` which sets it to the default `utf8`\n\n`callback(err, res)`:\n\n- `err` - the following attributes will be defined if applicable:\n\n - `limit` - the limit in bytes\n - `length` and `expected` - the expected length of the stream\n - `received` - the received bytes\n - `status` and `statusCode` - the corresponding status code for the error\n - `type` - either `entity.too.large`, `request.size.invalid`, or `stream.encoding.set`\n\n- `res` - the result, either as a `String` if an encoding was set or a `Buffer` otherwise.\n\nIf an error occurs, the stream will be paused,\nand you are responsible for correctly disposing the stream.\nFor HTTP requests, no handling is required if you send a response.\nFor streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks.\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2013 Jonathan Ong me@jongleberry.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/stream-utils/raw-body", - "_id": "raw-body@1.1.2", - "dist": { - "shasum": "55fd7c5da025273ccddb645397e0b0a73c8fb97d" - }, - "_from": "raw-body@1.1.2", - "_resolved": "https://registry.npmjs.org/raw-body/-/raw-body-1.1.2.tgz" -} diff --git a/node_modules/express/node_modules/connect/node_modules/uid2/LICENSE b/node_modules/express/node_modules/connect/node_modules/uid2/LICENSE deleted file mode 100644 index bdfab69b5..000000000 --- a/node_modules/express/node_modules/connect/node_modules/uid2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Marco Aurelio - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/connect/node_modules/uid2/index.js b/node_modules/express/node_modules/connect/node_modules/uid2/index.js deleted file mode 100644 index 6240b3083..000000000 --- a/node_modules/express/node_modules/connect/node_modules/uid2/index.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Module dependencies - */ - -var crypto = require('crypto'); - -/** - * 62 characters in the ascii range that can be used in URLs without special - * encoding. - */ -var UIDCHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - -/** - * Make a Buffer into a string ready for use in URLs - * - * @param {String} - * @returns {String} - * @api private - */ -function tostr(bytes) { - var chars, r, i; - - r = []; - for (i = 0; i < bytes.length; i++) { - r.push(UIDCHARS[bytes[i] % UIDCHARS.length]); - } - - return r.join(''); -} - -/** - * Generate an Unique Id - * - * @param {Number} length The number of chars of the uid - * @param {Number} cb (optional) Callback for async uid generation - * @api public - */ - -function uid(length, cb) { - - if (typeof cb === 'undefined') { - return tostr(crypto.pseudoRandomBytes(length)); - } else { - crypto.pseudoRandomBytes(length, function(err, bytes) { - if (err) return cb(err); - cb(null, tostr(bytes)); - }) - } -} - -/** - * Exports - */ - -module.exports = uid; diff --git a/node_modules/express/node_modules/connect/node_modules/uid2/package.json b/node_modules/express/node_modules/connect/node_modules/uid2/package.json deleted file mode 100644 index b9786fab6..000000000 --- a/node_modules/express/node_modules/connect/node_modules/uid2/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "uid2", - "description": "strong uid", - "tags": [ - "uid" - ], - "version": "0.0.3", - "dependencies": {}, - "readme": "ERROR: No README data found!", - "_id": "uid2@0.0.3", - "dist": { - "shasum": "d703205c61c80bcdf3b295602c523bd3a312dd6e" - }, - "_from": "uid2@0.0.3", - "_resolved": "https://registry.npmjs.org/uid2/-/uid2-0.0.3.tgz" -} diff --git a/node_modules/express/node_modules/connect/package.json b/node_modules/express/node_modules/connect/package.json deleted file mode 100644 index b3c6240aa..000000000 --- a/node_modules/express/node_modules/connect/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "connect", - "version": "2.12.0", - "description": "High performance middleware framework", - "keywords": [ - "framework", - "web", - "middleware", - "connect", - "rack" - ], - "repository": { - "type": "git", - "url": "git://github.com/senchalabs/connect.git" - }, - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "dependencies": { - "batch": "0.5.0", - "qs": "0.6.6", - "cookie-signature": "1.0.1", - "buffer-crc32": "0.2.1", - "cookie": "0.1.0", - "send": "0.1.4", - "bytes": "0.2.1", - "fresh": "0.2.0", - "pause": "0.0.1", - "uid2": "0.0.3", - "debug": ">= 0.7.3 < 1", - "methods": "0.1.0", - "raw-body": "1.1.2", - "negotiator": "0.3.0", - "multiparty": "2.2.0" - }, - "devDependencies": { - "should": ">= 2.0.2 < 3", - "mocha": ">= 1.13.0 < 2", - "jade": ">= 0.35.0 < 1", - "dox": ">= 0.4.4 < 1" - }, - "licenses": [ - { - "type": "MIT", - "url": "https://raw.github.com/senchalabs/connect/master/LICENSE" - } - ], - "main": "index", - "engines": { - "node": ">= 0.8.0" - }, - "scripts": { - "test": "make" - }, - "readme": "# Connect [![build status](https://secure.travis-ci.org/senchalabs/connect.png)](http://travis-ci.org/senchalabs/connect)\n\n Connect is an extensible HTTP server framework for [node](http://nodejs.org), providing high performance \"plugins\" known as _middleware_.\n\n Connect is bundled with over _20_ commonly used middleware, including\n a logger, session support, cookie parser, and [more](http://senchalabs.github.com/connect). Be sure to view the 2.x [documentation](http://senchalabs.github.com/connect/).\n\n```js\nvar connect = require('connect')\n , http = require('http');\n\nvar app = connect()\n .use(connect.favicon())\n .use(connect.logger('dev'))\n .use(connect.static('public'))\n .use(connect.directory('public'))\n .use(connect.cookieParser())\n .use(connect.session({ secret: 'my secret here' }))\n .use(function(req, res){\n res.end('Hello from Connect!\\n');\n });\n\nhttp.createServer(app).listen(3000);\n```\n\n## Middleware\n\n - [basicAuth](http://www.senchalabs.org/connect/basicAuth.html)\n - [bodyParser](http://www.senchalabs.org/connect/bodyParser.html)\n - [compress](http://www.senchalabs.org/connect/compress.html)\n - [cookieParser](http://www.senchalabs.org/connect/cookieParser.html)\n - [cookieSession](http://www.senchalabs.org/connect/cookieSession.html)\n - [csrf](http://www.senchalabs.org/connect/csrf.html)\n - [directory](http://www.senchalabs.org/connect/directory.html)\n - [errorHandler](http://www.senchalabs.org/connect/errorHandler.html)\n - [favicon](http://www.senchalabs.org/connect/favicon.html)\n - [json](http://www.senchalabs.org/connect/json.html)\n - [limit](http://www.senchalabs.org/connect/limit.html)\n - [logger](http://www.senchalabs.org/connect/logger.html)\n - [methodOverride](http://www.senchalabs.org/connect/methodOverride.html)\n - [multipart](http://www.senchalabs.org/connect/multipart.html)\n - [urlencoded](http://www.senchalabs.org/connect/urlencoded.html)\n - [query](http://www.senchalabs.org/connect/query.html)\n - [responseTime](http://www.senchalabs.org/connect/responseTime.html)\n - [session](http://www.senchalabs.org/connect/session.html)\n - [static](http://www.senchalabs.org/connect/static.html)\n - [staticCache](http://www.senchalabs.org/connect/staticCache.html)\n - [subdomains](http://www.senchalabs.org/connect/subdomains.html)\n - [vhost](http://www.senchalabs.org/connect/vhost.html)\n\n## Running Tests\n\nfirst:\n\n $ npm install -d\n\nthen:\n\n $ make test\n\n## Contributors\n\n https://github.com/senchalabs/connect/graphs/contributors\n\n## Node Compatibility\n\n Connect `< 1.x` is compatible with node 0.2.x\n\n\n Connect `1.x` is compatible with node 0.4.x\n\n\n Connect `2.x` is compatible with node 0.6.x\n\n\n Connect (_master_) is compatible with node 0.8.x\n\n## CLA\n\n [http://sencha.com/cla](http://sencha.com/cla)\n\n## License\n\nView the [LICENSE](https://github.com/senchalabs/connect/blob/master/LICENSE) file. The [Silk](http://www.famfamfam.com/lab/icons/silk/) icons used by the `directory` middleware created by/copyright of [FAMFAMFAM](http://www.famfamfam.com/).\n", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/senchalabs/connect/issues" - }, - "homepage": "https://github.com/senchalabs/connect", - "_id": "connect@2.12.0", - "dist": { - "shasum": "c22b246a17d16d9019266fcedccb80fe3478254a" - }, - "_from": "connect@2.12.0", - "_resolved": "https://registry.npmjs.org/connect/-/connect-2.12.0.tgz" -} diff --git a/node_modules/express/node_modules/cookie-signature/.npmignore b/node_modules/express/node_modules/cookie-signature/.npmignore deleted file mode 100644 index f1250e584..000000000 --- a/node_modules/express/node_modules/cookie-signature/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/express/node_modules/cookie-signature/History.md b/node_modules/express/node_modules/cookie-signature/History.md deleted file mode 100644 index 9e3017998..000000000 --- a/node_modules/express/node_modules/cookie-signature/History.md +++ /dev/null @@ -1,11 +0,0 @@ - -1.0.1 / 2013-04-15 -================== - - * Revert "Changed underlying HMAC algo. to sha512." - * Revert "Fix for timing attacks on MAC verification." - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/node_modules/cookie-signature/Makefile b/node_modules/express/node_modules/cookie-signature/Makefile deleted file mode 100644 index 4e9c8d36e..000000000 --- a/node_modules/express/node_modules/cookie-signature/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/cookie-signature/Readme.md b/node_modules/express/node_modules/cookie-signature/Readme.md deleted file mode 100644 index 2559e841b..000000000 --- a/node_modules/express/node_modules/cookie-signature/Readme.md +++ /dev/null @@ -1,42 +0,0 @@ - -# cookie-signature - - Sign and unsign cookies. - -## Example - -```js -var cookie = require('cookie-signature'); - -var val = cookie.sign('hello', 'tobiiscool'); -val.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI'); - -var val = cookie.sign('hello', 'tobiiscool'); -cookie.unsign(val, 'tobiiscool').should.equal('hello'); -cookie.unsign(val, 'luna').should.be.false; -``` - -## License - -(The MIT License) - -Copyright (c) 2012 LearnBoost <tj@learnboost.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/cookie-signature/index.js b/node_modules/express/node_modules/cookie-signature/index.js deleted file mode 100644 index ed62814e6..000000000 --- a/node_modules/express/node_modules/cookie-signature/index.js +++ /dev/null @@ -1,42 +0,0 @@ - -/** - * Module dependencies. - */ - -var crypto = require('crypto'); - -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ - -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError('cookie required'); - if ('string' != typeof secret) throw new TypeError('secret required'); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; - -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ - -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError('cookie required'); - if ('string' != typeof secret) throw new TypeError('secret required'); - var str = val.slice(0, val.lastIndexOf('.')); - return exports.sign(str, secret) == val ? str : false; -}; diff --git a/node_modules/express/node_modules/cookie-signature/package.json b/node_modules/express/node_modules/cookie-signature/package.json deleted file mode 100644 index fb2964988..000000000 --- a/node_modules/express/node_modules/cookie-signature/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "cookie-signature", - "version": "1.0.1", - "description": "Sign and unsign cookies", - "keywords": [ - "cookie", - "sign", - "unsign" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@learnboost.com" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "main": "index", - "readme": "\n# cookie-signature\n\n Sign and unsign cookies.\n\n## Example\n\n```js\nvar cookie = require('cookie-signature');\n\nvar val = cookie.sign('hello', 'tobiiscool');\nval.should.equal('hello.DGDUkGlIkCzPz+C0B064FNgHdEjox7ch8tOBGslZ5QI');\n\nvar val = cookie.sign('hello', 'tobiiscool');\ncookie.unsign(val, 'tobiiscool').should.equal('hello');\ncookie.unsign(val, 'luna').should.be.false;\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 LearnBoost <tj@learnboost.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "cookie-signature@1.0.1", - "dist": { - "shasum": "8cb1735bc2445307e195d7acfcefc82a60f57d9c" - }, - "_from": "cookie-signature@1.0.1", - "_resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.1.tgz" -} diff --git a/node_modules/express/node_modules/cookie/.npmignore b/node_modules/express/node_modules/cookie/.npmignore deleted file mode 100644 index 3c3629e64..000000000 --- a/node_modules/express/node_modules/cookie/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/express/node_modules/cookie/.travis.yml b/node_modules/express/node_modules/cookie/.travis.yml deleted file mode 100644 index 9400c1188..000000000 --- a/node_modules/express/node_modules/cookie/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - "0.6" - - "0.8" - - "0.10" diff --git a/node_modules/express/node_modules/cookie/LICENSE b/node_modules/express/node_modules/cookie/LICENSE deleted file mode 100644 index 249d9def9..000000000 --- a/node_modules/express/node_modules/cookie/LICENSE +++ /dev/null @@ -1,9 +0,0 @@ -// MIT License - -Copyright (C) Roman Shtylman - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/cookie/README.md b/node_modules/express/node_modules/cookie/README.md deleted file mode 100644 index 5187ed1cc..000000000 --- a/node_modules/express/node_modules/cookie/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# cookie [![Build Status](https://secure.travis-ci.org/shtylman/node-cookie.png?branch=master)](http://travis-ci.org/shtylman/node-cookie) # - -cookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers. - -See [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies. - -## how? - -``` -npm install cookie -``` - -```javascript -var cookie = require('cookie'); - -var hdr = cookie.serialize('foo', 'bar'); -// hdr = 'foo=bar'; - -var cookies = cookie.parse('foo=bar; cat=meow; dog=ruff'); -// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' }; -``` - -## more - -The serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values. - -### path -> cookie path - -### expires -> absolute expiration date for the cookie (Date object) - -### maxAge -> relative max age of the cookie from when the client receives it (seconds) - -### domain -> domain for the cookie - -### secure -> true or false - -### httpOnly -> true or false - diff --git a/node_modules/express/node_modules/cookie/index.js b/node_modules/express/node_modules/cookie/index.js deleted file mode 100644 index 16bdb65dd..000000000 --- a/node_modules/express/node_modules/cookie/index.js +++ /dev/null @@ -1,70 +0,0 @@ - -/// Serialize the a name value pair into a cookie string suitable for -/// http headers. An optional options object specified cookie parameters -/// -/// serialize('foo', 'bar', { httpOnly: true }) -/// => "foo=bar; httpOnly" -/// -/// @param {String} name -/// @param {String} val -/// @param {Object} options -/// @return {String} -var serialize = function(name, val, opt){ - opt = opt || {}; - var enc = opt.encode || encode; - var pairs = [name + '=' + enc(val)]; - - if (opt.maxAge) pairs.push('Max-Age=' + opt.maxAge); - if (opt.domain) pairs.push('Domain=' + opt.domain); - if (opt.path) pairs.push('Path=' + opt.path); - if (opt.expires) pairs.push('Expires=' + opt.expires.toUTCString()); - if (opt.httpOnly) pairs.push('HttpOnly'); - if (opt.secure) pairs.push('Secure'); - - return pairs.join('; '); -}; - -/// Parse the given cookie header string into an object -/// The object has the various cookies as keys(names) => values -/// @param {String} str -/// @return {Object} -var parse = function(str, opt) { - opt = opt || {}; - var obj = {} - var pairs = str.split(/[;,] */); - var dec = opt.decode || decode; - - pairs.forEach(function(pair) { - var eq_idx = pair.indexOf('=') - - // skip things that don't look like key=value - if (eq_idx < 0) { - return; - } - - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); - - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } - - // only assign once - if (undefined == obj[key]) { - try { - obj[key] = dec(val); - } catch (e) { - obj[key] = val; - } - } - }); - - return obj; -}; - -var encode = encodeURIComponent; -var decode = decodeURIComponent; - -module.exports.serialize = serialize; -module.exports.parse = parse; diff --git a/node_modules/express/node_modules/cookie/package.json b/node_modules/express/node_modules/cookie/package.json deleted file mode 100644 index 4732a577f..000000000 --- a/node_modules/express/node_modules/cookie/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "author": { - "name": "Roman Shtylman", - "email": "shtylman@gmail.com" - }, - "name": "cookie", - "description": "cookie parsing and serialization", - "version": "0.1.0", - "repository": { - "type": "git", - "url": "git://github.com/shtylman/node-cookie.git" - }, - "keywords": [ - "cookie", - "cookies" - ], - "main": "index.js", - "scripts": { - "test": "mocha" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "1.x.x" - }, - "optionalDependencies": {}, - "engines": { - "node": "*" - }, - "readme": "# cookie [![Build Status](https://secure.travis-ci.org/shtylman/node-cookie.png?branch=master)](http://travis-ci.org/shtylman/node-cookie) #\n\ncookie is a basic cookie parser and serializer. It doesn't make assumptions about how you are going to deal with your cookies. It basically just provides a way to read and write the HTTP cookie headers.\n\nSee [RFC6265](http://tools.ietf.org/html/rfc6265) for details about the http header for cookies.\n\n## how?\n\n```\nnpm install cookie\n```\n\n```javascript\nvar cookie = require('cookie');\n\nvar hdr = cookie.serialize('foo', 'bar');\n// hdr = 'foo=bar';\n\nvar cookies = cookie.parse('foo=bar; cat=meow; dog=ruff');\n// cookies = { foo: 'bar', cat: 'meow', dog: 'ruff' };\n```\n\n## more\n\nThe serialize function takes a third parameter, an object, to set cookie options. See the RFC for valid values.\n\n### path\n> cookie path\n\n### expires\n> absolute expiration date for the cookie (Date object)\n\n### maxAge\n> relative max age of the cookie from when the client receives it (seconds)\n\n### domain\n> domain for the cookie\n\n### secure\n> true or false\n\n### httpOnly\n> true or false\n\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/shtylman/node-cookie/issues" - }, - "homepage": "https://github.com/shtylman/node-cookie", - "_id": "cookie@0.1.0", - "dist": { - "shasum": "47533ff33776b0b380de876f5dc9702b22b39987" - }, - "_from": "cookie@0.1.0", - "_resolved": "https://registry.npmjs.org/cookie/-/cookie-0.1.0.tgz" -} diff --git a/node_modules/express/node_modules/cookie/test/mocha.opts b/node_modules/express/node_modules/cookie/test/mocha.opts deleted file mode 100644 index e2bfcc5ac..000000000 --- a/node_modules/express/node_modules/cookie/test/mocha.opts +++ /dev/null @@ -1 +0,0 @@ ---ui qunit diff --git a/node_modules/express/node_modules/cookie/test/parse.js b/node_modules/express/node_modules/cookie/test/parse.js deleted file mode 100644 index c6c27a20b..000000000 --- a/node_modules/express/node_modules/cookie/test/parse.js +++ /dev/null @@ -1,44 +0,0 @@ - -var assert = require('assert'); - -var cookie = require('..'); - -suite('parse'); - -test('basic', function() { - assert.deepEqual({ foo: 'bar' }, cookie.parse('foo=bar')); - assert.deepEqual({ foo: '123' }, cookie.parse('foo=123')); -}); - -test('ignore spaces', function() { - assert.deepEqual({ FOO: 'bar', baz: 'raz' }, - cookie.parse('FOO = bar; baz = raz')); -}); - -test('escaping', function() { - assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' }, - cookie.parse('foo="bar=123456789&name=Magic+Mouse"')); - - assert.deepEqual({ email: ' ",;/' }, - cookie.parse('email=%20%22%2c%3b%2f')); -}); - -test('ignore escaping error and return original value', function() { - assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar')); -}); - -test('ignore non values', function() { - assert.deepEqual({ foo: '%1', bar: 'bar' }, cookie.parse('foo=%1;bar=bar;HttpOnly;Secure')); -}); - -test('unencoded', function() { - assert.deepEqual({ foo: 'bar=123456789&name=Magic+Mouse' }, - cookie.parse('foo="bar=123456789&name=Magic+Mouse"',{ - decode: function(value) { return value; } - })); - - assert.deepEqual({ email: '%20%22%2c%3b%2f' }, - cookie.parse('email=%20%22%2c%3b%2f',{ - decode: function(value) { return value; } - })); -}) diff --git a/node_modules/express/node_modules/cookie/test/serialize.js b/node_modules/express/node_modules/cookie/test/serialize.js deleted file mode 100644 index 86bb8c935..000000000 --- a/node_modules/express/node_modules/cookie/test/serialize.js +++ /dev/null @@ -1,64 +0,0 @@ -// builtin -var assert = require('assert'); - -var cookie = require('..'); - -suite('serialize'); - -test('basic', function() { - assert.equal('foo=bar', cookie.serialize('foo', 'bar')); - assert.equal('foo=bar%20baz', cookie.serialize('foo', 'bar baz')); -}); - -test('path', function() { - assert.equal('foo=bar; Path=/', cookie.serialize('foo', 'bar', { - path: '/' - })); -}); - -test('secure', function() { - assert.equal('foo=bar; Secure', cookie.serialize('foo', 'bar', { - secure: true - })); - - assert.equal('foo=bar', cookie.serialize('foo', 'bar', { - secure: false - })); -}); - -test('domain', function() { - assert.equal('foo=bar; Domain=example.com', cookie.serialize('foo', 'bar', { - domain: 'example.com' - })); -}); - -test('httpOnly', function() { - assert.equal('foo=bar; HttpOnly', cookie.serialize('foo', 'bar', { - httpOnly: true - })); -}); - -test('maxAge', function() { - assert.equal('foo=bar; Max-Age=1000', cookie.serialize('foo', 'bar', { - maxAge: 1000 - })); -}); - -test('escaping', function() { - assert.deepEqual('cat=%2B%20', cookie.serialize('cat', '+ ')); -}); - -test('parse->serialize', function() { - - assert.deepEqual({ cat: 'foo=123&name=baz five' }, cookie.parse( - cookie.serialize('cat', 'foo=123&name=baz five'))); - - assert.deepEqual({ cat: ' ";/' }, cookie.parse( - cookie.serialize('cat', ' ";/'))); -}); - -test('unencoded', function() { - assert.deepEqual('cat=+ ', cookie.serialize('cat', '+ ', { - encode: function(value) { return value; } - })); -}) diff --git a/node_modules/express/node_modules/debug/Readme.md b/node_modules/express/node_modules/debug/Readme.md deleted file mode 100644 index c5a34e8b8..000000000 --- a/node_modules/express/node_modules/debug/Readme.md +++ /dev/null @@ -1,115 +0,0 @@ -# debug - - tiny node.js debugging utility modelled after node core's debugging technique. - -## Installation - -``` -$ npm install debug -``` - -## Usage - - With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. - -Example _app.js_: - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example _worker.js_: - -```js -var debug = require('debug')('worker'); - -setInterval(function(){ - debug('doing some work'); -}, 1000); -``` - - The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: - - ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) - - ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) - -## Millisecond diff - - When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - - When stderr is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - _(NOTE: Debug now uses stderr instead of stdout, so the correct shell command for this example is actually `DEBUG=* node example/worker 2> out &`)_ - - ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - -## Conventions - - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". - -## Wildcards - - The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". - -## Browser support - - Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - a('doing some work'); -}, 1200); -``` - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/debug/debug.js b/node_modules/express/node_modules/debug/debug.js deleted file mode 100644 index 509dc0ded..000000000 --- a/node_modules/express/node_modules/debug/debug.js +++ /dev/null @@ -1,137 +0,0 @@ - -/** - * Expose `debug()` as the module. - */ - -module.exports = debug; - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - fmt = coerce(fmt); - - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } -} - -/** - * The currently active debug mode names. - */ - -debug.names = []; -debug.skips = []; - -/** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - -debug.enable = function(name) { - try { - localStorage.debug = name; - } catch(e){} - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } -}; - -/** - * Disable debug output. - * - * @api public - */ - -debug.disable = function(){ - debug.enable(''); -}; - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -}; - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; -}; - -/** - * Coerce `val`. - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} - -// persist - -try { - if (window.localStorage) debug.enable(localStorage.debug); -} catch(e){} diff --git a/node_modules/express/node_modules/debug/index.js b/node_modules/express/node_modules/debug/index.js deleted file mode 100644 index e02c13b7f..000000000 --- a/node_modules/express/node_modules/debug/index.js +++ /dev/null @@ -1,5 +0,0 @@ -if ('undefined' == typeof window) { - module.exports = require('./lib/debug'); -} else { - module.exports = require('./debug'); -} diff --git a/node_modules/express/node_modules/debug/lib/debug.js b/node_modules/express/node_modules/debug/lib/debug.js deleted file mode 100644 index 3b0a9183d..000000000 --- a/node_modules/express/node_modules/debug/lib/debug.js +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Module dependencies. - */ - -var tty = require('tty'); - -/** - * Expose `debug()` as the module. - */ - -module.exports = debug; - -/** - * Enabled debuggers. - */ - -var names = [] - , skips = []; - -(process.env.DEBUG || '') - .split(/[\s,]+/) - .forEach(function(name){ - name = name.replace('*', '.*?'); - if (name[0] === '-') { - skips.push(new RegExp('^' + name.substr(1) + '$')); - } else { - names.push(new RegExp('^' + name + '$')); - } - }); - -/** - * Colors. - */ - -var colors = [6, 2, 3, 4, 5, 1]; - -/** - * Previous debug() call. - */ - -var prev = {}; - -/** - * Previously assigned color. - */ - -var prevColor = 0; - -/** - * Is stdout a TTY? Colored output is disabled when `true`. - */ - -var isatty = tty.isatty(2); - -/** - * Select a color. - * - * @return {Number} - * @api private - */ - -function color() { - return colors[prevColor++ % colors.length]; -} - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -function humanize(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -} - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - function disabled(){} - disabled.enabled = false; - - var match = skips.some(function(re){ - return re.test(name); - }); - - if (match) return disabled; - - match = names.some(function(re){ - return re.test(name); - }); - - if (!match) return disabled; - var c = color(); - - function colored(fmt) { - fmt = coerce(fmt); - - var curr = new Date; - var ms = curr - (prev[name] || curr); - prev[name] = curr; - - fmt = ' \u001b[9' + c + 'm' + name + ' ' - + '\u001b[3' + c + 'm\u001b[90m' - + fmt + '\u001b[3' + c + 'm' - + ' +' + humanize(ms) + '\u001b[0m'; - - console.error.apply(this, arguments); - } - - function plain(fmt) { - fmt = coerce(fmt); - - fmt = new Date().toUTCString() - + ' ' + name + ' ' + fmt; - console.error.apply(this, arguments); - } - - colored.enabled = plain.enabled = true; - - return isatty || process.env.DEBUG_COLORS - ? colored - : plain; -} - -/** - * Coerce `val`. - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} diff --git a/node_modules/express/node_modules/debug/package.json b/node_modules/express/node_modules/debug/package.json deleted file mode 100644 index 24abce648..000000000 --- a/node_modules/express/node_modules/debug/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "debug", - "version": "0.7.4", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" - }, - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*" - }, - "main": "lib/debug.js", - "browser": "./debug.js", - "engines": { - "node": "*" - }, - "files": [ - "lib/debug.js", - "debug.js", - "index.js" - ], - "component": { - "scripts": { - "debug/index.js": "index.js", - "debug/debug.js": "debug.js" - } - }, - "readme": "# debug\n\n tiny node.js debugging utility modelled after node core's debugging technique.\n\n## Installation\n\n```\n$ npm install debug\n```\n\n## Usage\n\n With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n \nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stderr is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n _(NOTE: Debug now uses stderr instead of stdout, so the correct shell command for this example is actually `DEBUG=* node example/worker 2> out &`)_\n \n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n \n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\". \n\n## Wildcards\n\n The \"*\" character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. \n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n a('doing some work');\n}, 1200);\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/debug/issues" - }, - "homepage": "https://github.com/visionmedia/debug", - "_id": "debug@0.7.4", - "_from": "debug@>= 0.7.3 < 1" -} diff --git a/node_modules/express/node_modules/fresh/.npmignore b/node_modules/express/node_modules/fresh/.npmignore deleted file mode 100644 index 9daeafb98..000000000 --- a/node_modules/express/node_modules/fresh/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/node_modules/express/node_modules/fresh/History.md b/node_modules/express/node_modules/fresh/History.md deleted file mode 100644 index 60a2903f9..000000000 --- a/node_modules/express/node_modules/fresh/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.2.0 / 2013-08-11 -================== - - * fix: return false for no-cache diff --git a/node_modules/express/node_modules/fresh/Makefile b/node_modules/express/node_modules/fresh/Makefile deleted file mode 100644 index 8e8640f2e..000000000 --- a/node_modules/express/node_modules/fresh/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --reporter spec \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/fresh/Readme.md b/node_modules/express/node_modules/fresh/Readme.md deleted file mode 100644 index 61366c577..000000000 --- a/node_modules/express/node_modules/fresh/Readme.md +++ /dev/null @@ -1,57 +0,0 @@ - -# node-fresh - - HTTP response freshness testing - -## fresh(req, res) - - Check freshness of `req` and `res` headers. - - When the cache is "fresh" __true__ is returned, - otherwise __false__ is returned to indicate that - the cache is now stale. - -## Example: - -```js -var req = { 'if-none-match': 'tobi' }; -var res = { 'etag': 'luna' }; -fresh(req, res); -// => false - -var req = { 'if-none-match': 'tobi' }; -var res = { 'etag': 'tobi' }; -fresh(req, res); -// => true -``` - -## Installation - -``` -$ npm install fresh -``` - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/fresh/index.js b/node_modules/express/node_modules/fresh/index.js deleted file mode 100644 index 9c3f47d1e..000000000 --- a/node_modules/express/node_modules/fresh/index.js +++ /dev/null @@ -1,53 +0,0 @@ - -/** - * Expose `fresh()`. - */ - -module.exports = fresh; - -/** - * Check freshness of `req` and `res` headers. - * - * When the cache is "fresh" __true__ is returned, - * otherwise __false__ is returned to indicate that - * the cache is now stale. - * - * @param {Object} req - * @param {Object} res - * @return {Boolean} - * @api public - */ - -function fresh(req, res) { - // defaults - var etagMatches = true; - var notModified = true; - - // fields - var modifiedSince = req['if-modified-since']; - var noneMatch = req['if-none-match']; - var lastModified = res['last-modified']; - var etag = res['etag']; - var cc = req['cache-control']; - - // unconditional request - if (!modifiedSince && !noneMatch) return false; - - // check for no-cache cache request directive - if (cc && cc.indexOf('no-cache') !== -1) return false; - - // parse if-none-match - if (noneMatch) noneMatch = noneMatch.split(/ *, */); - - // if-none-match - if (noneMatch) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0]; - - // if-modified-since - if (modifiedSince) { - modifiedSince = new Date(modifiedSince); - lastModified = new Date(lastModified); - notModified = lastModified <= modifiedSince; - } - - return !! (etagMatches && notModified); -} \ No newline at end of file diff --git a/node_modules/express/node_modules/fresh/package.json b/node_modules/express/node_modules/fresh/package.json deleted file mode 100644 index 473dc4d69..000000000 --- a/node_modules/express/node_modules/fresh/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "fresh", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "description": "HTTP response freshness testing", - "version": "0.2.0", - "main": "index.js", - "repository": { - "type": "git", - "url": "https://github.com/visionmedia/node-fresh.git" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "readme": "\n# node-fresh\n\n HTTP response freshness testing\n\n## fresh(req, res)\n\n Check freshness of `req` and `res` headers.\n\n When the cache is \"fresh\" __true__ is returned,\n otherwise __false__ is returned to indicate that\n the cache is now stale.\n\n## Example:\n\n```js\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'luna' };\nfresh(req, res);\n// => false\n\nvar req = { 'if-none-match': 'tobi' };\nvar res = { 'etag': 'tobi' };\nfresh(req, res);\n// => true\n```\n\n## Installation\n\n```\n$ npm install fresh\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/node-fresh/issues" - }, - "homepage": "https://github.com/visionmedia/node-fresh", - "_id": "fresh@0.2.0", - "dist": { - "shasum": "a4591b7f0ce1ad3083cb13b06d189a8d0e2c925c" - }, - "_from": "fresh@0.2.0", - "_resolved": "https://registry.npmjs.org/fresh/-/fresh-0.2.0.tgz" -} diff --git a/node_modules/express/node_modules/merge-descriptors/.npmignore b/node_modules/express/node_modules/merge-descriptors/.npmignore deleted file mode 100644 index f62e6050c..000000000 --- a/node_modules/express/node_modules/merge-descriptors/.npmignore +++ /dev/null @@ -1,59 +0,0 @@ -# Compiled source # -################### -*.com -*.class -*.dll -*.exe -*.o -*.so - -# Packages # -############ -# it's better to unpack these files and commit the raw source -# git has its own built in compression methods -*.7z -*.dmg -*.gz -*.iso -*.jar -*.rar -*.tar -*.zip - -# Logs and databases # -###################### -*.log -*.sql -*.sqlite - -# OS generated files # -###################### -.DS_Store* -ehthumbs.db -Icon? -Thumbs.db - -# Node.js # -########### -lib-cov -*.seed -*.log -*.csv -*.dat -*.out -*.pid -*.gz - -pids -logs -results - -node_modules -npm-debug.log - -# Components # -############## - -/build -/components -/vendors \ No newline at end of file diff --git a/node_modules/express/node_modules/merge-descriptors/README.md b/node_modules/express/node_modules/merge-descriptors/README.md deleted file mode 100644 index 34d715df0..000000000 --- a/node_modules/express/node_modules/merge-descriptors/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# Merge Descriptors [![Build Status](https://travis-ci.org/jonathanong/merge-descriptors.png)](https://travis-ci.org/jonathanong/merge-descriptors) - -Merge objects using descriptors. - -```js -var thing = { - get name() { - return 'jon' - } -} - -var animal = { - -} - -merge(animal, thing) - -animal.name === 'jon' -``` - -## API - -### merge(destination, source) - -Overwrites `destination`'s descriptors with `source`'s. - -## License - -The MIT License (MIT) - -Copyright (c) 2013 Jonathan Ong me@jongleberry.com - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/express/node_modules/merge-descriptors/component.json b/node_modules/express/node_modules/merge-descriptors/component.json deleted file mode 100644 index 26b1b8e85..000000000 --- a/node_modules/express/node_modules/merge-descriptors/component.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "merge-descriptors", - "description": "Merge objects using descriptors", - "version": "0.0.1", - "scripts": [ - "index.js" - ], - "repo": "jonathanong/merge-descriptors", - "license": "MIT" -} \ No newline at end of file diff --git a/node_modules/express/node_modules/merge-descriptors/index.js b/node_modules/express/node_modules/merge-descriptors/index.js deleted file mode 100644 index e4e23793c..000000000 --- a/node_modules/express/node_modules/merge-descriptors/index.js +++ /dev/null @@ -1,8 +0,0 @@ -module.exports = function (dest, src) { - Object.getOwnPropertyNames(src).forEach(function (name) { - var descriptor = Object.getOwnPropertyDescriptor(src, name) - Object.defineProperty(dest, name, descriptor) - }) - - return dest -} \ No newline at end of file diff --git a/node_modules/express/node_modules/merge-descriptors/package.json b/node_modules/express/node_modules/merge-descriptors/package.json deleted file mode 100644 index e6325f7b6..000000000 --- a/node_modules/express/node_modules/merge-descriptors/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "merge-descriptors", - "description": "Merge objects using descriptors", - "version": "0.0.1", - "author": { - "name": "Jonathan Ong", - "email": "me@jongleberry.com", - "url": "http://jongleberry.com" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/jonathanong/merge-descriptors.git" - }, - "bugs": { - "url": "https://github.com/jonathanong/merge-descriptors/issues" - }, - "scripts": { - "test": "make test;" - }, - "readme": "# Merge Descriptors [![Build Status](https://travis-ci.org/jonathanong/merge-descriptors.png)](https://travis-ci.org/jonathanong/merge-descriptors)\n\nMerge objects using descriptors.\n\n```js\nvar thing = {\n get name() {\n return 'jon'\n }\n}\n\nvar animal = {\n\n}\n\nmerge(animal, thing)\n\nanimal.name === 'jon'\n```\n\n## API\n\n### merge(destination, source)\n\nOverwrites `destination`'s descriptors with `source`'s.\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2013 Jonathan Ong me@jongleberry.com\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.", - "readmeFilename": "README.md", - "homepage": "https://github.com/jonathanong/merge-descriptors", - "_id": "merge-descriptors@0.0.1", - "dist": { - "shasum": "c6594e61b3fda36889f00404dfcb32624b8c5a63" - }, - "_from": "merge-descriptors@0.0.1", - "_resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-0.0.1.tgz" -} diff --git a/node_modules/express/node_modules/methods/History.md b/node_modules/express/node_modules/methods/History.md deleted file mode 100644 index 1d0e229fd..000000000 --- a/node_modules/express/node_modules/methods/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.1.0 / 2013-10-28 -================== - - * add http.METHODS support diff --git a/node_modules/express/node_modules/methods/Readme.md b/node_modules/express/node_modules/methods/Readme.md deleted file mode 100644 index ac0658e21..000000000 --- a/node_modules/express/node_modules/methods/Readme.md +++ /dev/null @@ -1,4 +0,0 @@ - -# Methods - - HTTP verbs that node core's parser supports. diff --git a/node_modules/express/node_modules/methods/index.js b/node_modules/express/node_modules/methods/index.js deleted file mode 100644 index 95b93f5fb..000000000 --- a/node_modules/express/node_modules/methods/index.js +++ /dev/null @@ -1,37 +0,0 @@ - -var http = require('http'); - -if (http.METHODS) { - module.exports = http.METHODS.map(function(method){ - return method.toLowerCase(); - }); - - return; -} - -module.exports = [ - 'get', - 'post', - 'put', - 'head', - 'delete', - 'options', - 'trace', - 'copy', - 'lock', - 'mkcol', - 'move', - 'propfind', - 'proppatch', - 'unlock', - 'report', - 'mkactivity', - 'checkout', - 'merge', - 'm-search', - 'notify', - 'subscribe', - 'unsubscribe', - 'patch', - 'search' -]; diff --git a/node_modules/express/node_modules/methods/package.json b/node_modules/express/node_modules/methods/package.json deleted file mode 100644 index 129cbf7b3..000000000 --- a/node_modules/express/node_modules/methods/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "methods", - "version": "0.1.0", - "description": "HTTP methods that node supports", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "keywords": [ - "http", - "methods" - ], - "author": { - "name": "TJ Holowaychuk" - }, - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/node-methods.git" - }, - "readme": "\n# Methods\n\n HTTP verbs that node core's parser supports.\n", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/node-methods/issues" - }, - "homepage": "https://github.com/visionmedia/node-methods", - "_id": "methods@0.1.0", - "dist": { - "shasum": "e0bd5232e34655efe6840453a92a45d4b030719e" - }, - "_from": "methods@0.1.0", - "_resolved": "https://registry.npmjs.org/methods/-/methods-0.1.0.tgz" -} diff --git a/node_modules/express/node_modules/mkdirp/.npmignore b/node_modules/express/node_modules/mkdirp/.npmignore deleted file mode 100644 index 9303c347e..000000000 --- a/node_modules/express/node_modules/mkdirp/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/express/node_modules/mkdirp/.travis.yml b/node_modules/express/node_modules/mkdirp/.travis.yml deleted file mode 100644 index 84fd7ca24..000000000 --- a/node_modules/express/node_modules/mkdirp/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.9 diff --git a/node_modules/express/node_modules/mkdirp/LICENSE b/node_modules/express/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1aeb0..000000000 --- a/node_modules/express/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express/node_modules/mkdirp/examples/pow.js b/node_modules/express/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index e6924212e..000000000 --- a/node_modules/express/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/express/node_modules/mkdirp/index.js b/node_modules/express/node_modules/mkdirp/index.js deleted file mode 100644 index fda6de8a2..000000000 --- a/node_modules/express/node_modules/mkdirp/index.js +++ /dev/null @@ -1,82 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, mode, f, made) { - if (typeof mode === 'function' || mode === undefined) { - f = mode; - mode = 0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - fs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), mode, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, mode, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - fs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, mode, made) { - if (mode === undefined) { - mode = 0777 & (~process.umask()); - } - if (!made) made = null; - - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - try { - fs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), mode, made); - sync(p, mode, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = fs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; diff --git a/node_modules/express/node_modules/mkdirp/package.json b/node_modules/express/node_modules/mkdirp/package.json deleted file mode 100644 index 38b3a4dc1..000000000 --- a/node_modules/express/node_modules/mkdirp/package.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "mkdirp", - "description": "Recursively mkdir, like `mkdir -p`", - "version": "0.3.5", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "main": "./index", - "keywords": [ - "mkdir", - "directory" - ], - "repository": { - "type": "git", - "url": "http://github.com/substack/node-mkdirp.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "devDependencies": { - "tap": "~0.4.0" - }, - "license": "MIT", - "readme": "# mkdirp\n\nLike `mkdir -p`, but in node.js!\n\n[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)\n\n# example\n\n## pow.js\n\n```js\nvar mkdirp = require('mkdirp');\n \nmkdirp('/tmp/foo/bar/baz', function (err) {\n if (err) console.error(err)\n else console.log('pow!')\n});\n```\n\nOutput\n\n```\npow!\n```\n\nAnd now /tmp/foo/bar/baz exists, huzzah!\n\n# methods\n\n```js\nvar mkdirp = require('mkdirp');\n```\n\n## mkdirp(dir, mode, cb)\n\nCreate a new directory and any necessary subdirectories at `dir` with octal\npermission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\n## mkdirp.sync(dir, mode)\n\nSynchronously create a new directory and any necessary subdirectories at `dir`\nwith octal permission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\nReturns the first directory that had to be created, if any.\n\n# install\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install mkdirp\n```\n\n# license\n\nMIT\n", - "readmeFilename": "readme.markdown", - "bugs": { - "url": "https://github.com/substack/node-mkdirp/issues" - }, - "homepage": "https://github.com/substack/node-mkdirp", - "_id": "mkdirp@0.3.5", - "dist": { - "shasum": "b83530397e309beac8bb6614fd1d35ebd5c06fc6" - }, - "_from": "mkdirp@0.3.5", - "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.3.5.tgz" -} diff --git a/node_modules/express/node_modules/mkdirp/readme.markdown b/node_modules/express/node_modules/mkdirp/readme.markdown deleted file mode 100644 index 83b0216ab..000000000 --- a/node_modules/express/node_modules/mkdirp/readme.markdown +++ /dev/null @@ -1,63 +0,0 @@ -# mkdirp - -Like `mkdir -p`, but in node.js! - -[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) - -# example - -## pow.js - -```js -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); -``` - -Output - -``` -pow! -``` - -And now /tmp/foo/bar/baz exists, huzzah! - -# methods - -```js -var mkdirp = require('mkdirp'); -``` - -## mkdirp(dir, mode, cb) - -Create a new directory and any necessary subdirectories at `dir` with octal -permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -`cb(err, made)` fires with the error or the first directory `made` -that had to be created, if any. - -## mkdirp.sync(dir, mode) - -Synchronously create a new directory and any necessary subdirectories at `dir` -with octal permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -Returns the first directory that had to be created, if any. - -# install - -With [npm](http://npmjs.org) do: - -``` -npm install mkdirp -``` - -# license - -MIT diff --git a/node_modules/express/node_modules/mkdirp/test/chmod.js b/node_modules/express/node_modules/mkdirp/test/chmod.js deleted file mode 100644 index 520dcb8e9..000000000 --- a/node_modules/express/node_modules/mkdirp/test/chmod.js +++ /dev/null @@ -1,38 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -test('chmod-pre', function (t) { - var mode = 0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); - -test('chmod', function (t) { - var mode = 0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.end(); - }); - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/clobber.js b/node_modules/express/node_modules/mkdirp/test/clobber.js deleted file mode 100644 index 0eb709987..000000000 --- a/node_modules/express/node_modules/mkdirp/test/clobber.js +++ /dev/null @@ -1,37 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -// a file in the way -var itw = ps.slice(0, 3).join('/'); - - -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); - - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) - -test('clobber', function (t) { - t.plan(2); - mkdirp(file, 0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/mkdirp.js b/node_modules/express/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index b07cd70c1..000000000 --- a/node_modules/express/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('woo', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/perm.js b/node_modules/express/node_modules/mkdirp/test/perm.js deleted file mode 100644 index 23a7abbd2..000000000 --- a/node_modules/express/node_modules/mkdirp/test/perm.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('async perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); - -test('async root perm', function (t) { - mkdirp('/tmp', 0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/perm_sync.js b/node_modules/express/node_modules/mkdirp/test/perm_sync.js deleted file mode 100644 index f685f6090..000000000 --- a/node_modules/express/node_modules/mkdirp/test/perm_sync.js +++ /dev/null @@ -1,39 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); - -test('sync root perm', function (t) { - t.plan(1); - - var file = '/tmp'; - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/race.js b/node_modules/express/node_modules/mkdirp/test/race.js deleted file mode 100644 index 96a044763..000000000 --- a/node_modules/express/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,41 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('race', function (t) { - t.plan(4); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - } - }) - }) - }); - } -}); diff --git a/node_modules/express/node_modules/mkdirp/test/rel.js b/node_modules/express/node_modules/mkdirp/test/rel.js deleted file mode 100644 index 79858243a..000000000 --- a/node_modules/express/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('rel', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/return.js b/node_modules/express/node_modules/mkdirp/test/return.js deleted file mode 100644 index bce68e561..000000000 --- a/node_modules/express/node_modules/mkdirp/test/return.js +++ /dev/null @@ -1,25 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, '/tmp/' + x); - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, null); - }); - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/return_sync.js b/node_modules/express/node_modules/mkdirp/test/return_sync.js deleted file mode 100644 index 7c222d355..000000000 --- a/node_modules/express/node_modules/mkdirp/test/return_sync.js +++ /dev/null @@ -1,24 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - // Note that this will throw on failure, which will fail the test. - var made = mkdirp.sync(file); - t.equal(made, '/tmp/' + x); - - // making the same file again should have no effect. - made = mkdirp.sync(file); - t.equal(made, null); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/root.js b/node_modules/express/node_modules/mkdirp/test/root.js deleted file mode 100644 index 97ad7a2f3..000000000 --- a/node_modules/express/node_modules/mkdirp/test/root.js +++ /dev/null @@ -1,18 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('root', function (t) { - // '/' on unix, 'c:/' on windows. - var file = path.resolve('/'); - - mkdirp(file, 0755, function (err) { - if (err) throw err - fs.stat(file, function (er, stat) { - if (er) throw er - t.ok(stat.isDirectory(), 'target is a directory'); - t.end(); - }) - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/sync.js b/node_modules/express/node_modules/mkdirp/test/sync.js deleted file mode 100644 index 7530cada8..000000000 --- a/node_modules/express/node_modules/mkdirp/test/sync.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file, 0755); - } catch (err) { - t.fail(err); - return t.end(); - } - - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }); - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/umask.js b/node_modules/express/node_modules/mkdirp/test/umask.js deleted file mode 100644 index 64ccafe22..000000000 --- a/node_modules/express/node_modules/mkdirp/test/umask.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('implicit mode from umask', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0777 & (~process.umask())); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/express/node_modules/mkdirp/test/umask_sync.js b/node_modules/express/node_modules/mkdirp/test/umask_sync.js deleted file mode 100644 index 35bd5cbbf..000000000 --- a/node_modules/express/node_modules/mkdirp/test/umask_sync.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('umask sync modes', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file); - } catch (err) { - t.fail(err); - return t.end(); - } - - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, (0777 & (~process.umask()))); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }); - }); -}); diff --git a/node_modules/express/node_modules/range-parser/.npmignore b/node_modules/express/node_modules/range-parser/.npmignore deleted file mode 100644 index 9daeafb98..000000000 --- a/node_modules/express/node_modules/range-parser/.npmignore +++ /dev/null @@ -1 +0,0 @@ -test diff --git a/node_modules/express/node_modules/range-parser/History.md b/node_modules/express/node_modules/range-parser/History.md deleted file mode 100644 index 82df7b1e4..000000000 --- a/node_modules/express/node_modules/range-parser/History.md +++ /dev/null @@ -1,15 +0,0 @@ - -0.0.4 / 2012-06-17 -================== - - * changed: ret -1 for unsatisfiable and -2 when invalid - -0.0.3 / 2012-06-17 -================== - - * fix last-byte-pos default to len - 1 - -0.0.2 / 2012-06-14 -================== - - * add `.type` diff --git a/node_modules/express/node_modules/range-parser/Makefile b/node_modules/express/node_modules/range-parser/Makefile deleted file mode 100644 index 8e8640f2e..000000000 --- a/node_modules/express/node_modules/range-parser/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --reporter spec \ - --require should - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/range-parser/Readme.md b/node_modules/express/node_modules/range-parser/Readme.md deleted file mode 100644 index b2a67fe83..000000000 --- a/node_modules/express/node_modules/range-parser/Readme.md +++ /dev/null @@ -1,28 +0,0 @@ - -# node-range-parser - - Range header field parser. - -## Example: - -```js -assert(-1 == parse(200, 'bytes=500-20')); -assert(-2 == parse(200, 'bytes=malformed')); -parse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }])); -parse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }])); -parse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }])); -parse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }])); -parse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }])); -parse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }])); -parse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }])); -parse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }])); -parse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }])); -parse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }])); -parse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }])); -``` - -## Installation - -``` -$ npm install range-parser -``` \ No newline at end of file diff --git a/node_modules/express/node_modules/range-parser/index.js b/node_modules/express/node_modules/range-parser/index.js deleted file mode 100644 index 9b0f7a8ec..000000000 --- a/node_modules/express/node_modules/range-parser/index.js +++ /dev/null @@ -1,49 +0,0 @@ - -/** - * Parse "Range" header `str` relative to the given file `size`. - * - * @param {Number} size - * @param {String} str - * @return {Array} - * @api public - */ - -module.exports = function(size, str){ - var valid = true; - var i = str.indexOf('='); - - if (-1 == i) return -2; - - var arr = str.slice(i + 1).split(',').map(function(range){ - var range = range.split('-') - , start = parseInt(range[0], 10) - , end = parseInt(range[1], 10); - - // -nnn - if (isNaN(start)) { - start = size - end; - end = size - 1; - // nnn- - } else if (isNaN(end)) { - end = size - 1; - } - - // limit last-byte-pos to current length - if (end > size - 1) end = size - 1; - - // invalid - if (isNaN(start) - || isNaN(end) - || start > end - || start < 0) valid = false; - - return { - start: start, - end: end - }; - }); - - arr.type = str.slice(0, i); - - return valid ? arr : -1; -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/range-parser/package.json b/node_modules/express/node_modules/range-parser/package.json deleted file mode 100644 index 276113784..000000000 --- a/node_modules/express/node_modules/range-parser/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "range-parser", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca", - "url": "http://tjholowaychuk.com" - }, - "description": "Range header field string parser", - "version": "0.0.4", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "mocha": "*", - "should": "*" - }, - "readme": "\n# node-range-parser\n\n Range header field parser.\n\n## Example:\n\n```js\nassert(-1 == parse(200, 'bytes=500-20'));\nassert(-2 == parse(200, 'bytes=malformed'));\nparse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }]));\nparse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }]));\nparse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }]));\nparse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }]));\nparse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }]));\nparse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }]));\nparse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }]));\nparse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }]));\nparse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }]));\nparse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }]));\nparse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }]));\n```\n\n## Installation\n\n```\n$ npm install range-parser\n```", - "readmeFilename": "Readme.md", - "_id": "range-parser@0.0.4", - "dist": { - "shasum": "83d826681e378aac53688dca7947bd9f9c96fe77" - }, - "_from": "range-parser@0.0.4", - "_resolved": "https://registry.npmjs.org/range-parser/-/range-parser-0.0.4.tgz" -} diff --git a/node_modules/express/node_modules/send/.npmignore b/node_modules/express/node_modules/send/.npmignore deleted file mode 100644 index f1250e584..000000000 --- a/node_modules/express/node_modules/send/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/express/node_modules/send/History.md b/node_modules/express/node_modules/send/History.md deleted file mode 100644 index 55c4af745..000000000 --- a/node_modules/express/node_modules/send/History.md +++ /dev/null @@ -1,40 +0,0 @@ - -0.1.4 / 2013-08-11 -================== - - * update fresh - -0.1.3 / 2013-07-08 -================== - - * Revert "Fix fd leak" - -0.1.2 / 2013-07-03 -================== - - * Fix fd leak - -0.1.0 / 2012-08-25 -================== - - * add options parameter to send() that is passed to fs.createReadStream() [kanongil] - -0.0.4 / 2012-08-16 -================== - - * allow custom "Accept-Ranges" definition - -0.0.3 / 2012-07-16 -================== - - * fix normalization of the root directory. Closes #3 - -0.0.2 / 2012-07-09 -================== - - * add passing of req explicitly for now (YUCK) - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/express/node_modules/send/Makefile b/node_modules/express/node_modules/send/Makefile deleted file mode 100644 index a9dcfd50d..000000000 --- a/node_modules/express/node_modules/send/Makefile +++ /dev/null @@ -1,8 +0,0 @@ - -test: - @./node_modules/.bin/mocha \ - --require should \ - --reporter spec \ - --bail - -.PHONY: test \ No newline at end of file diff --git a/node_modules/express/node_modules/send/Readme.md b/node_modules/express/node_modules/send/Readme.md deleted file mode 100644 index ea7b23410..000000000 --- a/node_modules/express/node_modules/send/Readme.md +++ /dev/null @@ -1,128 +0,0 @@ -# send - - Send is Connect's `static()` extracted for generalized use, a streaming static file - server supporting partial responses (Ranges), conditional-GET negotiation, high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework. - -## Installation - - $ npm install send - -## Examples - - Small: - -```js -var http = require('http'); -var send = require('send'); - -var app = http.createServer(function(req, res){ - send(req, req.url).pipe(res); -}).listen(3000); -``` - - Serving from a root directory with custom error-handling: - -```js -var http = require('http'); -var send = require('send'); -var url = require('url'); - -var app = http.createServer(function(req, res){ - // your custom error-handling logic: - function error(err) { - res.statusCode = err.status || 500; - res.end(err.message); - } - - // your custom directory handling logic: - function redirect() { - res.statusCode = 301; - res.setHeader('Location', req.url + '/'); - res.end('Redirecting to ' + req.url + '/'); - } - - // transfer arbitrary files from within - // /www/example.com/public/* - send(req, url.parse(req.url).pathname) - .root('/www/example.com/public') - .on('error', error) - .on('directory', redirect) - .pipe(res); -}).listen(3000); -``` - -## API - -### Events - - - `error` an error occurred `(err)` - - `directory` a directory was requested - - `file` a file was requested `(path, stat)` - - `stream` file streaming has started `(stream)` - - `end` streaming has completed - -### .root(dir) - - Serve files relative to `path`. Aliased as `.from(dir)`. - -### .index(path) - - By default send supports "index.html" files, to disable this - invoke `.index(false)` or to supply a new index pass a string. - -### .maxage(ms) - - Provide a max-age in milliseconds for http caching, defaults to 0. - -### .hidden(bool) - - Enable or disable transfer of hidden files, defaults to false. - -## Error-handling - - By default when no `error` listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc. - -## Caching - - It does _not_ perform internal caching, you should use a reverse proxy cache such - as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;). - -## Debugging - - To enable `debug()` instrumentation output export __DEBUG__: - -``` -$ DEBUG=send node app -``` - -## Running tests - -``` -$ npm install -$ make test -``` - -## License - -(The MIT License) - -Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express/node_modules/send/index.js b/node_modules/express/node_modules/send/index.js deleted file mode 100644 index f17158d85..000000000 --- a/node_modules/express/node_modules/send/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/send'); \ No newline at end of file diff --git a/node_modules/express/node_modules/send/lib/send.js b/node_modules/express/node_modules/send/lib/send.js deleted file mode 100644 index a3d94a69d..000000000 --- a/node_modules/express/node_modules/send/lib/send.js +++ /dev/null @@ -1,474 +0,0 @@ - -/** - * Module dependencies. - */ - -var debug = require('debug')('send') - , parseRange = require('range-parser') - , Stream = require('stream') - , mime = require('mime') - , fresh = require('fresh') - , path = require('path') - , http = require('http') - , fs = require('fs') - , basename = path.basename - , normalize = path.normalize - , join = path.join - , utils = require('./utils'); - -/** - * Expose `send`. - */ - -exports = module.exports = send; - -/** - * Expose mime module. - */ - -exports.mime = mime; - -/** - * Return a `SendStream` for `req` and `path`. - * - * @param {Request} req - * @param {String} path - * @param {Object} options - * @return {SendStream} - * @api public - */ - -function send(req, path, options) { - return new SendStream(req, path, options); -} - -/** - * Initialize a `SendStream` with the given `path`. - * - * Events: - * - * - `error` an error occurred - * - `stream` file streaming has started - * - `end` streaming has completed - * - `directory` a directory was requested - * - * @param {Request} req - * @param {String} path - * @param {Object} options - * @api private - */ - -function SendStream(req, path, options) { - var self = this; - this.req = req; - this.path = path; - this.options = options || {}; - this.maxage(0); - this.hidden(false); - this.index('index.html'); -} - -/** - * Inherits from `Stream.prototype`. - */ - -SendStream.prototype.__proto__ = Stream.prototype; - -/** - * Enable or disable "hidden" (dot) files. - * - * @param {Boolean} path - * @return {SendStream} - * @api public - */ - -SendStream.prototype.hidden = function(val){ - debug('hidden %s', val); - this._hidden = val; - return this; -}; - -/** - * Set index `path`, set to a falsy - * value to disable index support. - * - * @param {String|Boolean} path - * @return {SendStream} - * @api public - */ - -SendStream.prototype.index = function(path){ - debug('index %s', path); - this._index = path; - return this; -}; - -/** - * Set root `path`. - * - * @param {String} path - * @return {SendStream} - * @api public - */ - -SendStream.prototype.root = -SendStream.prototype.from = function(path){ - this._root = normalize(path); - return this; -}; - -/** - * Set max-age to `ms`. - * - * @param {Number} ms - * @return {SendStream} - * @api public - */ - -SendStream.prototype.maxage = function(ms){ - if (Infinity == ms) ms = 60 * 60 * 24 * 365 * 1000; - debug('max-age %d', ms); - this._maxage = ms; - return this; -}; - -/** - * Emit error with `status`. - * - * @param {Number} status - * @api private - */ - -SendStream.prototype.error = function(status, err){ - var res = this.res; - var msg = http.STATUS_CODES[status]; - err = err || new Error(msg); - err.status = status; - if (this.listeners('error').length) return this.emit('error', err); - res.statusCode = err.status; - res.end(msg); -}; - -/** - * Check if the pathname is potentially malicious. - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.isMalicious = function(){ - return !this._root && ~this.path.indexOf('..'); -}; - -/** - * Check if the pathname ends with "/". - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.hasTrailingSlash = function(){ - return '/' == this.path[this.path.length - 1]; -}; - -/** - * Check if the basename leads with ".". - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.hasLeadingDot = function(){ - return '.' == basename(this.path)[0]; -}; - -/** - * Check if this is a conditional GET request. - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.isConditionalGET = function(){ - return this.req.headers['if-none-match'] - || this.req.headers['if-modified-since']; -}; - -/** - * Strip content-* header fields. - * - * @api private - */ - -SendStream.prototype.removeContentHeaderFields = function(){ - var res = this.res; - Object.keys(res._headers).forEach(function(field){ - if (0 == field.indexOf('content')) { - res.removeHeader(field); - } - }); -}; - -/** - * Respond with 304 not modified. - * - * @api private - */ - -SendStream.prototype.notModified = function(){ - var res = this.res; - debug('not modified'); - this.removeContentHeaderFields(); - res.statusCode = 304; - res.end(); -}; - -/** - * Check if the request is cacheable, aka - * responded with 2xx or 304 (see RFC 2616 section 14.2{5,6}). - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.isCachable = function(){ - var res = this.res; - return (res.statusCode >= 200 && res.statusCode < 300) || 304 == res.statusCode; -}; - -/** - * Handle stat() error. - * - * @param {Error} err - * @api private - */ - -SendStream.prototype.onStatError = function(err){ - var notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR']; - if (~notfound.indexOf(err.code)) return this.error(404, err); - this.error(500, err); -}; - -/** - * Check if the cache is fresh. - * - * @return {Boolean} - * @api private - */ - -SendStream.prototype.isFresh = function(){ - return fresh(this.req.headers, this.res._headers); -}; - -/** - * Redirect to `path`. - * - * @param {String} path - * @api private - */ - -SendStream.prototype.redirect = function(path){ - if (this.listeners('directory').length) return this.emit('directory'); - var res = this.res; - path += '/'; - res.statusCode = 301; - res.setHeader('Location', path); - res.end('Redirecting to ' + utils.escape(path)); -}; - -/** - * Pipe to `res. - * - * @param {Stream} res - * @return {Stream} res - * @api public - */ - -SendStream.prototype.pipe = function(res){ - var self = this - , args = arguments - , path = this.path - , root = this._root; - - // references - this.res = res; - - // invalid request uri - path = utils.decode(path); - if (-1 == path) return this.error(400); - - // null byte(s) - if (~path.indexOf('\0')) return this.error(400); - - // join / normalize from optional root dir - if (root) path = normalize(join(this._root, path)); - - // ".." is malicious without "root" - if (this.isMalicious()) return this.error(403); - - // malicious path - if (root && 0 != path.indexOf(root)) return this.error(403); - - // hidden file support - if (!this._hidden && this.hasLeadingDot()) return this.error(404); - - // index file support - if (this._index && this.hasTrailingSlash()) path += this._index; - - debug('stat "%s"', path); - fs.stat(path, function(err, stat){ - if (err) return self.onStatError(err); - if (stat.isDirectory()) return self.redirect(self.path); - self.emit('file', path, stat); - self.send(path, stat); - }); - - return res; -}; - -/** - * Transfer `path`. - * - * @param {String} path - * @api public - */ - -SendStream.prototype.send = function(path, stat){ - var options = this.options; - var len = stat.size; - var res = this.res; - var req = this.req; - var ranges = req.headers.range; - var offset = options.start || 0; - - // set header fields - this.setHeader(stat); - - // set content-type - this.type(path); - - // conditional GET support - if (this.isConditionalGET() - && this.isCachable() - && this.isFresh()) { - return this.notModified(); - } - - // adjust len to start/end options - len = Math.max(0, len - offset); - if (options.end !== undefined) { - var bytes = options.end - offset + 1; - if (len > bytes) len = bytes; - } - - // Range support - if (ranges) { - ranges = parseRange(len, ranges); - - // unsatisfiable - if (-1 == ranges) { - res.setHeader('Content-Range', 'bytes */' + stat.size); - return this.error(416); - } - - // valid (syntactically invalid ranges are treated as a regular response) - if (-2 != ranges) { - options.start = offset + ranges[0].start; - options.end = offset + ranges[0].end; - - // Content-Range - res.statusCode = 206; - res.setHeader('Content-Range', 'bytes ' - + ranges[0].start - + '-' - + ranges[0].end - + '/' - + len); - len = options.end - options.start + 1; - } - } - - // content-length - res.setHeader('Content-Length', len); - - // HEAD support - if ('HEAD' == req.method) return res.end(); - - this.stream(path, options); -}; - -/** - * Stream `path` to the response. - * - * @param {String} path - * @param {Object} options - * @api private - */ - -SendStream.prototype.stream = function(path, options){ - // TODO: this is all lame, refactor meeee - var self = this; - var res = this.res; - var req = this.req; - - // pipe - var stream = fs.createReadStream(path, options); - this.emit('stream', stream); - stream.pipe(res); - - // socket closed, done with the fd - req.on('close', stream.destroy.bind(stream)); - - // error handling code-smell - stream.on('error', function(err){ - // no hope in responding - if (res._header) { - console.error(err.stack); - req.destroy(); - return; - } - - // 500 - err.status = 500; - self.emit('error', err); - }); - - // end - stream.on('end', function(){ - self.emit('end'); - }); -}; - -/** - * Set content-type based on `path` - * if it hasn't been explicitly set. - * - * @param {String} path - * @api private - */ - -SendStream.prototype.type = function(path){ - var res = this.res; - if (res.getHeader('Content-Type')) return; - var type = mime.lookup(path); - var charset = mime.charsets.lookup(type); - debug('content-type %s', type); - res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : '')); -}; - -/** - * Set reaponse header fields, most - * fields may be pre-defined. - * - * @param {Object} stat - * @api private - */ - -SendStream.prototype.setHeader = function(stat){ - var res = this.res; - if (!res.getHeader('Accept-Ranges')) res.setHeader('Accept-Ranges', 'bytes'); - if (!res.getHeader('ETag')) res.setHeader('ETag', utils.etag(stat)); - if (!res.getHeader('Date')) res.setHeader('Date', new Date().toUTCString()); - if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (this._maxage / 1000)); - if (!res.getHeader('Last-Modified')) res.setHeader('Last-Modified', stat.mtime.toUTCString()); -}; diff --git a/node_modules/express/node_modules/send/lib/utils.js b/node_modules/express/node_modules/send/lib/utils.js deleted file mode 100644 index 950e5a2c1..000000000 --- a/node_modules/express/node_modules/send/lib/utils.js +++ /dev/null @@ -1,47 +0,0 @@ - -/** - * Return an ETag in the form of `"-"` - * from the given `stat`. - * - * @param {Object} stat - * @return {String} - * @api private - */ - -exports.etag = function(stat) { - return '"' + stat.size + '-' + Number(stat.mtime) + '"'; -}; - -/** - * decodeURIComponent. - * - * Allows V8 to only deoptimize this fn instead of all - * of send(). - * - * @param {String} path - * @api private - */ - -exports.decode = function(path){ - try { - return decodeURIComponent(path); - } catch (err) { - return -1; - } -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; \ No newline at end of file diff --git a/node_modules/express/node_modules/send/node_modules/mime/LICENSE b/node_modules/express/node_modules/send/node_modules/mime/LICENSE deleted file mode 100644 index 451fc4550..000000000 --- a/node_modules/express/node_modules/send/node_modules/mime/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Benjamin Thomas, Robert Kieffer - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express/node_modules/send/node_modules/mime/README.md b/node_modules/express/node_modules/send/node_modules/mime/README.md deleted file mode 100644 index 6ca19bd1e..000000000 --- a/node_modules/express/node_modules/send/node_modules/mime/README.md +++ /dev/null @@ -1,66 +0,0 @@ -# mime - -Comprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community. - -## Install - -Install with [npm](http://github.com/isaacs/npm): - - npm install mime - -## API - Queries - -### mime.lookup(path) -Get the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g. - - var mime = require('mime'); - - mime.lookup('/path/to/file.txt'); // => 'text/plain' - mime.lookup('file.txt'); // => 'text/plain' - mime.lookup('.TXT'); // => 'text/plain' - mime.lookup('htm'); // => 'text/html' - -### mime.default_type -Sets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.) - -### mime.extension(type) -Get the default extension for `type` - - mime.extension('text/html'); // => 'html' - mime.extension('application/octet-stream'); // => 'bin' - -### mime.charsets.lookup() - -Map mime-type to charset - - mime.charsets.lookup('text/plain'); // => 'UTF-8' - -(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.) - -## API - Defining Custom Types - -The following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types). - -### mime.define() - -Add custom mime/extension mappings - - mime.define({ - 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'], - 'application/x-my-type': ['x-mt', 'x-mtt'], - // etc ... - }); - - mime.lookup('x-sft'); // => 'text/x-some-format' - -The first entry in the extensions array is returned by `mime.extension()`. E.g. - - mime.extension('text/x-some-format'); // => 'x-sf' - -### mime.load(filepath) - -Load mappings from an Apache ".types" format file - - mime.load('./my_project.types'); - -The .types file format is simple - See the `types` dir for examples. diff --git a/node_modules/express/node_modules/send/node_modules/mime/mime.js b/node_modules/express/node_modules/send/node_modules/mime/mime.js deleted file mode 100644 index 48be0c5e4..000000000 --- a/node_modules/express/node_modules/send/node_modules/mime/mime.js +++ /dev/null @@ -1,114 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -function Mime() { - // Map of extension -> mime type - this.types = Object.create(null); - - // Map of mime type -> extension - this.extensions = Object.create(null); -} - -/** - * Define mimetype -> extension mappings. Each key is a mime-type that maps - * to an array of extensions associated with the type. The first extension is - * used as the default extension for the type. - * - * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); - * - * @param map (Object) type definitions - */ -Mime.prototype.define = function (map) { - for (var type in map) { - var exts = map[type]; - - for (var i = 0; i < exts.length; i++) { - if (process.env.DEBUG_MIME && this.types[exts]) { - console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' + - this.types[exts] + ' to ' + type); - } - - this.types[exts[i]] = type; - } - - // Default extension is the first one we encounter - if (!this.extensions[type]) { - this.extensions[type] = exts[0]; - } - } -}; - -/** - * Load an Apache2-style ".types" file - * - * This may be called multiple times (it's expected). Where files declare - * overlapping types/extensions, the last file wins. - * - * @param file (String) path of file to load. - */ -Mime.prototype.load = function(file) { - - this._loading = file; - // Read file and split into lines - var map = {}, - content = fs.readFileSync(file, 'ascii'), - lines = content.split(/[\r\n]+/); - - lines.forEach(function(line) { - // Clean up whitespace/comments, and split into fields - var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/); - map[fields.shift()] = fields; - }); - - this.define(map); - - this._loading = null; -}; - -/** - * Lookup a mime type based on extension - */ -Mime.prototype.lookup = function(path, fallback) { - var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase(); - - return this.types[ext] || fallback || this.default_type; -}; - -/** - * Return file extension associated with a mime type - */ -Mime.prototype.extension = function(mimeType) { - var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase(); - return this.extensions[type]; -}; - -// Default instance -var mime = new Mime(); - -// Load local copy of -// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types -mime.load(path.join(__dirname, 'types/mime.types')); - -// Load additional types from node.js community -mime.load(path.join(__dirname, 'types/node.types')); - -// Default type -mime.default_type = mime.lookup('bin'); - -// -// Additional API specific to the default instance -// - -mime.Mime = Mime; - -/** - * Lookup a charset based on mime type. - */ -mime.charsets = { - lookup: function(mimeType, fallback) { - // Assume text types are utf8 - return (/^text\//).test(mimeType) ? 'UTF-8' : fallback; - } -}; - -module.exports = mime; diff --git a/node_modules/express/node_modules/send/node_modules/mime/package.json b/node_modules/express/node_modules/send/node_modules/mime/package.json deleted file mode 100644 index a97593921..000000000 --- a/node_modules/express/node_modules/send/node_modules/mime/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "author": { - "name": "Robert Kieffer", - "email": "robert@broofa.com", - "url": "http://github.com/broofa" - }, - "contributors": [ - { - "name": "Benjamin Thomas", - "email": "benjamin@benjaminthomas.org", - "url": "http://github.com/bentomas" - } - ], - "dependencies": {}, - "description": "A comprehensive library for mime-type mapping", - "devDependencies": {}, - "keywords": [ - "util", - "mime" - ], - "main": "mime.js", - "name": "mime", - "repository": { - "url": "https://github.com/broofa/node-mime", - "type": "git" - }, - "version": "1.2.11", - "readme": "# mime\n\nComprehensive MIME type mapping API. Includes all 600+ types and 800+ extensions defined by the Apache project, plus additional types submitted by the node.js community.\n\n## Install\n\nInstall with [npm](http://github.com/isaacs/npm):\n\n npm install mime\n\n## API - Queries\n\n### mime.lookup(path)\nGet the mime type associated with a file, if no mime type is found `application/octet-stream` is returned. Performs a case-insensitive lookup using the extension in `path` (the substring after the last '/' or '.'). E.g.\n\n var mime = require('mime');\n\n mime.lookup('/path/to/file.txt'); // => 'text/plain'\n mime.lookup('file.txt'); // => 'text/plain'\n mime.lookup('.TXT'); // => 'text/plain'\n mime.lookup('htm'); // => 'text/html'\n\n### mime.default_type\nSets the mime type returned when `mime.lookup` fails to find the extension searched for. (Default is `application/octet-stream`.)\n\n### mime.extension(type)\nGet the default extension for `type`\n\n mime.extension('text/html'); // => 'html'\n mime.extension('application/octet-stream'); // => 'bin'\n\n### mime.charsets.lookup()\n\nMap mime-type to charset\n\n mime.charsets.lookup('text/plain'); // => 'UTF-8'\n\n(The logic for charset lookups is pretty rudimentary. Feel free to suggest improvements.)\n\n## API - Defining Custom Types\n\nThe following APIs allow you to add your own type mappings within your project. If you feel a type should be included as part of node-mime, see [requesting new types](https://github.com/broofa/node-mime/wiki/Requesting-New-Types).\n\n### mime.define()\n\nAdd custom mime/extension mappings\n\n mime.define({\n 'text/x-some-format': ['x-sf', 'x-sft', 'x-sfml'],\n 'application/x-my-type': ['x-mt', 'x-mtt'],\n // etc ...\n });\n\n mime.lookup('x-sft'); // => 'text/x-some-format'\n\nThe first entry in the extensions array is returned by `mime.extension()`. E.g.\n\n mime.extension('text/x-some-format'); // => 'x-sf'\n\n### mime.load(filepath)\n\nLoad mappings from an Apache \".types\" format file\n\n mime.load('./my_project.types');\n\nThe .types file format is simple - See the `types` dir for examples.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/broofa/node-mime/issues" - }, - "homepage": "https://github.com/broofa/node-mime", - "_id": "mime@1.2.11", - "_from": "mime@~1.2.9" -} diff --git a/node_modules/express/node_modules/send/node_modules/mime/test.js b/node_modules/express/node_modules/send/node_modules/mime/test.js deleted file mode 100644 index 2cda1c7ad..000000000 --- a/node_modules/express/node_modules/send/node_modules/mime/test.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * Usage: node test.js - */ - -var mime = require('./mime'); -var assert = require('assert'); -var path = require('path'); - -function eq(a, b) { - console.log('Test: ' + a + ' === ' + b); - assert.strictEqual.apply(null, arguments); -} - -console.log(Object.keys(mime.extensions).length + ' types'); -console.log(Object.keys(mime.types).length + ' extensions\n'); - -// -// Test mime lookups -// - -eq('text/plain', mime.lookup('text.txt')); // normal file -eq('text/plain', mime.lookup('TEXT.TXT')); // uppercase -eq('text/plain', mime.lookup('dir/text.txt')); // dir + file -eq('text/plain', mime.lookup('.text.txt')); // hidden file -eq('text/plain', mime.lookup('.txt')); // nameless -eq('text/plain', mime.lookup('txt')); // extension-only -eq('text/plain', mime.lookup('/txt')); // extension-less () -eq('text/plain', mime.lookup('\\txt')); // Windows, extension-less -eq('application/octet-stream', mime.lookup('text.nope')); // unrecognized -eq('fallback', mime.lookup('text.fallback', 'fallback')); // alternate default - -// -// Test extensions -// - -eq('txt', mime.extension(mime.types.text)); -eq('html', mime.extension(mime.types.htm)); -eq('bin', mime.extension('application/octet-stream')); -eq('bin', mime.extension('application/octet-stream ')); -eq('html', mime.extension(' text/html; charset=UTF-8')); -eq('html', mime.extension('text/html; charset=UTF-8 ')); -eq('html', mime.extension('text/html; charset=UTF-8')); -eq('html', mime.extension('text/html ; charset=UTF-8')); -eq('html', mime.extension('text/html;charset=UTF-8')); -eq('html', mime.extension('text/Html;charset=UTF-8')); -eq(undefined, mime.extension('unrecognized')); - -// -// Test node.types lookups -// - -eq('application/font-woff', mime.lookup('file.woff')); -eq('application/octet-stream', mime.lookup('file.buffer')); -eq('audio/mp4', mime.lookup('file.m4a')); -eq('font/opentype', mime.lookup('file.otf')); - -// -// Test charsets -// - -eq('UTF-8', mime.charsets.lookup('text/plain')); -eq(undefined, mime.charsets.lookup(mime.types.js)); -eq('fallback', mime.charsets.lookup('application/octet-stream', 'fallback')); - -// -// Test for overlaps between mime.types and node.types -// - -var apacheTypes = new mime.Mime(), nodeTypes = new mime.Mime(); -apacheTypes.load(path.join(__dirname, 'types/mime.types')); -nodeTypes.load(path.join(__dirname, 'types/node.types')); - -var keys = [].concat(Object.keys(apacheTypes.types)) - .concat(Object.keys(nodeTypes.types)); -keys.sort(); -for (var i = 1; i < keys.length; i++) { - if (keys[i] == keys[i-1]) { - console.warn('Warning: ' + - 'node.types defines ' + keys[i] + '->' + nodeTypes.types[keys[i]] + - ', mime.types defines ' + keys[i] + '->' + apacheTypes.types[keys[i]]); - } -} - -console.log('\nOK'); diff --git a/node_modules/express/node_modules/send/node_modules/mime/types/mime.types b/node_modules/express/node_modules/send/node_modules/mime/types/mime.types deleted file mode 100644 index da8cd6918..000000000 --- a/node_modules/express/node_modules/send/node_modules/mime/types/mime.types +++ /dev/null @@ -1,1588 +0,0 @@ -# This file maps Internet media types to unique file extension(s). -# Although created for httpd, this file is used by many software systems -# and has been placed in the public domain for unlimited redisribution. -# -# The table below contains both registered and (common) unregistered types. -# A type that has no unique extension can be ignored -- they are listed -# here to guide configurations toward known types and to make it easier to -# identify "new" types. File extensions are also commonly used to indicate -# content languages and encodings, so choose them carefully. -# -# Internet media types should be registered as described in RFC 4288. -# The registry is at . -# -# MIME type (lowercased) Extensions -# ============================================ ========== -# application/1d-interleaved-parityfec -# application/3gpp-ims+xml -# application/activemessage -application/andrew-inset ez -# application/applefile -application/applixware aw -application/atom+xml atom -application/atomcat+xml atomcat -# application/atomicmail -application/atomsvc+xml atomsvc -# application/auth-policy+xml -# application/batch-smtp -# application/beep+xml -# application/calendar+xml -# application/cals-1840 -# application/ccmp+xml -application/ccxml+xml ccxml -application/cdmi-capability cdmia -application/cdmi-container cdmic -application/cdmi-domain cdmid -application/cdmi-object cdmio -application/cdmi-queue cdmiq -# application/cea-2018+xml -# application/cellml+xml -# application/cfw -# application/cnrp+xml -# application/commonground -# application/conference-info+xml -# application/cpl+xml -# application/csta+xml -# application/cstadata+xml -application/cu-seeme cu -# application/cybercash -application/davmount+xml davmount -# application/dca-rft -# application/dec-dx -# application/dialog-info+xml -# application/dicom -# application/dns -application/docbook+xml dbk -# application/dskpp+xml -application/dssc+der dssc -application/dssc+xml xdssc -# application/dvcs -application/ecmascript ecma -# application/edi-consent -# application/edi-x12 -# application/edifact -application/emma+xml emma -# application/epp+xml -application/epub+zip epub -# application/eshop -# application/example -application/exi exi -# application/fastinfoset -# application/fastsoap -# application/fits -application/font-tdpfr pfr -# application/framework-attributes+xml -application/gml+xml gml -application/gpx+xml gpx -application/gxf gxf -# application/h224 -# application/held+xml -# application/http -application/hyperstudio stk -# application/ibe-key-request+xml -# application/ibe-pkg-reply+xml -# application/ibe-pp-data -# application/iges -# application/im-iscomposing+xml -# application/index -# application/index.cmd -# application/index.obj -# application/index.response -# application/index.vnd -application/inkml+xml ink inkml -# application/iotp -application/ipfix ipfix -# application/ipp -# application/isup -application/java-archive jar -application/java-serialized-object ser -application/java-vm class -application/javascript js -application/json json -application/jsonml+json jsonml -# application/kpml-request+xml -# application/kpml-response+xml -application/lost+xml lostxml -application/mac-binhex40 hqx -application/mac-compactpro cpt -# application/macwriteii -application/mads+xml mads -application/marc mrc -application/marcxml+xml mrcx -application/mathematica ma nb mb -# application/mathml-content+xml -# application/mathml-presentation+xml -application/mathml+xml mathml -# application/mbms-associated-procedure-description+xml -# application/mbms-deregister+xml -# application/mbms-envelope+xml -# application/mbms-msk+xml -# application/mbms-msk-response+xml -# application/mbms-protection-description+xml -# application/mbms-reception-report+xml -# application/mbms-register+xml -# application/mbms-register-response+xml -# application/mbms-user-service-description+xml -application/mbox mbox -# application/media_control+xml -application/mediaservercontrol+xml mscml -application/metalink+xml metalink -application/metalink4+xml meta4 -application/mets+xml mets -# application/mikey -application/mods+xml mods -# application/moss-keys -# application/moss-signature -# application/mosskey-data -# application/mosskey-request -application/mp21 m21 mp21 -application/mp4 mp4s -# application/mpeg4-generic -# application/mpeg4-iod -# application/mpeg4-iod-xmt -# application/msc-ivr+xml -# application/msc-mixer+xml -application/msword doc dot -application/mxf mxf -# application/nasdata -# application/news-checkgroups -# application/news-groupinfo -# application/news-transmission -# application/nss -# application/ocsp-request -# application/ocsp-response -application/octet-stream bin dms lrf mar so dist distz pkg bpk dump elc deploy -application/oda oda -application/oebps-package+xml opf -application/ogg ogx -application/omdoc+xml omdoc -application/onenote onetoc onetoc2 onetmp onepkg -application/oxps oxps -# application/parityfec -application/patch-ops-error+xml xer -application/pdf pdf -application/pgp-encrypted pgp -# application/pgp-keys -application/pgp-signature asc sig -application/pics-rules prf -# application/pidf+xml -# application/pidf-diff+xml -application/pkcs10 p10 -application/pkcs7-mime p7m p7c -application/pkcs7-signature p7s -application/pkcs8 p8 -application/pkix-attr-cert ac -application/pkix-cert cer -application/pkix-crl crl -application/pkix-pkipath pkipath -application/pkixcmp pki -application/pls+xml pls -# application/poc-settings+xml -application/postscript ai eps ps -# application/prs.alvestrand.titrax-sheet -application/prs.cww cww -# application/prs.nprend -# application/prs.plucker -# application/prs.rdf-xml-crypt -# application/prs.xsf+xml -application/pskc+xml pskcxml -# application/qsig -application/rdf+xml rdf -application/reginfo+xml rif -application/relax-ng-compact-syntax rnc -# application/remote-printing -application/resource-lists+xml rl -application/resource-lists-diff+xml rld -# application/riscos -# application/rlmi+xml -application/rls-services+xml rs -application/rpki-ghostbusters gbr -application/rpki-manifest mft -application/rpki-roa roa -# application/rpki-updown -application/rsd+xml rsd -application/rss+xml rss -application/rtf rtf -# application/rtx -# application/samlassertion+xml -# application/samlmetadata+xml -application/sbml+xml sbml -application/scvp-cv-request scq -application/scvp-cv-response scs -application/scvp-vp-request spq -application/scvp-vp-response spp -application/sdp sdp -# application/set-payment -application/set-payment-initiation setpay -# application/set-registration -application/set-registration-initiation setreg -# application/sgml -# application/sgml-open-catalog -application/shf+xml shf -# application/sieve -# application/simple-filter+xml -# application/simple-message-summary -# application/simplesymbolcontainer -# application/slate -# application/smil -application/smil+xml smi smil -# application/soap+fastinfoset -# application/soap+xml -application/sparql-query rq -application/sparql-results+xml srx -# application/spirits-event+xml -application/srgs gram -application/srgs+xml grxml -application/sru+xml sru -application/ssdl+xml ssdl -application/ssml+xml ssml -# application/tamp-apex-update -# application/tamp-apex-update-confirm -# application/tamp-community-update -# application/tamp-community-update-confirm -# application/tamp-error -# application/tamp-sequence-adjust -# application/tamp-sequence-adjust-confirm -# application/tamp-status-query -# application/tamp-status-response -# application/tamp-update -# application/tamp-update-confirm -application/tei+xml tei teicorpus -application/thraud+xml tfi -# application/timestamp-query -# application/timestamp-reply -application/timestamped-data tsd -# application/tve-trigger -# application/ulpfec -# application/vcard+xml -# application/vemmi -# application/vividence.scriptfile -# application/vnd.3gpp.bsf+xml -application/vnd.3gpp.pic-bw-large plb -application/vnd.3gpp.pic-bw-small psb -application/vnd.3gpp.pic-bw-var pvb -# application/vnd.3gpp.sms -# application/vnd.3gpp2.bcmcsinfo+xml -# application/vnd.3gpp2.sms -application/vnd.3gpp2.tcap tcap -application/vnd.3m.post-it-notes pwn -application/vnd.accpac.simply.aso aso -application/vnd.accpac.simply.imp imp -application/vnd.acucobol acu -application/vnd.acucorp atc acutc -application/vnd.adobe.air-application-installer-package+zip air -application/vnd.adobe.formscentral.fcdt fcdt -application/vnd.adobe.fxp fxp fxpl -# application/vnd.adobe.partial-upload -application/vnd.adobe.xdp+xml xdp -application/vnd.adobe.xfdf xfdf -# application/vnd.aether.imp -# application/vnd.ah-barcode -application/vnd.ahead.space ahead -application/vnd.airzip.filesecure.azf azf -application/vnd.airzip.filesecure.azs azs -application/vnd.amazon.ebook azw -application/vnd.americandynamics.acc acc -application/vnd.amiga.ami ami -# application/vnd.amundsen.maze+xml -application/vnd.android.package-archive apk -application/vnd.anser-web-certificate-issue-initiation cii -application/vnd.anser-web-funds-transfer-initiation fti -application/vnd.antix.game-component atx -application/vnd.apple.installer+xml mpkg -application/vnd.apple.mpegurl m3u8 -# application/vnd.arastra.swi -application/vnd.aristanetworks.swi swi -application/vnd.astraea-software.iota iota -application/vnd.audiograph aep -# application/vnd.autopackage -# application/vnd.avistar+xml -application/vnd.blueice.multipass mpm -# application/vnd.bluetooth.ep.oob -application/vnd.bmi bmi -application/vnd.businessobjects rep -# application/vnd.cab-jscript -# application/vnd.canon-cpdl -# application/vnd.canon-lips -# application/vnd.cendio.thinlinc.clientconf -application/vnd.chemdraw+xml cdxml -application/vnd.chipnuts.karaoke-mmd mmd -application/vnd.cinderella cdy -# application/vnd.cirpack.isdn-ext -application/vnd.claymore cla -application/vnd.cloanto.rp9 rp9 -application/vnd.clonk.c4group c4g c4d c4f c4p c4u -application/vnd.cluetrust.cartomobile-config c11amc -application/vnd.cluetrust.cartomobile-config-pkg c11amz -# application/vnd.collection+json -# application/vnd.commerce-battelle -application/vnd.commonspace csp -application/vnd.contact.cmsg cdbcmsg -application/vnd.cosmocaller cmc -application/vnd.crick.clicker clkx -application/vnd.crick.clicker.keyboard clkk -application/vnd.crick.clicker.palette clkp -application/vnd.crick.clicker.template clkt -application/vnd.crick.clicker.wordbank clkw -application/vnd.criticaltools.wbs+xml wbs -application/vnd.ctc-posml pml -# application/vnd.ctct.ws+xml -# application/vnd.cups-pdf -# application/vnd.cups-postscript -application/vnd.cups-ppd ppd -# application/vnd.cups-raster -# application/vnd.cups-raw -# application/vnd.curl -application/vnd.curl.car car -application/vnd.curl.pcurl pcurl -# application/vnd.cybank -application/vnd.dart dart -application/vnd.data-vision.rdz rdz -application/vnd.dece.data uvf uvvf uvd uvvd -application/vnd.dece.ttml+xml uvt uvvt -application/vnd.dece.unspecified uvx uvvx -application/vnd.dece.zip uvz uvvz -application/vnd.denovo.fcselayout-link fe_launch -# application/vnd.dir-bi.plate-dl-nosuffix -application/vnd.dna dna -application/vnd.dolby.mlp mlp -# application/vnd.dolby.mobile.1 -# application/vnd.dolby.mobile.2 -application/vnd.dpgraph dpg -application/vnd.dreamfactory dfac -application/vnd.ds-keypoint kpxx -application/vnd.dvb.ait ait -# application/vnd.dvb.dvbj -# application/vnd.dvb.esgcontainer -# application/vnd.dvb.ipdcdftnotifaccess -# application/vnd.dvb.ipdcesgaccess -# application/vnd.dvb.ipdcesgaccess2 -# application/vnd.dvb.ipdcesgpdd -# application/vnd.dvb.ipdcroaming -# application/vnd.dvb.iptv.alfec-base -# application/vnd.dvb.iptv.alfec-enhancement -# application/vnd.dvb.notif-aggregate-root+xml -# application/vnd.dvb.notif-container+xml -# application/vnd.dvb.notif-generic+xml -# application/vnd.dvb.notif-ia-msglist+xml -# application/vnd.dvb.notif-ia-registration-request+xml -# application/vnd.dvb.notif-ia-registration-response+xml -# application/vnd.dvb.notif-init+xml -# application/vnd.dvb.pfr -application/vnd.dvb.service svc -# application/vnd.dxr -application/vnd.dynageo geo -# application/vnd.easykaraoke.cdgdownload -# application/vnd.ecdis-update -application/vnd.ecowin.chart mag -# application/vnd.ecowin.filerequest -# application/vnd.ecowin.fileupdate -# application/vnd.ecowin.series -# application/vnd.ecowin.seriesrequest -# application/vnd.ecowin.seriesupdate -# application/vnd.emclient.accessrequest+xml -application/vnd.enliven nml -# application/vnd.eprints.data+xml -application/vnd.epson.esf esf -application/vnd.epson.msf msf -application/vnd.epson.quickanime qam -application/vnd.epson.salt slt -application/vnd.epson.ssf ssf -# application/vnd.ericsson.quickcall -application/vnd.eszigno3+xml es3 et3 -# application/vnd.etsi.aoc+xml -# application/vnd.etsi.cug+xml -# application/vnd.etsi.iptvcommand+xml -# application/vnd.etsi.iptvdiscovery+xml -# application/vnd.etsi.iptvprofile+xml -# application/vnd.etsi.iptvsad-bc+xml -# application/vnd.etsi.iptvsad-cod+xml -# application/vnd.etsi.iptvsad-npvr+xml -# application/vnd.etsi.iptvservice+xml -# application/vnd.etsi.iptvsync+xml -# application/vnd.etsi.iptvueprofile+xml -# application/vnd.etsi.mcid+xml -# application/vnd.etsi.overload-control-policy-dataset+xml -# application/vnd.etsi.sci+xml -# application/vnd.etsi.simservs+xml -# application/vnd.etsi.tsl+xml -# application/vnd.etsi.tsl.der -# application/vnd.eudora.data -application/vnd.ezpix-album ez2 -application/vnd.ezpix-package ez3 -# application/vnd.f-secure.mobile -application/vnd.fdf fdf -application/vnd.fdsn.mseed mseed -application/vnd.fdsn.seed seed dataless -# application/vnd.ffsns -# application/vnd.fints -application/vnd.flographit gph -application/vnd.fluxtime.clip ftc -# application/vnd.font-fontforge-sfd -application/vnd.framemaker fm frame maker book -application/vnd.frogans.fnc fnc -application/vnd.frogans.ltf ltf -application/vnd.fsc.weblaunch fsc -application/vnd.fujitsu.oasys oas -application/vnd.fujitsu.oasys2 oa2 -application/vnd.fujitsu.oasys3 oa3 -application/vnd.fujitsu.oasysgp fg5 -application/vnd.fujitsu.oasysprs bh2 -# application/vnd.fujixerox.art-ex -# application/vnd.fujixerox.art4 -# application/vnd.fujixerox.hbpl -application/vnd.fujixerox.ddd ddd -application/vnd.fujixerox.docuworks xdw -application/vnd.fujixerox.docuworks.binder xbd -# application/vnd.fut-misnet -application/vnd.fuzzysheet fzs -application/vnd.genomatix.tuxedo txd -# application/vnd.geocube+xml -application/vnd.geogebra.file ggb -application/vnd.geogebra.tool ggt -application/vnd.geometry-explorer gex gre -application/vnd.geonext gxt -application/vnd.geoplan g2w -application/vnd.geospace g3w -# application/vnd.globalplatform.card-content-mgt -# application/vnd.globalplatform.card-content-mgt-response -application/vnd.gmx gmx -application/vnd.google-earth.kml+xml kml -application/vnd.google-earth.kmz kmz -application/vnd.grafeq gqf gqs -# application/vnd.gridmp -application/vnd.groove-account gac -application/vnd.groove-help ghf -application/vnd.groove-identity-message gim -application/vnd.groove-injector grv -application/vnd.groove-tool-message gtm -application/vnd.groove-tool-template tpl -application/vnd.groove-vcard vcg -# application/vnd.hal+json -application/vnd.hal+xml hal -application/vnd.handheld-entertainment+xml zmm -application/vnd.hbci hbci -# application/vnd.hcl-bireports -application/vnd.hhe.lesson-player les -application/vnd.hp-hpgl hpgl -application/vnd.hp-hpid hpid -application/vnd.hp-hps hps -application/vnd.hp-jlyt jlt -application/vnd.hp-pcl pcl -application/vnd.hp-pclxl pclxl -# application/vnd.httphone -application/vnd.hydrostatix.sof-data sfd-hdstx -# application/vnd.hzn-3d-crossword -# application/vnd.ibm.afplinedata -# application/vnd.ibm.electronic-media -application/vnd.ibm.minipay mpy -application/vnd.ibm.modcap afp listafp list3820 -application/vnd.ibm.rights-management irm -application/vnd.ibm.secure-container sc -application/vnd.iccprofile icc icm -application/vnd.igloader igl -application/vnd.immervision-ivp ivp -application/vnd.immervision-ivu ivu -# application/vnd.informedcontrol.rms+xml -# application/vnd.informix-visionary -# application/vnd.infotech.project -# application/vnd.infotech.project+xml -# application/vnd.innopath.wamp.notification -application/vnd.insors.igm igm -application/vnd.intercon.formnet xpw xpx -application/vnd.intergeo i2g -# application/vnd.intertrust.digibox -# application/vnd.intertrust.nncp -application/vnd.intu.qbo qbo -application/vnd.intu.qfx qfx -# application/vnd.iptc.g2.conceptitem+xml -# application/vnd.iptc.g2.knowledgeitem+xml -# application/vnd.iptc.g2.newsitem+xml -# application/vnd.iptc.g2.newsmessage+xml -# application/vnd.iptc.g2.packageitem+xml -# application/vnd.iptc.g2.planningitem+xml -application/vnd.ipunplugged.rcprofile rcprofile -application/vnd.irepository.package+xml irp -application/vnd.is-xpr xpr -application/vnd.isac.fcs fcs -application/vnd.jam jam -# application/vnd.japannet-directory-service -# application/vnd.japannet-jpnstore-wakeup -# application/vnd.japannet-payment-wakeup -# application/vnd.japannet-registration -# application/vnd.japannet-registration-wakeup -# application/vnd.japannet-setstore-wakeup -# application/vnd.japannet-verification -# application/vnd.japannet-verification-wakeup -application/vnd.jcp.javame.midlet-rms rms -application/vnd.jisp jisp -application/vnd.joost.joda-archive joda -application/vnd.kahootz ktz ktr -application/vnd.kde.karbon karbon -application/vnd.kde.kchart chrt -application/vnd.kde.kformula kfo -application/vnd.kde.kivio flw -application/vnd.kde.kontour kon -application/vnd.kde.kpresenter kpr kpt -application/vnd.kde.kspread ksp -application/vnd.kde.kword kwd kwt -application/vnd.kenameaapp htke -application/vnd.kidspiration kia -application/vnd.kinar kne knp -application/vnd.koan skp skd skt skm -application/vnd.kodak-descriptor sse -application/vnd.las.las+xml lasxml -# application/vnd.liberty-request+xml -application/vnd.llamagraphics.life-balance.desktop lbd -application/vnd.llamagraphics.life-balance.exchange+xml lbe -application/vnd.lotus-1-2-3 123 -application/vnd.lotus-approach apr -application/vnd.lotus-freelance pre -application/vnd.lotus-notes nsf -application/vnd.lotus-organizer org -application/vnd.lotus-screencam scm -application/vnd.lotus-wordpro lwp -application/vnd.macports.portpkg portpkg -# application/vnd.marlin.drm.actiontoken+xml -# application/vnd.marlin.drm.conftoken+xml -# application/vnd.marlin.drm.license+xml -# application/vnd.marlin.drm.mdcf -application/vnd.mcd mcd -application/vnd.medcalcdata mc1 -application/vnd.mediastation.cdkey cdkey -# application/vnd.meridian-slingshot -application/vnd.mfer mwf -application/vnd.mfmp mfm -application/vnd.micrografx.flo flo -application/vnd.micrografx.igx igx -application/vnd.mif mif -# application/vnd.minisoft-hp3000-save -# application/vnd.mitsubishi.misty-guard.trustweb -application/vnd.mobius.daf daf -application/vnd.mobius.dis dis -application/vnd.mobius.mbk mbk -application/vnd.mobius.mqy mqy -application/vnd.mobius.msl msl -application/vnd.mobius.plc plc -application/vnd.mobius.txf txf -application/vnd.mophun.application mpn -application/vnd.mophun.certificate mpc -# application/vnd.motorola.flexsuite -# application/vnd.motorola.flexsuite.adsi -# application/vnd.motorola.flexsuite.fis -# application/vnd.motorola.flexsuite.gotap -# application/vnd.motorola.flexsuite.kmr -# application/vnd.motorola.flexsuite.ttc -# application/vnd.motorola.flexsuite.wem -# application/vnd.motorola.iprm -application/vnd.mozilla.xul+xml xul -application/vnd.ms-artgalry cil -# application/vnd.ms-asf -application/vnd.ms-cab-compressed cab -# application/vnd.ms-color.iccprofile -application/vnd.ms-excel xls xlm xla xlc xlt xlw -application/vnd.ms-excel.addin.macroenabled.12 xlam -application/vnd.ms-excel.sheet.binary.macroenabled.12 xlsb -application/vnd.ms-excel.sheet.macroenabled.12 xlsm -application/vnd.ms-excel.template.macroenabled.12 xltm -application/vnd.ms-fontobject eot -application/vnd.ms-htmlhelp chm -application/vnd.ms-ims ims -application/vnd.ms-lrm lrm -# application/vnd.ms-office.activex+xml -application/vnd.ms-officetheme thmx -# application/vnd.ms-opentype -# application/vnd.ms-package.obfuscated-opentype -application/vnd.ms-pki.seccat cat -application/vnd.ms-pki.stl stl -# application/vnd.ms-playready.initiator+xml -application/vnd.ms-powerpoint ppt pps pot -application/vnd.ms-powerpoint.addin.macroenabled.12 ppam -application/vnd.ms-powerpoint.presentation.macroenabled.12 pptm -application/vnd.ms-powerpoint.slide.macroenabled.12 sldm -application/vnd.ms-powerpoint.slideshow.macroenabled.12 ppsm -application/vnd.ms-powerpoint.template.macroenabled.12 potm -# application/vnd.ms-printing.printticket+xml -application/vnd.ms-project mpp mpt -# application/vnd.ms-tnef -# application/vnd.ms-wmdrm.lic-chlg-req -# application/vnd.ms-wmdrm.lic-resp -# application/vnd.ms-wmdrm.meter-chlg-req -# application/vnd.ms-wmdrm.meter-resp -application/vnd.ms-word.document.macroenabled.12 docm -application/vnd.ms-word.template.macroenabled.12 dotm -application/vnd.ms-works wps wks wcm wdb -application/vnd.ms-wpl wpl -application/vnd.ms-xpsdocument xps -application/vnd.mseq mseq -# application/vnd.msign -# application/vnd.multiad.creator -# application/vnd.multiad.creator.cif -# application/vnd.music-niff -application/vnd.musician mus -application/vnd.muvee.style msty -application/vnd.mynfc taglet -# application/vnd.ncd.control -# application/vnd.ncd.reference -# application/vnd.nervana -# application/vnd.netfpx -application/vnd.neurolanguage.nlu nlu -application/vnd.nitf ntf nitf -application/vnd.noblenet-directory nnd -application/vnd.noblenet-sealer nns -application/vnd.noblenet-web nnw -# application/vnd.nokia.catalogs -# application/vnd.nokia.conml+wbxml -# application/vnd.nokia.conml+xml -# application/vnd.nokia.isds-radio-presets -# application/vnd.nokia.iptv.config+xml -# application/vnd.nokia.landmark+wbxml -# application/vnd.nokia.landmark+xml -# application/vnd.nokia.landmarkcollection+xml -# application/vnd.nokia.n-gage.ac+xml -application/vnd.nokia.n-gage.data ngdat -application/vnd.nokia.n-gage.symbian.install n-gage -# application/vnd.nokia.ncd -# application/vnd.nokia.pcd+wbxml -# application/vnd.nokia.pcd+xml -application/vnd.nokia.radio-preset rpst -application/vnd.nokia.radio-presets rpss -application/vnd.novadigm.edm edm -application/vnd.novadigm.edx edx -application/vnd.novadigm.ext ext -# application/vnd.ntt-local.file-transfer -# application/vnd.ntt-local.sip-ta_remote -# application/vnd.ntt-local.sip-ta_tcp_stream -application/vnd.oasis.opendocument.chart odc -application/vnd.oasis.opendocument.chart-template otc -application/vnd.oasis.opendocument.database odb -application/vnd.oasis.opendocument.formula odf -application/vnd.oasis.opendocument.formula-template odft -application/vnd.oasis.opendocument.graphics odg -application/vnd.oasis.opendocument.graphics-template otg -application/vnd.oasis.opendocument.image odi -application/vnd.oasis.opendocument.image-template oti -application/vnd.oasis.opendocument.presentation odp -application/vnd.oasis.opendocument.presentation-template otp -application/vnd.oasis.opendocument.spreadsheet ods -application/vnd.oasis.opendocument.spreadsheet-template ots -application/vnd.oasis.opendocument.text odt -application/vnd.oasis.opendocument.text-master odm -application/vnd.oasis.opendocument.text-template ott -application/vnd.oasis.opendocument.text-web oth -# application/vnd.obn -# application/vnd.oftn.l10n+json -# application/vnd.oipf.contentaccessdownload+xml -# application/vnd.oipf.contentaccessstreaming+xml -# application/vnd.oipf.cspg-hexbinary -# application/vnd.oipf.dae.svg+xml -# application/vnd.oipf.dae.xhtml+xml -# application/vnd.oipf.mippvcontrolmessage+xml -# application/vnd.oipf.pae.gem -# application/vnd.oipf.spdiscovery+xml -# application/vnd.oipf.spdlist+xml -# application/vnd.oipf.ueprofile+xml -# application/vnd.oipf.userprofile+xml -application/vnd.olpc-sugar xo -# application/vnd.oma-scws-config -# application/vnd.oma-scws-http-request -# application/vnd.oma-scws-http-response -# application/vnd.oma.bcast.associated-procedure-parameter+xml -# application/vnd.oma.bcast.drm-trigger+xml -# application/vnd.oma.bcast.imd+xml -# application/vnd.oma.bcast.ltkm -# application/vnd.oma.bcast.notification+xml -# application/vnd.oma.bcast.provisioningtrigger -# application/vnd.oma.bcast.sgboot -# application/vnd.oma.bcast.sgdd+xml -# application/vnd.oma.bcast.sgdu -# application/vnd.oma.bcast.simple-symbol-container -# application/vnd.oma.bcast.smartcard-trigger+xml -# application/vnd.oma.bcast.sprov+xml -# application/vnd.oma.bcast.stkm -# application/vnd.oma.cab-address-book+xml -# application/vnd.oma.cab-feature-handler+xml -# application/vnd.oma.cab-pcc+xml -# application/vnd.oma.cab-user-prefs+xml -# application/vnd.oma.dcd -# application/vnd.oma.dcdc -application/vnd.oma.dd2+xml dd2 -# application/vnd.oma.drm.risd+xml -# application/vnd.oma.group-usage-list+xml -# application/vnd.oma.pal+xml -# application/vnd.oma.poc.detailed-progress-report+xml -# application/vnd.oma.poc.final-report+xml -# application/vnd.oma.poc.groups+xml -# application/vnd.oma.poc.invocation-descriptor+xml -# application/vnd.oma.poc.optimized-progress-report+xml -# application/vnd.oma.push -# application/vnd.oma.scidm.messages+xml -# application/vnd.oma.xcap-directory+xml -# application/vnd.omads-email+xml -# application/vnd.omads-file+xml -# application/vnd.omads-folder+xml -# application/vnd.omaloc-supl-init -application/vnd.openofficeorg.extension oxt -# application/vnd.openxmlformats-officedocument.custom-properties+xml -# application/vnd.openxmlformats-officedocument.customxmlproperties+xml -# application/vnd.openxmlformats-officedocument.drawing+xml -# application/vnd.openxmlformats-officedocument.drawingml.chart+xml -# application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml -# application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml -# application/vnd.openxmlformats-officedocument.extended-properties+xml -# application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml -# application/vnd.openxmlformats-officedocument.presentationml.comments+xml -# application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml -# application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml -application/vnd.openxmlformats-officedocument.presentationml.presentation pptx -# application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.presprops+xml -application/vnd.openxmlformats-officedocument.presentationml.slide sldx -# application/vnd.openxmlformats-officedocument.presentationml.slide+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml -# application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml -application/vnd.openxmlformats-officedocument.presentationml.slideshow ppsx -# application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml -# application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml -# application/vnd.openxmlformats-officedocument.presentationml.tags+xml -application/vnd.openxmlformats-officedocument.presentationml.template potx -# application/vnd.openxmlformats-officedocument.presentationml.template.main+xml -# application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.sheet xlsx -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml -application/vnd.openxmlformats-officedocument.spreadsheetml.template xltx -# application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml -# application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml -# application/vnd.openxmlformats-officedocument.theme+xml -# application/vnd.openxmlformats-officedocument.themeoverride+xml -# application/vnd.openxmlformats-officedocument.vmldrawing -# application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.document docx -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml -application/vnd.openxmlformats-officedocument.wordprocessingml.template dotx -# application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml -# application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml -# application/vnd.openxmlformats-package.core-properties+xml -# application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml -# application/vnd.openxmlformats-package.relationships+xml -# application/vnd.quobject-quoxdocument -# application/vnd.osa.netdeploy -application/vnd.osgeo.mapguide.package mgp -# application/vnd.osgi.bundle -application/vnd.osgi.dp dp -application/vnd.osgi.subsystem esa -# application/vnd.otps.ct-kip+xml -application/vnd.palm pdb pqa oprc -# application/vnd.paos.xml -application/vnd.pawaafile paw -application/vnd.pg.format str -application/vnd.pg.osasli ei6 -# application/vnd.piaccess.application-licence -application/vnd.picsel efif -application/vnd.pmi.widget wg -# application/vnd.poc.group-advertisement+xml -application/vnd.pocketlearn plf -application/vnd.powerbuilder6 pbd -# application/vnd.powerbuilder6-s -# application/vnd.powerbuilder7 -# application/vnd.powerbuilder7-s -# application/vnd.powerbuilder75 -# application/vnd.powerbuilder75-s -# application/vnd.preminet -application/vnd.previewsystems.box box -application/vnd.proteus.magazine mgz -application/vnd.publishare-delta-tree qps -application/vnd.pvi.ptid1 ptid -# application/vnd.pwg-multiplexed -# application/vnd.pwg-xhtml-print+xml -# application/vnd.qualcomm.brew-app-res -application/vnd.quark.quarkxpress qxd qxt qwd qwt qxl qxb -# application/vnd.radisys.moml+xml -# application/vnd.radisys.msml+xml -# application/vnd.radisys.msml-audit+xml -# application/vnd.radisys.msml-audit-conf+xml -# application/vnd.radisys.msml-audit-conn+xml -# application/vnd.radisys.msml-audit-dialog+xml -# application/vnd.radisys.msml-audit-stream+xml -# application/vnd.radisys.msml-conf+xml -# application/vnd.radisys.msml-dialog+xml -# application/vnd.radisys.msml-dialog-base+xml -# application/vnd.radisys.msml-dialog-fax-detect+xml -# application/vnd.radisys.msml-dialog-fax-sendrecv+xml -# application/vnd.radisys.msml-dialog-group+xml -# application/vnd.radisys.msml-dialog-speech+xml -# application/vnd.radisys.msml-dialog-transform+xml -# application/vnd.rainstor.data -# application/vnd.rapid -application/vnd.realvnc.bed bed -application/vnd.recordare.musicxml mxl -application/vnd.recordare.musicxml+xml musicxml -# application/vnd.renlearn.rlprint -application/vnd.rig.cryptonote cryptonote -application/vnd.rim.cod cod -application/vnd.rn-realmedia rm -application/vnd.rn-realmedia-vbr rmvb -application/vnd.route66.link66+xml link66 -# application/vnd.rs-274x -# application/vnd.ruckus.download -# application/vnd.s3sms -application/vnd.sailingtracker.track st -# application/vnd.sbm.cid -# application/vnd.sbm.mid2 -# application/vnd.scribus -# application/vnd.sealed.3df -# application/vnd.sealed.csf -# application/vnd.sealed.doc -# application/vnd.sealed.eml -# application/vnd.sealed.mht -# application/vnd.sealed.net -# application/vnd.sealed.ppt -# application/vnd.sealed.tiff -# application/vnd.sealed.xls -# application/vnd.sealedmedia.softseal.html -# application/vnd.sealedmedia.softseal.pdf -application/vnd.seemail see -application/vnd.sema sema -application/vnd.semd semd -application/vnd.semf semf -application/vnd.shana.informed.formdata ifm -application/vnd.shana.informed.formtemplate itp -application/vnd.shana.informed.interchange iif -application/vnd.shana.informed.package ipk -application/vnd.simtech-mindmapper twd twds -application/vnd.smaf mmf -# application/vnd.smart.notebook -application/vnd.smart.teacher teacher -# application/vnd.software602.filler.form+xml -# application/vnd.software602.filler.form-xml-zip -application/vnd.solent.sdkm+xml sdkm sdkd -application/vnd.spotfire.dxp dxp -application/vnd.spotfire.sfs sfs -# application/vnd.sss-cod -# application/vnd.sss-dtf -# application/vnd.sss-ntf -application/vnd.stardivision.calc sdc -application/vnd.stardivision.draw sda -application/vnd.stardivision.impress sdd -application/vnd.stardivision.math smf -application/vnd.stardivision.writer sdw vor -application/vnd.stardivision.writer-global sgl -application/vnd.stepmania.package smzip -application/vnd.stepmania.stepchart sm -# application/vnd.street-stream -application/vnd.sun.xml.calc sxc -application/vnd.sun.xml.calc.template stc -application/vnd.sun.xml.draw sxd -application/vnd.sun.xml.draw.template std -application/vnd.sun.xml.impress sxi -application/vnd.sun.xml.impress.template sti -application/vnd.sun.xml.math sxm -application/vnd.sun.xml.writer sxw -application/vnd.sun.xml.writer.global sxg -application/vnd.sun.xml.writer.template stw -# application/vnd.sun.wadl+xml -application/vnd.sus-calendar sus susp -application/vnd.svd svd -# application/vnd.swiftview-ics -application/vnd.symbian.install sis sisx -application/vnd.syncml+xml xsm -application/vnd.syncml.dm+wbxml bdm -application/vnd.syncml.dm+xml xdm -# application/vnd.syncml.dm.notification -# application/vnd.syncml.ds.notification -application/vnd.tao.intent-module-archive tao -application/vnd.tcpdump.pcap pcap cap dmp -application/vnd.tmobile-livetv tmo -application/vnd.trid.tpt tpt -application/vnd.triscape.mxs mxs -application/vnd.trueapp tra -# application/vnd.truedoc -# application/vnd.ubisoft.webplayer -application/vnd.ufdl ufd ufdl -application/vnd.uiq.theme utz -application/vnd.umajin umj -application/vnd.unity unityweb -application/vnd.uoml+xml uoml -# application/vnd.uplanet.alert -# application/vnd.uplanet.alert-wbxml -# application/vnd.uplanet.bearer-choice -# application/vnd.uplanet.bearer-choice-wbxml -# application/vnd.uplanet.cacheop -# application/vnd.uplanet.cacheop-wbxml -# application/vnd.uplanet.channel -# application/vnd.uplanet.channel-wbxml -# application/vnd.uplanet.list -# application/vnd.uplanet.list-wbxml -# application/vnd.uplanet.listcmd -# application/vnd.uplanet.listcmd-wbxml -# application/vnd.uplanet.signal -application/vnd.vcx vcx -# application/vnd.vd-study -# application/vnd.vectorworks -# application/vnd.verimatrix.vcas -# application/vnd.vidsoft.vidconference -application/vnd.visio vsd vst vss vsw -application/vnd.visionary vis -# application/vnd.vividence.scriptfile -application/vnd.vsf vsf -# application/vnd.wap.sic -# application/vnd.wap.slc -application/vnd.wap.wbxml wbxml -application/vnd.wap.wmlc wmlc -application/vnd.wap.wmlscriptc wmlsc -application/vnd.webturbo wtb -# application/vnd.wfa.wsc -# application/vnd.wmc -# application/vnd.wmf.bootstrap -# application/vnd.wolfram.mathematica -# application/vnd.wolfram.mathematica.package -application/vnd.wolfram.player nbp -application/vnd.wordperfect wpd -application/vnd.wqd wqd -# application/vnd.wrq-hp3000-labelled -application/vnd.wt.stf stf -# application/vnd.wv.csp+wbxml -# application/vnd.wv.csp+xml -# application/vnd.wv.ssp+xml -application/vnd.xara xar -application/vnd.xfdl xfdl -# application/vnd.xfdl.webform -# application/vnd.xmi+xml -# application/vnd.xmpie.cpkg -# application/vnd.xmpie.dpkg -# application/vnd.xmpie.plan -# application/vnd.xmpie.ppkg -# application/vnd.xmpie.xlim -application/vnd.yamaha.hv-dic hvd -application/vnd.yamaha.hv-script hvs -application/vnd.yamaha.hv-voice hvp -application/vnd.yamaha.openscoreformat osf -application/vnd.yamaha.openscoreformat.osfpvg+xml osfpvg -# application/vnd.yamaha.remote-setup -application/vnd.yamaha.smaf-audio saf -application/vnd.yamaha.smaf-phrase spf -# application/vnd.yamaha.through-ngn -# application/vnd.yamaha.tunnel-udpencap -application/vnd.yellowriver-custom-menu cmp -application/vnd.zul zir zirz -application/vnd.zzazz.deck+xml zaz -application/voicexml+xml vxml -# application/vq-rtcpxr -# application/watcherinfo+xml -# application/whoispp-query -# application/whoispp-response -application/widget wgt -application/winhlp hlp -# application/wita -# application/wordperfect5.1 -application/wsdl+xml wsdl -application/wspolicy+xml wspolicy -application/x-7z-compressed 7z -application/x-abiword abw -application/x-ace-compressed ace -# application/x-amf -application/x-apple-diskimage dmg -application/x-authorware-bin aab x32 u32 vox -application/x-authorware-map aam -application/x-authorware-seg aas -application/x-bcpio bcpio -application/x-bittorrent torrent -application/x-blorb blb blorb -application/x-bzip bz -application/x-bzip2 bz2 boz -application/x-cbr cbr cba cbt cbz cb7 -application/x-cdlink vcd -application/x-cfs-compressed cfs -application/x-chat chat -application/x-chess-pgn pgn -application/x-conference nsc -# application/x-compress -application/x-cpio cpio -application/x-csh csh -application/x-debian-package deb udeb -application/x-dgc-compressed dgc -application/x-director dir dcr dxr cst cct cxt w3d fgd swa -application/x-doom wad -application/x-dtbncx+xml ncx -application/x-dtbook+xml dtb -application/x-dtbresource+xml res -application/x-dvi dvi -application/x-envoy evy -application/x-eva eva -application/x-font-bdf bdf -# application/x-font-dos -# application/x-font-framemaker -application/x-font-ghostscript gsf -# application/x-font-libgrx -application/x-font-linux-psf psf -application/x-font-otf otf -application/x-font-pcf pcf -application/x-font-snf snf -# application/x-font-speedo -# application/x-font-sunos-news -application/x-font-ttf ttf ttc -application/x-font-type1 pfa pfb pfm afm -application/font-woff woff -# application/x-font-vfont -application/x-freearc arc -application/x-futuresplash spl -application/x-gca-compressed gca -application/x-glulx ulx -application/x-gnumeric gnumeric -application/x-gramps-xml gramps -application/x-gtar gtar -# application/x-gzip -application/x-hdf hdf -application/x-install-instructions install -application/x-iso9660-image iso -application/x-java-jnlp-file jnlp -application/x-latex latex -application/x-lzh-compressed lzh lha -application/x-mie mie -application/x-mobipocket-ebook prc mobi -application/x-ms-application application -application/x-ms-shortcut lnk -application/x-ms-wmd wmd -application/x-ms-wmz wmz -application/x-ms-xbap xbap -application/x-msaccess mdb -application/x-msbinder obd -application/x-mscardfile crd -application/x-msclip clp -application/x-msdownload exe dll com bat msi -application/x-msmediaview mvb m13 m14 -application/x-msmetafile wmf wmz emf emz -application/x-msmoney mny -application/x-mspublisher pub -application/x-msschedule scd -application/x-msterminal trm -application/x-mswrite wri -application/x-netcdf nc cdf -application/x-nzb nzb -application/x-pkcs12 p12 pfx -application/x-pkcs7-certificates p7b spc -application/x-pkcs7-certreqresp p7r -application/x-rar-compressed rar -application/x-research-info-systems ris -application/x-sh sh -application/x-shar shar -application/x-shockwave-flash swf -application/x-silverlight-app xap -application/x-sql sql -application/x-stuffit sit -application/x-stuffitx sitx -application/x-subrip srt -application/x-sv4cpio sv4cpio -application/x-sv4crc sv4crc -application/x-t3vm-image t3 -application/x-tads gam -application/x-tar tar -application/x-tcl tcl -application/x-tex tex -application/x-tex-tfm tfm -application/x-texinfo texinfo texi -application/x-tgif obj -application/x-ustar ustar -application/x-wais-source src -application/x-x509-ca-cert der crt -application/x-xfig fig -application/x-xliff+xml xlf -application/x-xpinstall xpi -application/x-xz xz -application/x-zmachine z1 z2 z3 z4 z5 z6 z7 z8 -# application/x400-bp -application/xaml+xml xaml -# application/xcap-att+xml -# application/xcap-caps+xml -application/xcap-diff+xml xdf -# application/xcap-el+xml -# application/xcap-error+xml -# application/xcap-ns+xml -# application/xcon-conference-info-diff+xml -# application/xcon-conference-info+xml -application/xenc+xml xenc -application/xhtml+xml xhtml xht -# application/xhtml-voice+xml -application/xml xml xsl -application/xml-dtd dtd -# application/xml-external-parsed-entity -# application/xmpp+xml -application/xop+xml xop -application/xproc+xml xpl -application/xslt+xml xslt -application/xspf+xml xspf -application/xv+xml mxml xhvml xvml xvm -application/yang yang -application/yin+xml yin -application/zip zip -# audio/1d-interleaved-parityfec -# audio/32kadpcm -# audio/3gpp -# audio/3gpp2 -# audio/ac3 -audio/adpcm adp -# audio/amr -# audio/amr-wb -# audio/amr-wb+ -# audio/asc -# audio/atrac-advanced-lossless -# audio/atrac-x -# audio/atrac3 -audio/basic au snd -# audio/bv16 -# audio/bv32 -# audio/clearmode -# audio/cn -# audio/dat12 -# audio/dls -# audio/dsr-es201108 -# audio/dsr-es202050 -# audio/dsr-es202211 -# audio/dsr-es202212 -# audio/dv -# audio/dvi4 -# audio/eac3 -# audio/evrc -# audio/evrc-qcp -# audio/evrc0 -# audio/evrc1 -# audio/evrcb -# audio/evrcb0 -# audio/evrcb1 -# audio/evrcwb -# audio/evrcwb0 -# audio/evrcwb1 -# audio/example -# audio/fwdred -# audio/g719 -# audio/g722 -# audio/g7221 -# audio/g723 -# audio/g726-16 -# audio/g726-24 -# audio/g726-32 -# audio/g726-40 -# audio/g728 -# audio/g729 -# audio/g7291 -# audio/g729d -# audio/g729e -# audio/gsm -# audio/gsm-efr -# audio/gsm-hr-08 -# audio/ilbc -# audio/ip-mr_v2.5 -# audio/isac -# audio/l16 -# audio/l20 -# audio/l24 -# audio/l8 -# audio/lpc -audio/midi mid midi kar rmi -# audio/mobile-xmf -audio/mp4 mp4a -# audio/mp4a-latm -# audio/mpa -# audio/mpa-robust -audio/mpeg mpga mp2 mp2a mp3 m2a m3a -# audio/mpeg4-generic -# audio/musepack -audio/ogg oga ogg spx -# audio/opus -# audio/parityfec -# audio/pcma -# audio/pcma-wb -# audio/pcmu-wb -# audio/pcmu -# audio/prs.sid -# audio/qcelp -# audio/red -# audio/rtp-enc-aescm128 -# audio/rtp-midi -# audio/rtx -audio/s3m s3m -audio/silk sil -# audio/smv -# audio/smv0 -# audio/smv-qcp -# audio/sp-midi -# audio/speex -# audio/t140c -# audio/t38 -# audio/telephone-event -# audio/tone -# audio/uemclip -# audio/ulpfec -# audio/vdvi -# audio/vmr-wb -# audio/vnd.3gpp.iufp -# audio/vnd.4sb -# audio/vnd.audiokoz -# audio/vnd.celp -# audio/vnd.cisco.nse -# audio/vnd.cmles.radio-events -# audio/vnd.cns.anp1 -# audio/vnd.cns.inf1 -audio/vnd.dece.audio uva uvva -audio/vnd.digital-winds eol -# audio/vnd.dlna.adts -# audio/vnd.dolby.heaac.1 -# audio/vnd.dolby.heaac.2 -# audio/vnd.dolby.mlp -# audio/vnd.dolby.mps -# audio/vnd.dolby.pl2 -# audio/vnd.dolby.pl2x -# audio/vnd.dolby.pl2z -# audio/vnd.dolby.pulse.1 -audio/vnd.dra dra -audio/vnd.dts dts -audio/vnd.dts.hd dtshd -# audio/vnd.dvb.file -# audio/vnd.everad.plj -# audio/vnd.hns.audio -audio/vnd.lucent.voice lvp -audio/vnd.ms-playready.media.pya pya -# audio/vnd.nokia.mobile-xmf -# audio/vnd.nortel.vbk -audio/vnd.nuera.ecelp4800 ecelp4800 -audio/vnd.nuera.ecelp7470 ecelp7470 -audio/vnd.nuera.ecelp9600 ecelp9600 -# audio/vnd.octel.sbc -# audio/vnd.qcelp -# audio/vnd.rhetorex.32kadpcm -audio/vnd.rip rip -# audio/vnd.sealedmedia.softseal.mpeg -# audio/vnd.vmx.cvsd -# audio/vorbis -# audio/vorbis-config -audio/webm weba -audio/x-aac aac -audio/x-aiff aif aiff aifc -audio/x-caf caf -audio/x-flac flac -audio/x-matroska mka -audio/x-mpegurl m3u -audio/x-ms-wax wax -audio/x-ms-wma wma -audio/x-pn-realaudio ram ra -audio/x-pn-realaudio-plugin rmp -# audio/x-tta -audio/x-wav wav -audio/xm xm -chemical/x-cdx cdx -chemical/x-cif cif -chemical/x-cmdf cmdf -chemical/x-cml cml -chemical/x-csml csml -# chemical/x-pdb -chemical/x-xyz xyz -image/bmp bmp -image/cgm cgm -# image/example -# image/fits -image/g3fax g3 -image/gif gif -image/ief ief -# image/jp2 -image/jpeg jpeg jpg jpe -# image/jpm -# image/jpx -image/ktx ktx -# image/naplps -image/png png -image/prs.btif btif -# image/prs.pti -image/sgi sgi -image/svg+xml svg svgz -# image/t38 -image/tiff tiff tif -# image/tiff-fx -image/vnd.adobe.photoshop psd -# image/vnd.cns.inf2 -image/vnd.dece.graphic uvi uvvi uvg uvvg -image/vnd.dvb.subtitle sub -image/vnd.djvu djvu djv -image/vnd.dwg dwg -image/vnd.dxf dxf -image/vnd.fastbidsheet fbs -image/vnd.fpx fpx -image/vnd.fst fst -image/vnd.fujixerox.edmics-mmr mmr -image/vnd.fujixerox.edmics-rlc rlc -# image/vnd.globalgraphics.pgb -# image/vnd.microsoft.icon -# image/vnd.mix -image/vnd.ms-modi mdi -image/vnd.ms-photo wdp -image/vnd.net-fpx npx -# image/vnd.radiance -# image/vnd.sealed.png -# image/vnd.sealedmedia.softseal.gif -# image/vnd.sealedmedia.softseal.jpg -# image/vnd.svf -image/vnd.wap.wbmp wbmp -image/vnd.xiff xif -image/webp webp -image/x-3ds 3ds -image/x-cmu-raster ras -image/x-cmx cmx -image/x-freehand fh fhc fh4 fh5 fh7 -image/x-icon ico -image/x-mrsid-image sid -image/x-pcx pcx -image/x-pict pic pct -image/x-portable-anymap pnm -image/x-portable-bitmap pbm -image/x-portable-graymap pgm -image/x-portable-pixmap ppm -image/x-rgb rgb -image/x-tga tga -image/x-xbitmap xbm -image/x-xpixmap xpm -image/x-xwindowdump xwd -# message/cpim -# message/delivery-status -# message/disposition-notification -# message/example -# message/external-body -# message/feedback-report -# message/global -# message/global-delivery-status -# message/global-disposition-notification -# message/global-headers -# message/http -# message/imdn+xml -# message/news -# message/partial -message/rfc822 eml mime -# message/s-http -# message/sip -# message/sipfrag -# message/tracking-status -# message/vnd.si.simp -# model/example -model/iges igs iges -model/mesh msh mesh silo -model/vnd.collada+xml dae -model/vnd.dwf dwf -# model/vnd.flatland.3dml -model/vnd.gdl gdl -# model/vnd.gs-gdl -# model/vnd.gs.gdl -model/vnd.gtw gtw -# model/vnd.moml+xml -model/vnd.mts mts -# model/vnd.parasolid.transmit.binary -# model/vnd.parasolid.transmit.text -model/vnd.vtu vtu -model/vrml wrl vrml -model/x3d+binary x3db x3dbz -model/x3d+vrml x3dv x3dvz -model/x3d+xml x3d x3dz -# multipart/alternative -# multipart/appledouble -# multipart/byteranges -# multipart/digest -# multipart/encrypted -# multipart/example -# multipart/form-data -# multipart/header-set -# multipart/mixed -# multipart/parallel -# multipart/related -# multipart/report -# multipart/signed -# multipart/voice-message -# text/1d-interleaved-parityfec -text/cache-manifest appcache -text/calendar ics ifb -text/css css -text/csv csv -# text/directory -# text/dns -# text/ecmascript -# text/enriched -# text/example -# text/fwdred -text/html html htm -# text/javascript -text/n3 n3 -# text/parityfec -text/plain txt text conf def list log in -# text/prs.fallenstein.rst -text/prs.lines.tag dsc -# text/vnd.radisys.msml-basic-layout -# text/red -# text/rfc822-headers -text/richtext rtx -# text/rtf -# text/rtp-enc-aescm128 -# text/rtx -text/sgml sgml sgm -# text/t140 -text/tab-separated-values tsv -text/troff t tr roff man me ms -text/turtle ttl -# text/ulpfec -text/uri-list uri uris urls -text/vcard vcard -# text/vnd.abc -text/vnd.curl curl -text/vnd.curl.dcurl dcurl -text/vnd.curl.scurl scurl -text/vnd.curl.mcurl mcurl -# text/vnd.dmclientscript -text/vnd.dvb.subtitle sub -# text/vnd.esmertec.theme-descriptor -text/vnd.fly fly -text/vnd.fmi.flexstor flx -text/vnd.graphviz gv -text/vnd.in3d.3dml 3dml -text/vnd.in3d.spot spot -# text/vnd.iptc.newsml -# text/vnd.iptc.nitf -# text/vnd.latex-z -# text/vnd.motorola.reflex -# text/vnd.ms-mediapackage -# text/vnd.net2phone.commcenter.command -# text/vnd.si.uricatalogue -text/vnd.sun.j2me.app-descriptor jad -# text/vnd.trolltech.linguist -# text/vnd.wap.si -# text/vnd.wap.sl -text/vnd.wap.wml wml -text/vnd.wap.wmlscript wmls -text/x-asm s asm -text/x-c c cc cxx cpp h hh dic -text/x-fortran f for f77 f90 -text/x-java-source java -text/x-opml opml -text/x-pascal p pas -text/x-nfo nfo -text/x-setext etx -text/x-sfv sfv -text/x-uuencode uu -text/x-vcalendar vcs -text/x-vcard vcf -# text/xml -# text/xml-external-parsed-entity -# video/1d-interleaved-parityfec -video/3gpp 3gp -# video/3gpp-tt -video/3gpp2 3g2 -# video/bmpeg -# video/bt656 -# video/celb -# video/dv -# video/example -video/h261 h261 -video/h263 h263 -# video/h263-1998 -# video/h263-2000 -video/h264 h264 -# video/h264-rcdo -# video/h264-svc -video/jpeg jpgv -# video/jpeg2000 -video/jpm jpm jpgm -video/mj2 mj2 mjp2 -# video/mp1s -# video/mp2p -# video/mp2t -video/mp4 mp4 mp4v mpg4 -# video/mp4v-es -video/mpeg mpeg mpg mpe m1v m2v -# video/mpeg4-generic -# video/mpv -# video/nv -video/ogg ogv -# video/parityfec -# video/pointer -video/quicktime qt mov -# video/raw -# video/rtp-enc-aescm128 -# video/rtx -# video/smpte292m -# video/ulpfec -# video/vc1 -# video/vnd.cctv -video/vnd.dece.hd uvh uvvh -video/vnd.dece.mobile uvm uvvm -# video/vnd.dece.mp4 -video/vnd.dece.pd uvp uvvp -video/vnd.dece.sd uvs uvvs -video/vnd.dece.video uvv uvvv -# video/vnd.directv.mpeg -# video/vnd.directv.mpeg-tts -# video/vnd.dlna.mpeg-tts -video/vnd.dvb.file dvb -video/vnd.fvt fvt -# video/vnd.hns.video -# video/vnd.iptvforum.1dparityfec-1010 -# video/vnd.iptvforum.1dparityfec-2005 -# video/vnd.iptvforum.2dparityfec-1010 -# video/vnd.iptvforum.2dparityfec-2005 -# video/vnd.iptvforum.ttsavc -# video/vnd.iptvforum.ttsmpeg2 -# video/vnd.motorola.video -# video/vnd.motorola.videop -video/vnd.mpegurl mxu m4u -video/vnd.ms-playready.media.pyv pyv -# video/vnd.nokia.interleaved-multimedia -# video/vnd.nokia.videovoip -# video/vnd.objectvideo -# video/vnd.sealed.mpeg1 -# video/vnd.sealed.mpeg4 -# video/vnd.sealed.swf -# video/vnd.sealedmedia.softseal.mov -video/vnd.uvvu.mp4 uvu uvvu -video/vnd.vivo viv -video/webm webm -video/x-f4v f4v -video/x-fli fli -video/x-flv flv -video/x-m4v m4v -video/x-matroska mkv mk3d mks -video/x-mng mng -video/x-ms-asf asf asx -video/x-ms-vob vob -video/x-ms-wm wm -video/x-ms-wmv wmv -video/x-ms-wmx wmx -video/x-ms-wvx wvx -video/x-msvideo avi -video/x-sgi-movie movie -video/x-smv smv -x-conference/x-cooltalk ice diff --git a/node_modules/express/node_modules/send/node_modules/mime/types/node.types b/node_modules/express/node_modules/send/node_modules/mime/types/node.types deleted file mode 100644 index 55b2cf794..000000000 --- a/node_modules/express/node_modules/send/node_modules/mime/types/node.types +++ /dev/null @@ -1,77 +0,0 @@ -# What: WebVTT -# Why: To allow formats intended for marking up external text track resources. -# http://dev.w3.org/html5/webvtt/ -# Added by: niftylettuce -text/vtt vtt - -# What: Google Chrome Extension -# Why: To allow apps to (work) be served with the right content type header. -# http://codereview.chromium.org/2830017 -# Added by: niftylettuce -application/x-chrome-extension crx - -# What: HTC support -# Why: To properly render .htc files such as CSS3PIE -# Added by: niftylettuce -text/x-component htc - -# What: HTML5 application cache manifes ('.manifest' extension) -# Why: De-facto standard. Required by Mozilla browser when serving HTML5 apps -# per https://developer.mozilla.org/en/offline_resources_in_firefox -# Added by: louisremi -text/cache-manifest manifest - -# What: node binary buffer format -# Why: semi-standard extension w/in the node community -# Added by: tootallnate -application/octet-stream buffer - -# What: The "protected" MP-4 formats used by iTunes. -# Why: Required for streaming music to browsers (?) -# Added by: broofa -application/mp4 m4p -audio/mp4 m4a - -# What: Video format, Part of RFC1890 -# Why: See https://github.com/bentomas/node-mime/pull/6 -# Added by: mjrusso -video/MP2T ts - -# What: EventSource mime type -# Why: mime type of Server-Sent Events stream -# http://www.w3.org/TR/eventsource/#text-event-stream -# Added by: francois2metz -text/event-stream event-stream - -# What: Mozilla App manifest mime type -# Why: https://developer.mozilla.org/en/Apps/Manifest#Serving_manifests -# Added by: ednapiranha -application/x-web-app-manifest+json webapp - -# What: Lua file types -# Why: Googling around shows de-facto consensus on these -# Added by: creationix (Issue #45) -text/x-lua lua -application/x-lua-bytecode luac - -# What: Markdown files, as per http://daringfireball.net/projects/markdown/syntax -# Why: http://stackoverflow.com/questions/10701983/what-is-the-mime-type-for-markdown -# Added by: avoidwork -text/x-markdown markdown md mkd - -# What: ini files -# Why: because they're just text files -# Added by: Matthew Kastor -text/plain ini - -# What: DASH Adaptive Streaming manifest -# Why: https://developer.mozilla.org/en-US/docs/DASH_Adaptive_Streaming_for_HTML_5_Video -# Added by: eelcocramer -application/dash+xml mdp - -# What: OpenType font files - http://www.microsoft.com/typography/otspec/ -# Why: Browsers usually ignore the font MIME types and sniff the content, -# but Chrome, shows a warning if OpenType fonts aren't served with -# the `font/opentype` MIME type: http://i.imgur.com/8c5RN8M.png. -# Added by: alrra -font/opentype otf diff --git a/node_modules/express/node_modules/send/package.json b/node_modules/express/node_modules/send/package.json deleted file mode 100644 index 4d7780473..000000000 --- a/node_modules/express/node_modules/send/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "send", - "version": "0.1.4", - "description": "Better streaming static file server with Range and conditional-GET support", - "keywords": [ - "static", - "file", - "server" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": { - "debug": "*", - "mime": "~1.2.9", - "fresh": "0.2.0", - "range-parser": "0.0.4" - }, - "devDependencies": { - "mocha": "*", - "should": "*", - "supertest": "0.0.1", - "connect": "2.x" - }, - "scripts": { - "test": "make test" - }, - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/send.git" - }, - "main": "index", - "readme": "# send\n\n Send is Connect's `static()` extracted for generalized use, a streaming static file\n server supporting partial responses (Ranges), conditional-GET negotiation, high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework.\n\n## Installation\n\n $ npm install send\n\n## Examples\n\n Small:\n\n```js\nvar http = require('http');\nvar send = require('send');\n\nvar app = http.createServer(function(req, res){\n send(req, req.url).pipe(res);\n}).listen(3000);\n```\n\n Serving from a root directory with custom error-handling:\n\n```js\nvar http = require('http');\nvar send = require('send');\nvar url = require('url');\n\nvar app = http.createServer(function(req, res){\n // your custom error-handling logic:\n function error(err) {\n res.statusCode = err.status || 500;\n res.end(err.message);\n }\n\n // your custom directory handling logic:\n function redirect() {\n res.statusCode = 301;\n res.setHeader('Location', req.url + '/');\n res.end('Redirecting to ' + req.url + '/');\n }\n\n // transfer arbitrary files from within\n // /www/example.com/public/*\n send(req, url.parse(req.url).pathname)\n .root('/www/example.com/public')\n .on('error', error)\n .on('directory', redirect)\n .pipe(res);\n}).listen(3000);\n```\n\n## API\n\n### Events\n\n - `error` an error occurred `(err)`\n - `directory` a directory was requested\n - `file` a file was requested `(path, stat)`\n - `stream` file streaming has started `(stream)`\n - `end` streaming has completed\n\n### .root(dir)\n\n Serve files relative to `path`. Aliased as `.from(dir)`.\n\n### .index(path)\n\n By default send supports \"index.html\" files, to disable this\n invoke `.index(false)` or to supply a new index pass a string.\n\n### .maxage(ms)\n\n Provide a max-age in milliseconds for http caching, defaults to 0.\n\n### .hidden(bool)\n\n Enable or disable transfer of hidden files, defaults to false.\n\n## Error-handling\n\n By default when no `error` listeners are present an automatic response will be made, otherwise you have full control over the response, aka you may show a 5xx page etc.\n\n## Caching\n\n It does _not_ perform internal caching, you should use a reverse proxy cache such\n as Varnish for this, or those fancy things called CDNs. If your application is small enough that it would benefit from single-node memory caching, it's small enough that it does not need caching at all ;).\n\n## Debugging\n\n To enable `debug()` instrumentation output export __DEBUG__:\n\n```\n$ DEBUG=send node app\n```\n\n## Running tests\n\n```\n$ npm install\n$ make test\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/send/issues" - }, - "homepage": "https://github.com/visionmedia/send", - "_id": "send@0.1.4", - "dist": { - "shasum": "a35fd61a4d0cf79096f3ec58358fce38023f2dd8" - }, - "_from": "send@0.1.4", - "_resolved": "https://registry.npmjs.org/send/-/send-0.1.4.tgz" -} diff --git a/node_modules/express/package.json b/node_modules/express/package.json deleted file mode 100644 index c845653fa..000000000 --- a/node_modules/express/package.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "name": "express", - "description": "Sinatra inspired web development framework", - "version": "3.4.8", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "contributors": [ - { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - { - "name": "Ciaran Jessup", - "email": "ciaranj@gmail.com" - }, - { - "name": "Guillermo Rauch", - "email": "rauchg@gmail.com" - } - ], - "dependencies": { - "connect": "2.12.0", - "commander": "1.3.2", - "range-parser": "0.0.4", - "mkdirp": "0.3.5", - "cookie": "0.1.0", - "buffer-crc32": "0.2.1", - "fresh": "0.2.0", - "methods": "0.1.0", - "send": "0.1.4", - "cookie-signature": "1.0.1", - "merge-descriptors": "0.0.1", - "debug": ">= 0.7.3 < 1" - }, - "devDependencies": { - "ejs": "~0.8.4", - "mocha": "~1.15.1", - "jade": "~0.30.0", - "hjs": "~0.0.6", - "stylus": "~0.40.0", - "should": "~2.1.1", - "connect-redis": "~1.4.5", - "marked": "0.2.10", - "supertest": "~0.8.1" - }, - "keywords": [ - "express", - "framework", - "sinatra", - "web", - "rest", - "restful", - "router", - "app", - "api" - ], - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/express" - }, - "main": "index", - "bin": { - "express": "./bin/express" - }, - "scripts": { - "prepublish": "npm prune", - "test": "make test" - }, - "engines": { - "node": ">= 0.8.0" - }, - "license": "MIT", - "readme": "[![express logo](http://f.cl.ly/items/0V2S1n0K1i3y1c122g04/Screen%20Shot%202012-04-11%20at%209.59.42%20AM.png)](http://expressjs.com/)\n\n Fast, unopinionated, minimalist web framework for [node](http://nodejs.org).\n\n [![Build Status](https://secure.travis-ci.org/visionmedia/express.png)](http://travis-ci.org/visionmedia/express) [![Gittip](http://img.shields.io/gittip/visionmedia.png)](https://www.gittip.com/visionmedia/)\n\n```js\nvar express = require('express');\nvar app = express();\n\napp.get('/', function(req, res){\n res.send('Hello World');\n});\n\napp.listen(3000);\n```\n\n## Installation\n\n $ npm install -g express\n\n## Quick Start\n\n The quickest way to get started with express is to utilize the executable `express(1)` to generate an application as shown below:\n\n Create the app:\n\n $ npm install -g express\n $ express /tmp/foo && cd /tmp/foo\n\n Install dependencies:\n\n $ npm install\n\n Start the server:\n\n $ node app\n\n## Features\n\n * Built on [Connect](http://github.com/senchalabs/connect)\n * Robust routing\n * HTTP helpers (redirection, caching, etc)\n * View system supporting 14+ template engines\n * Content negotiation\n * Focus on high performance\n * Environment based configuration\n * Executable for generating applications quickly\n * High test coverage\n\n## Philosophy\n\n The Express philosophy is to provide small, robust tooling for HTTP servers, making\n it a great solution for single page applications, web sites, hybrids, or public\n HTTP APIs.\n\n Built on Connect, you can use _only_ what you need, and nothing more. Applications\n can be as big or as small as you like, even a single file. Express does\n not force you to use any specific ORM or template engine. With support for over\n 14 template engines via [Consolidate.js](http://github.com/visionmedia/consolidate.js),\n you can quickly craft your perfect framework.\n\n## More Information\n\n * [Website and Documentation](http://expressjs.com/) stored at [visionmedia/expressjs.com](https://github.com/visionmedia/expressjs.com)\n * Join #express on freenode\n * [Google Group](http://groups.google.com/group/express-js) for discussion\n * Follow [tjholowaychuk](http://twitter.com/tjholowaychuk) on twitter for updates\n * Visit the [Wiki](http://github.com/visionmedia/express/wiki)\n * [Русскоязычная документация](http://jsman.ru/express/)\n * Run express examples [online](https://runnable.com/express)\n\n## Viewing Examples\n\nClone the Express repo, then install the dev dependencies to install all the example / test suite dependencies:\n\n $ git clone git://github.com/visionmedia/express.git --depth 1\n $ cd express\n $ npm install\n\nThen run whichever tests you want:\n\n $ node examples/content-negotiation\n\nYou can also view live examples here:\n\n\n\n## Running Tests\n\nTo run the test suite, first invoke the following command within the repo, installing the development dependencies:\n\n $ npm install\n\nThen run the tests:\n\n $ make test\n\n## Contributors\n\n https://github.com/visionmedia/express/graphs/contributors\n\n## License\n\n(The MIT License)\n\nCopyright (c) 2009-2012 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/express/issues" - }, - "homepage": "https://github.com/visionmedia/express", - "_id": "express@3.4.8", - "_from": "express@3.x" -} diff --git a/node_modules/express3-handlebars/.npmignore b/node_modules/express3-handlebars/.npmignore deleted file mode 100644 index 1ca957177..000000000 --- a/node_modules/express3-handlebars/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log diff --git a/node_modules/express3-handlebars/HISTORY.md b/node_modules/express3-handlebars/HISTORY.md deleted file mode 100644 index dffabcceb..000000000 --- a/node_modules/express3-handlebars/HISTORY.md +++ /dev/null @@ -1,149 +0,0 @@ -Express3 Handlebars Change History -================================== - -0.5.0 (2013-07-25) ------------------- - -* Added `loadTemplates()` method which will load all the templates in a - specified directory. - -* Added support for multiple partials directories. This enables the - `partialsDir` configuration property to be specified as an *array* of - directories, and loads all of the templates in each one. - - This feature allows an app's partials to be split up in multiple directories, - which is common if an app has some shared partials which will also be exposed - to the client, and some server-side-only partials. - -* Added runnable code examples in this package's "examples/" directory. - -* Improved optional argument handling in public methods to treat Express - `locals` function objects as `options` and not `callback` params to the method - being invoked. - - -0.4.1 (2013-04-06) ------------------- - -* Updated `async` dependency to the latest stable minor version: "~0.2". - - -0.4.0 (2013-03-24) ------------------- - -* (!) Removed the following "get" -> "load" aliases which kept in v0.2.0 for - back-compat: - - * `getPartials()` -> `loadPartials()` - * `getTemplate()` -> `loadTemplate()` - - This is the future version where these aliases have been removed. - -* (!) Renamed `lib/express3-handlebars.js` -> `lib/express-handlebars.js`. - -* Exposed `getHandlebarsSemver()` function as a static property on the - `ExpressHandlebars` constructor. - -* Rearranged module exports by moving the engine factory function to `index.js`, - making the `lib/express3-handlebars.js` module only responsible for exporting - the `ExpressHandlebars` constructor. - - -0.3.3 (2013-03-22) ------------------- - -* Updated internal `_resolveLayoutPath()` method to take the full - `options`/locals objects which the view is rendered with. This makes it easier - to override. (Issue #14) - - -0.3.2 (2013-02-20) ------------------- - -* Transfered ownership and copyright to Yahoo! Inc. This software is still free - to use, and is now licensed under the Yahoo! Inc. BSD license. - - -0.3.1 (2013-02-18) ------------------- - -* Updated README with info about `options.helpers` for `render()` and - `renderView()` docs. - - -0.3.0 (2013-02-18) ------------------- - -* Added support for render-level helpers, via `options.helpers`, to the - `render()` and `renderView()` methods. Handlebars' `registerHelper()` function - now works as expected and does not have to be called before the - `ExpressHandlebars` instance is created. Helpers are now merged from: - `handlebars.helpers` (global), `helpers` (instance), and `options.helpers` - (render-level) before a template is rendered; this provides flexibility at - all levels. - -* Added `handlebarsVersion` property which is the version number of `handlebars` - as a semver. This is used internally to branch on certain operations which - differ between Handlebars releases. - - -0.2.3 (2013-02-13) ------------------- - -* Fixed issue with naming nested partials when using the latest version of - Handlebars (1.0.rc.2). Previous versions require a hack to replace "/"s with - "."s in partial names, and the latest version of Handlebars fixes that bug. - This hack will only be applied to old versions of Handlebars. (Issue #9) - - -0.2.2 (2013-02-04) ------------------- - -* Updated README with the public method renames which happened v0.2.0. - - -0.2.1 (2013-02-04) ------------------- - -* `extname`, `layoutsDir`, and `partialsDir` property values will now reference - the values on the prototype unless an `ExpressHandlebars` instance is - constructed with config values for these properties. - -* Improved clarity of method implementations, and exposed more override "hooks" - via new private methods: `_getPartialName()`, `_renderTemplate()`, and - `_resolveLayoutPath()`. - - -0.2.0 (2013-02-01) ------------------- - -* (!) Renamed methods prefixed with "get" to "load" for clarity: - - * `getPartials()` -> `loadPartials()` - * `getTemplate()` -> `loadTemplate()` - - Aliases for these methods have been created to maintain back-compat, but the - old method names are now deprecated will be removed in the future. (Issue #5) - -* All paths are resolved before checking in or adding to caches. (Issue #1) - -* Force `{precompiled: false}` option within `render()` and `renderView()` - methods to prevent trying to render with precompiled templates. (Issue #2) - - -0.1.2 (2013-01-10) ------------------- - -* Tweaked formatting of README documentation. - - -0.1.1 (2013-01-10) ------------------- - -* Added README documentation. - - -0.1.0 (2013-01-07) ------------------- - -* Initial release. diff --git a/node_modules/express3-handlebars/LICENSE b/node_modules/express3-handlebars/LICENSE deleted file mode 100644 index 6fd95450c..000000000 --- a/node_modules/express3-handlebars/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright 2013 Yahoo! Inc. -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - - * Neither the name of the Yahoo! Inc. nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/express3-handlebars/README.md b/node_modules/express3-handlebars/README.md deleted file mode 100644 index 357896e71..000000000 --- a/node_modules/express3-handlebars/README.md +++ /dev/null @@ -1,612 +0,0 @@ -Express3 Handlebars -=================== - -A [Handlebars][] view engine for [Express][] which doesn't suck. - -[![Dependency Status](https://david-dm.org/ericf/express3-handlebars.png)][status] - - -[Express]: https://github.com/visionmedia/express -[Handlebars]: https://github.com/wycats/handlebars.js -[status]: https://david-dm.org/ericf/express3-handlebars - - -Goals & Design --------------- - -I created this project out of frustration with the existing Handlebars view -engines for Express. As of version 3.x, Express got out of the business of being -a generic view engine — this was a great decision — leaving developers to -implement the concepts of layouts, partials, and doing file I/O for their -template engines of choice. - -### Goals and Features - -After building a half-dozen Express apps, I developed requirements and opinions -about what a Handlebars view engine should provide and how it should be -implemented. The following is that list: - -* Add back the concept of "layout", which was removed in Express 3.x. - -* Add back the concept of "partials" via Handlebars' partials mechanism. - -* Support a directory of partials; e.g., `{{> foo/bar}}` which exists on the - file system at `views/partials/foo/bar.handlebars` by default. - -* Smart file system I/O and template caching. When in development, templates are - always loaded from disk. In production, raw files and compiled templates are - cached, including partials. - -* All async and non-blocking. File system I/O is slow and servers should not be - blocked from handling requests while reading from disk. I/O queuing is used to - avoid doing unnecessary work. - -* Ability to expose precompiled templates and partials to the client, enabling - template sharing and reuse. - -* Ability to use a different Handlebars module/implementation other than the - Handlebars npm package. - -### Package Design - -This package was designed to work great for both the simple and complex use -cases. I _intentionally_ made sure the full implementation is exposed and is -easily overrideable. - -The package exports a function which can be invoked with no arguments or with a -`config` object and it will return a function (closed over sane defaults) which -can be registered with an Express app. It's an engine factory function. - -This exported engine factory has two properties which expose the underlying -implementation: - -* `ExpressHandlebars()`: The constructor function which holds the internal - implementation on its `prototype`. This produces instance objects which store - their configuration, `compiled` and `precompiled` templates, and expose an - `engine()` function which can be registered with an Express app. - -* `create()`: A convenience factory function for creating `ExpressHandlebars` - instances. - -An instance-based approach is used so that multiple `ExpressHandlebars` -instances can be created with their own configuration, templates, partials, and -helpers. - - -Installation ------------- - -Install using npm: - -```shell -$ npm install express3-handlebars -``` - - -Usage ------ - -This view engine uses sane defaults that leverage the "Express-way" of -structuring an app's views. This makes it trivial to use in basic apps: - -### Basic Usage - -**Directory Structure:** - -``` -. -├── app.js -└── views - ├── home.handlebars - └── layouts - └── main.handlebars - -2 directories, 3 files -``` - -**app.js:** - -Creates a super simple Express app which shows the basic way to register a -Handlebars view engine using this package. - -```javascript -var express = require('express'), - exphbs = require('express3-handlebars'), - - app = express(); - -app.engine('handlebars', exphbs({defaultLayout: 'main'})); -app.set('view engine', 'handlebars'); - -app.get('/', function (req, res) { - res.render('home'); -}); - -app.listen(3000); -``` - -**views/layouts/main.handlebars:** - -The main layout is the HTML page wrapper which can be reused for the different -views of the app. `{{{body}}}` is used as a placeholder for where the main -content should be rendered. - -```html - - - - - Example App - - - - {{{body}}} - - - -``` - -**views/home.handlebars:** - -The content for the app's home view which will be rendered into the layout's -`{{{body}}}`. - -```html -

    Example App: Home

    -``` - -#### Running the Example - -The above example is bundled in this package's [examples directory][], where -it can be run by: - -```shell -$ cd examples/basic/ && node app -``` - -### Using Instances - -Another way to use this view engine is to create an instance(s) of -`ExpressHandlebars`, allowing access to the full API: - -```javascript -var express = require('express'), - exphbs = require('express3-handlebars'), - - app = express(), - hbs = exphbs.create({ /* config */ }); - -// Register `hbs.engine` with the Express app. -app.engine('handlebars', hbs.engine); -app.set('view engine', 'handlebars'); - -// ...still have a reference to `hbs`, on which methods like `loadPartials()` -// can be called. -``` - -**Note:** The [Advanced Usage][] example demonstrates how `ExpressHandlebars` -instances can be leveraged. - -### Template Caching - -This view engine uses a smart template caching strategy. In development, -templates will always be loaded from disk, i.e., no caching. In production, raw -files and compiled Handlebars templates are aggressively cached. - -The easiest way to control template/view caching is through Express' -[view cache setting][]: - -```javascript -app.enable('view cache'); -``` - -Express enables this setting by default when in production mode, i.e., -`process.env.NODE_ENV === "production"`. - -**Note:** All of the public API methods accept `options.cache`, which gives -control over caching when calling these methods directly. - -### Layouts - -A layout is simply a Handlebars template with a `{{{body}}}` placeholder. -Usually it will be an HTML page wrapper into which views will be rendered. - -This view engine adds back the concept of "layout", which was removed in Express -3.x. It can be configured with a path to the layouts directory, by default it's -set to `"views/layouts/"`. - -There are two ways to set a default layout: configuring the view engine's -`defaultLayout` property, or setting [Express locals][] `app.locals.layout`. - -The layout into which a view should be rendered can be overridden per-request -by assigning a different value to the `layout` request local. The following -will render the "home" view with no layout: - -```javascript -app.get('/', function (req, res, next) { - res.render('home', {layout: false}); -}); -``` - -### Helpers - -Helper functions, or "helpers" are functions that can be -[registered with Handlebars][] and can be called within a template. Helpers can -be used for transforming output, iterating over data, etc. To keep with the -spirit of *logic-less* templates, helpers are the place where logic should be -defined. - -Handlebars ships with some [built-in helpers][], such as: `with`, `if`, `each`, -etc. Most application will need to extend this set of helpers to include -app-specific logic and transformations. Beyond defining global helpers on -`Handlebars`, this view engine supports `ExpressHandlebars` instance-level -helpers via the `helpers` configuration property, and render-level helpers via -`options.helpers` when calling the `render()` and `renderView()` methods. - -The following example shows helpers being specified at each level: - -**app.js:** - -Creates a super simple Express app which shows the basic way to register -`ExpressHandlebars` instance-level helpers, and override one at the -render-level. - -```javascript -var express = require('express'), - exphbs = require('express3-handlebars'), - - app = express(), - hbs; - -hbs = exphbs.create({ - // Specify helpers which are only registered on this instance. - helpers: { - foo: function () { return 'FOO!'; } - bar: function () { return 'BAR!'; } - } -}); - -app.engine('handlebars', hbs.engine); -app.set('view engine', 'handlebars'); - -app.get('/', function (req, res, next) { - res.render('home', { - showTitle: true, - - // Override `foo` helper only for this rendering. - helpers: { - foo: function () { return 'foo.'; } - } - }); -}); - -app.listen(3000); -``` - -**views/home.handlebars:** - -The app's home view which uses helper functions to help render the contents. - -```html - - - - - Example App - Home - - - - - {{#if showTitle}} -

    Home

    - {{/if}} - - -

    {{foo}}

    - - -

    {{bar}}

    - - - -``` - -#### More on Helpers - -Refer to the [Handlebars website][] for more information on defining helpers: - -* [Expression Helpers][] -* [Block Helpers][] - - -[examples directory]: https://github.com/ericf/express3-handlebars/tree/master/examples -[view cache setting]: http://expressjs.com/api.html#app-settings -[Express locals]: http://expressjs.com/api.html#app.locals -[registered with Handlebars]: https://github.com/wycats/handlebars.js/#registering-helpers -[built-in helpers]: http://handlebarsjs.com/#builtins -[Handlebars website]: http://handlebarsjs.com/ -[Expression Helpers]: http://handlebarsjs.com/expressions.html#helpers -[Block Helpers]: http://handlebarsjs.com/block_helpers.html - - -API ---- - -### Configuration and Defaults - -There are two main ways to use this package: via its engine factory function, or -creating `ExpressHandlebars` instances; both use the same configuration -properties and defaults. - -```javascript -var exphbs = require('express3-handlebars'); - -// Using the engine factory: -exphbs({ /* config */ }); - -// Create an instance: -exphbs.create({ /* config */ }); -``` - -The following is the list of configuration properties and their default values -(if any): - -#### `defaultLayout` -The string name or path of a template in the `layoutsDir` to use as the default -layout. This is overridden by a `layout` specified in the app or response -`locals`. **Note:** A falsy value will render without a layout; e.g., -`res.render('home', {layout: false});`. - -#### `extname=".handlebars"` -The string name of the file extension used by the templates. - -#### `handlebars=require('handlebars')` -The Handlebars module/implementation. This allows for the `ExpressHandlebars` -instance to use a different Handlebars module/implementation than that provided -by the Handlebars npm package. - -#### `helpers` -An object which holds the helper functions used when rendering templates with -this `ExpressHandlebars` instance. When rendering a template, a collection of -helpers will be generated by merging: `handlebars.helpers` (global), `helpers` -(instance), and `options.helpers` (render-level). This allows Handlebars' -`registerHelper()` function to operate as expected, will providing two extra -levels over helper overrides. - -#### `layoutsDir="views/layouts/"` -The string path to the directory where the layout templates reside. - -#### `partialsDir="views/partials/"` -The string path to the directory where the partials templates reside. - -### Properties - -The public API properties are provided via `ExpressHandlebars` instances. In -additional to the properties listed in the **Configuration and Defaults** -section, the following are additional public properties: - -#### `compiled` -An object cache which holds compiled Handlebars template functions in the -format: `{"path/to/template": [Function]}`. - -#### `engine` -A function reference to the `renderView()` method which is bound to `this` -`ExpressHandlebars` instance. This bound function should be used when -registering this view engine with an Express app. - -#### `handlebarsVersion` -The version number of `handlebars` as a semver. This is unsed internally to -branch on certain operations which differ between Handlebars releases. - -#### `precompiled` -An object cache which holds precompiled Handlebars template strings in the -format: `{"path/to/template": [String]}`. - -### Methods - -The following is the list of public API methods provided via `ExpressHandlebars` -instances: - -#### `loadPartials(options|callback, [callback])` - -Retrieves the partials in the `partialsDir` and passes an object mapping the -partials in the form `{name: partial}` to the `callback`. - -By default each partial will be a compiled Handlebars template function. Use -`options.precompiled` to receive the partials as precompiled templates — this is -useful for sharing templates with client code. - -**Parameters:** - -* `[options]`: Optional object containing any of the following properties: - - * `[cache]`: Whether cached templates can be used if they have already been - requested. This is recommended for production to avoid unnecessary file I/O. - - * `[precompiled=false]`: Whether precompiled templates should be provided, - instead of compiled Handlebars template functions. - -* `callback`: Function to call once the partials are retrieved. - -The name of each partial corresponds to its location in `partialsDir`. For -example, consider the following directory structure: - -``` -views -└── partials - ├── foo - │   └── bar.handlebars - └── title.handlebars - -2 directories, 2 files -``` - -`loadPartials()` would produce the following result: - -```javascript -var hbs = require('express3-handlebars').create(); - -hbs.loadPartials(function (err, partials) { - console.log(partials); - // => { 'foo.bar': [Function], - // => title: [Function] } -}); -``` - -**Note:** The partial name `"foo.bar"` would ideally be `"foo/bar"`, but this is -being prevented by a [Handlebars bug][]. Once this bug is fixed, a future -version will use a "/" separator. Templates requiring the partial still use: -`{{> foo/bar}}`. - -#### `loadTemplate(filePath, options|callback, [callback])` - -Retrieves the template at the specified `filePath` and passes a compiled -Handlebars template function to the `callback`. - -Use `options.precompiled` to receive a precompiled Handlebars template. - -**Parameters:** - -* `filePath`: String path to the Handlebars template file. - -* `[options]`: Optional object containing any of the following properties: - - * `[cache]`: Whether a cached template can be used if it have already been - requested. This is recommended for production to avoid necessary file I/O. - - * `[precompiled=false]`: Whether a precompiled template should be provided, - instead of a compiled Handlebars template function. - -* `callback`: Function to call once the template is retrieved. - -#### `loadTemplates(dirPath, options|callback, [callback])` - -Retrieves the all the templates in the specified `dirPath` and passes an object -mapping the compiled templates in the form `{filename: template}` to the -`callback`. - -Use `options.precompiled` to receive precompiled Handlebars templates — this is -useful for sharing templates with client code. - -**Parameters:** - -* `dirPath`: String path to the directory containing Handlebars template files. - -* `[options]`: Optional object containing any of the following properties: - - * `[cache]`: Whether cached templates can be used if it have already been - requested. This is recommended for production to avoid necessary file I/O. - - * `[precompiled=false]`: Whether precompiled templates should be provided, - instead of a compiled Handlebars template function. - -* `callback`: Function to call once the templates are retrieved. - -#### `render(filePath, options|callback, [callback])` - -Renders the template at the specified `filePath` using this instance's `helpers` -and partials, and passes the resulting string to the `callback`. - -The `options` will be used both as the context in which the Handlebars template -is rendered, and to signal this view engine on how it should behave, e.g., -`options.cache = false` will load _always_ load the templates from disk. - -**Parameters:** - -* `filePath`: String path to the Handlebars template file. - -* `[options]`: Optional object which will serve as the context in which the - Handlebars template is rendered. It may also contain any of the following - properties which affect this view engine's behavior: - - * `[cache]`: Whether a cached template can be used if it have already been - requested. This is recommended for production to avoid unnecessary file I/O. - - * `[helpers]`: Render-level helpers should be merged with (and will override) - instance and global helper functions. - -* `callback`: Function to call once the template is retrieved. - -#### `renderView(viewPath, options|callback, [callback])` - -Renders the template at the specified `viewPath` as the `{{{body}}}` within the -layout specified by the `defaultLayout` or `options.layout`. Rendering will use -this instance's `helpers` and partials, and passes the resulting string to the -`callback`. - -This method is called by Express and is the main entry point into this Express -view engine implementation. It adds the concept of a "layout" and delegates -rendering to the `render()` method. - -The `options` will be used both as the context in which the Handlebars templates -are rendered, and to signal this view engine on how it should behave, e.g., -`options.cache=false` will load _always_ load the templates from disk. - -**Parameters:** - -* `viewPath`: String path to the Handlebars template file which should serve as - the `{{{body}}}` when using a layout. - -* `[options]`: Optional object which will serve as the context in which the - Handlebars templates are rendered. It may also contain any of the following - properties which affect this view engine's behavior: - - * `[cache]`: Whether cached templates can be used if they have already been - requested. This is recommended for production to avoid unnecessary file I/O. - - * `[helpers]`: Render-level helpers should be merged with (and will override) - instance and global helper functions. - - * `[layout]`: Optional string path to the Handlebars template file to be used - as the "layout". This overrides any `defaultLayout` value. Passing a falsy - value will render with no layout (even if a `defaultLayout` is defined). - -* `callback`: Function to call once the template is retrieved. - -### Statics - -The following is the list of static API properties and methods provided on the -`ExpressHandlebars` constructor: - -#### `getHandlebarsSemver(handlebars)` - -Returns a semver-compatible version string for the specified `handlebars` -module/implementation. - -This utility function is used to compute the value for an `ExpressHandlebars` -instance's `handlebarsVersion` property. - - -[Handlebars bug]: https://github.com/wycats/handlebars.js/pull/389 - - -Examples --------- - -### [Basic Usage][] - -This example shows the most basic way to use this view engine. - -### [Advanced Usage][] - -This example is more comprehensive and shows how to use many of the features of -this view engine, including helpers, partials, multiple layouts, etc. - -As noted in the **Package Design** section, this view engine's implementation is -instance-based, and more advanced usages can take advantage of this. The -Advanced Usage example demonstrates how to use an `ExpressHandlebars` instance -to share templates with the client, among other features. - - -[Basic Usage]: https://github.com/ericf/express3-handlebars/tree/master/examples/basic -[Advanced Usage]: https://github.com/ericf/express3-handlebars/tree/master/examples/advanced - - -License -------- - -This software is free to use under the Yahoo! Inc. BSD license. -See the [LICENSE file][] for license text and copyright information. - - -[LICENSE file]: https://github.com/ericf/express3-handlebars/blob/master/LICENSE diff --git a/node_modules/express3-handlebars/examples/advanced/app.js b/node_modules/express3-handlebars/examples/advanced/app.js deleted file mode 100644 index 2b7d8ae9f..000000000 --- a/node_modules/express3-handlebars/examples/advanced/app.js +++ /dev/null @@ -1,99 +0,0 @@ -var express = require('express'), - exphbs = require('../../'), // "express3-handlebars" - helpers = require('./lib/helpers'), - - app = express(), - hbs; - -// Create `ExpressHandlebars` instance with a default layout. -hbs = exphbs.create({ - defaultLayout: 'main', - helpers : helpers, - - // Uses multiple partials dirs, templates in "shared/templates/" are shared - // with the client-side of the app (see below). - partialsDir: [ - 'shared/templates/', - 'views/partials/' - ] -}); - -// Register `hbs` as our view engine using its bound `engine()` function. -app.engine('handlebars', hbs.engine); -app.set('view engine', 'handlebars'); - -// Middleware to expose the app's shared templates to the cliet-side of the app -// for pages which need them. -function exposeTemplates(req, res, next) { - // Uses the `ExpressHandlebars` instance to get the get the **precompiled** - // templates which will be shared with the client-side of the app. - hbs.loadTemplates('shared/templates/', { - cache : app.enabled('view cache'), - precompiled: true - }, function (err, templates) { - if (err) { return next(err); } - - // RegExp to remove the ".handlebars" extension from the template names. - var extRegex = new RegExp(hbs.extname + '$'); - - // Creates an array of templates which are exposed via - // `res.locals.templates`. - templates = Object.keys(templates).map(function (name) { - return { - name : name.replace(extRegex, ''), - template: templates[name] - }; - }); - - // Exposes the templates during view rendering. - if (templates.length) { - res.locals.templates = templates; - } - - next(); - }); -} - -app.get('/', function (req, res) { - res.render('home', { - title: 'Home' - }); -}); - -app.get('/yell', function (req, res) { - res.render('yell', { - title: 'Yell', - - // This `message` will be transformed by our `yell()` helper. - message: 'hello world' - }); -}); - -app.get('/exclaim', function (req, res) { - res.render('yell', { - title : 'Exclaim', - message: 'hello world', - - // This overrides _only_ the default `yell()` helper. - helpers: { - yell: function (msg) { - return (msg + '!!!'); - } - } - }); -}); - -app.get('/echo/:message?', exposeTemplates, function (req, res) { - res.render('echo', { - title : 'Echo', - message: req.params.message, - - // Overrides which layout to use, instead of the defaul "main" layout. - layout: 'shared-templates' - }); -}); - -app.use(express.static('public/')); -app.listen(3000); - -console.log('express3-handlebars example server listening on: 3000'); diff --git a/node_modules/express3-handlebars/examples/advanced/lib/helpers.js b/node_modules/express3-handlebars/examples/advanced/lib/helpers.js deleted file mode 100644 index 7f36cf66d..000000000 --- a/node_modules/express3-handlebars/examples/advanced/lib/helpers.js +++ /dev/null @@ -1,3 +0,0 @@ -exports.yell = function (msg) { - return msg.toUpperCase(); -}; diff --git a/node_modules/express3-handlebars/examples/advanced/public/echo.js b/node_modules/express3-handlebars/examples/advanced/public/echo.js deleted file mode 100644 index df031891a..000000000 --- a/node_modules/express3-handlebars/examples/advanced/public/echo.js +++ /dev/null @@ -1,14 +0,0 @@ -// The client-side "app" which leverages the shared Handlebars "echo" template. -// This will prompt the user for a message, then echo it out by rendering the -// message using the shared template which was exposed by the server. -(function () { - var button = document.getElementById('say'); - - button.addEventListener('click', function (e) { - var message = prompt('Say Something:', 'Yo yo'), - echo = document.createElement('div'); - - echo.innerHTML = Handlebars.templates.echo({message: message}); - document.body.appendChild(echo); - }, false); -}()); diff --git a/node_modules/express3-handlebars/examples/advanced/shared/templates/echo.handlebars b/node_modules/express3-handlebars/examples/advanced/shared/templates/echo.handlebars deleted file mode 100644 index 8e5a71cae..000000000 --- a/node_modules/express3-handlebars/examples/advanced/shared/templates/echo.handlebars +++ /dev/null @@ -1 +0,0 @@ -

    echo: {{message}}

    diff --git a/node_modules/express3-handlebars/examples/advanced/views/echo.handlebars b/node_modules/express3-handlebars/examples/advanced/views/echo.handlebars deleted file mode 100644 index e486a8d5a..000000000 --- a/node_modules/express3-handlebars/examples/advanced/views/echo.handlebars +++ /dev/null @@ -1,8 +0,0 @@ -

    {{> page/title}}

    - -{{> page/nav}} - - -{{> echo}} - - diff --git a/node_modules/express3-handlebars/examples/advanced/views/home.handlebars b/node_modules/express3-handlebars/examples/advanced/views/home.handlebars deleted file mode 100644 index 12708930b..000000000 --- a/node_modules/express3-handlebars/examples/advanced/views/home.handlebars +++ /dev/null @@ -1,3 +0,0 @@ -

    {{> page/title}}

    - -{{> page/nav}} diff --git a/node_modules/express3-handlebars/examples/advanced/views/layouts/main.handlebars b/node_modules/express3-handlebars/examples/advanced/views/layouts/main.handlebars deleted file mode 100644 index 6ea95a580..000000000 --- a/node_modules/express3-handlebars/examples/advanced/views/layouts/main.handlebars +++ /dev/null @@ -1,12 +0,0 @@ - - - - - {{> page/title}} - - - - {{{body}}} - - - diff --git a/node_modules/express3-handlebars/examples/advanced/views/layouts/shared-templates.handlebars b/node_modules/express3-handlebars/examples/advanced/views/layouts/shared-templates.handlebars deleted file mode 100644 index d4396aeec..000000000 --- a/node_modules/express3-handlebars/examples/advanced/views/layouts/shared-templates.handlebars +++ /dev/null @@ -1,25 +0,0 @@ - - - - - {{> page/title}} - - - - {{{body}}} - - {{! Only needs the Handlebars Runtime, because the exposed templates are precompiled. }} - - - - - diff --git a/node_modules/express3-handlebars/examples/advanced/views/partials/page/nav.handlebars b/node_modules/express3-handlebars/examples/advanced/views/partials/page/nav.handlebars deleted file mode 100644 index 545e85e69..000000000 --- a/node_modules/express3-handlebars/examples/advanced/views/partials/page/nav.handlebars +++ /dev/null @@ -1,6 +0,0 @@ - diff --git a/node_modules/express3-handlebars/examples/advanced/views/partials/page/title.handlebars b/node_modules/express3-handlebars/examples/advanced/views/partials/page/title.handlebars deleted file mode 100644 index 4c9a4e938..000000000 --- a/node_modules/express3-handlebars/examples/advanced/views/partials/page/title.handlebars +++ /dev/null @@ -1 +0,0 @@ -Example App: {{title}} diff --git a/node_modules/express3-handlebars/examples/advanced/views/yell.handlebars b/node_modules/express3-handlebars/examples/advanced/views/yell.handlebars deleted file mode 100644 index b5272c3eb..000000000 --- a/node_modules/express3-handlebars/examples/advanced/views/yell.handlebars +++ /dev/null @@ -1,5 +0,0 @@ -

    {{> page/title}}

    - -{{> page/nav}} - -

    {{yell message}}

    diff --git a/node_modules/express3-handlebars/examples/basic/app.js b/node_modules/express3-handlebars/examples/basic/app.js deleted file mode 100644 index f13855cb5..000000000 --- a/node_modules/express3-handlebars/examples/basic/app.js +++ /dev/null @@ -1,15 +0,0 @@ -var express = require('express'), - exphbs = require('../../'), // "express3-handlebars" - - app = express(); - -app.engine('handlebars', exphbs({defaultLayout: 'main'})); -app.set('view engine', 'handlebars'); - -app.get('/', function (req, res) { - res.render('home'); -}); - -app.listen(3000); - -console.log('express3-handlebars example server listening on: 3000'); diff --git a/node_modules/express3-handlebars/examples/basic/views/home.handlebars b/node_modules/express3-handlebars/examples/basic/views/home.handlebars deleted file mode 100644 index d69419082..000000000 --- a/node_modules/express3-handlebars/examples/basic/views/home.handlebars +++ /dev/null @@ -1 +0,0 @@ -

    Example App: Home

    diff --git a/node_modules/express3-handlebars/examples/basic/views/layouts/main.handlebars b/node_modules/express3-handlebars/examples/basic/views/layouts/main.handlebars deleted file mode 100644 index 49aff4b7e..000000000 --- a/node_modules/express3-handlebars/examples/basic/views/layouts/main.handlebars +++ /dev/null @@ -1,12 +0,0 @@ - - - - - Example App - - - - {{{body}}} - - - diff --git a/node_modules/express3-handlebars/index.js b/node_modules/express3-handlebars/index.js deleted file mode 100644 index 5546d2165..000000000 --- a/node_modules/express3-handlebars/index.js +++ /dev/null @@ -1,13 +0,0 @@ -var ExpressHandlebars = require('./lib/express-handlebars'); - -function exphbs(config) { - return exphbs.create(config).engine; -} - -exphbs.create = function (config) { - return new ExpressHandlebars(config); -}; - -exphbs.ExpressHandlebars = ExpressHandlebars; - -module.exports = exphbs; diff --git a/node_modules/express3-handlebars/lib/express-handlebars.js b/node_modules/express3-handlebars/lib/express-handlebars.js deleted file mode 100644 index 9d966eb9a..000000000 --- a/node_modules/express3-handlebars/lib/express-handlebars.js +++ /dev/null @@ -1,367 +0,0 @@ -var async = require('async'), - fs = require('fs'), - glob = require('glob'), - path = require('path'), - semver = require('semver'); - -// -- Utilites ----------------------------------------------------------------- - -function extend(obj) { - Array.prototype.slice.call(arguments, 1).forEach(function (source) { - if (!source) { return; } - - for (var key in source) { - obj[key] = source[key]; - } - }); - - return obj; -} - -// -- Constructor -------------------------------------------------------------- - -function ExpressHandlebars(config) { - config || (config = {}); - - var handlebars = config.handlebars || require('handlebars'); - - if ('extname' in config) { this.extname = config.extname; } - if ('layoutsDir' in config) { this.layoutsDir = config.layoutsDir; } - if ('partialsDir' in config) { this.partialsDir = config.partialsDir; } - - this.defaultLayout = config.defaultLayout; - this.handlebars = handlebars; - this.helpers = config.helpers; - - this.handlebarsVersion = ExpressHandlebars.getHandlebarsSemver(handlebars); - - this.compiled = {}; - this.precompiled = {}; - - this.engine = this.renderView.bind(this); -} - -// -- Statics ------------------------------------------------------------------ - -ExpressHandlebars._dirCache = {}; -ExpressHandlebars._fileCache = {}; -ExpressHandlebars._pendingReads = {}; - -ExpressHandlebars.getHandlebarsSemver = function (handlebars) { - var version = handlebars.VERSION || ''; - - // Makes sure the Handlebars version is a valid semver. - if (version && !semver.valid(version)) { - version = version.replace(/(\d\.\d)\.(\D.*)/, '$1.0-$2'); - } - - return version; -}; - -// -- Prototype ---------------------------------------------------------------- - -extend(ExpressHandlebars.prototype, { - // -- Public Properties ---------------------------------------------------- - - extname : '.handlebars', - layoutsDir : 'views/layouts/', - partialsDir: 'views/partials/', - - // -- Public Methods ------------------------------------------------------- - - loadPartials: function (options, callback) { - if (arguments.length < 2 && typeof options === 'function') { - callback = options; - options = {}; - } - - options || (options = {}); - - function load(dirs, options, callback) { - Array.isArray(dirs) || (dirs = [dirs]); - var loadTemplates = this.loadTemplates.bind(this); - - async.map(dirs, function (dir, callback) { - loadTemplates(dir, options, callback); - }, callback); - } - - function mapPartials(dirs, callback) { - var getPartialName = this._getPartialName.bind(this), - partials; - - partials = dirs.reduce(function (partials, templates) { - Object.keys(templates).forEach(function (filePath) { - partials[getPartialName(filePath)] = templates[filePath]; - }); - - return partials; - }, {}); - - callback(null, partials); - } - - async.waterfall([ - load.bind(this, this.partialsDir, options), - mapPartials.bind(this) - ], callback); - }, - - loadTemplate: function (filePath, options, callback) { - filePath = path.resolve(filePath); - - if (arguments.length < 3 && typeof options === 'function') { - callback = options; - options = {}; - } - - options || (options = {}); - - var precompiled = options.precompiled, - cache = precompiled ? this.precompiled : this.compiled, - template = options.cache && cache[filePath], - compile; - - if (template) { - callback(null, template); - return; - } - - compile = this.handlebars[precompiled ? 'precompile' : 'compile']; - - this._loadFile(filePath, options, function (err, file) { - if (err) { return callback(err); } - - try { - template = cache[filePath] = compile(file); - callback(null, template); - } catch (ex) { - callback(ex); - } - }); - }, - - loadTemplates: function (dirPath, options, callback) { - if (arguments.length < 3 && typeof options === 'function') { - callback = options; - options = {}; - } - - options || (options = {}); - - function load(filePath, callback) { - this.loadTemplate(path.join(dirPath, filePath), options, callback); - } - - function mapTemplates(filePaths, callback) { - async.map(filePaths, load.bind(this), function (err, templates) { - if (err) { return callback(err); } - - var map = filePaths.reduce(function (map, filePath, i) { - map[filePath] = templates[i]; - return map; - }, {}); - - callback(null, map); - }); - } - - async.waterfall([ - this._loadDir.bind(this, dirPath, options), - mapTemplates.bind(this) - ], callback); - }, - - render: function (filePath, options, callback) { - if (arguments.length < 3 && typeof options === 'function') { - callback = options; - options = {}; - } - - options || (options = {}); - - var helpers = extend({}, - this.handlebars.helpers, this.helpers, options.helpers); - - function loadTemplates(callback) { - async.parallel({ - partials: this.loadPartials.bind(this, options), - template: this.loadTemplate.bind(this, filePath, options) - }, callback); - } - - function renderTemplate(templates, callback) { - this._renderTemplate(templates.template, options, { - helpers : helpers, - partials: templates.partials - }, callback); - } - - // Force `{precompiled: false}` option, before passing `options` along - // to `getPartials()` and `getTemplate()` methods. - if (options.precompiled) { - options = extend({}, options, {precompiled: false}); - } - - async.waterfall([ - loadTemplates.bind(this), - renderTemplate.bind(this) - ], callback); - }, - - renderView: function (viewPath, options, callback) { - if (arguments.length < 3 && typeof options === 'function') { - callback = options; - options = {}; - } - - options || (options = {}); - - var layoutPath = this._resolveLayoutPath(options); - - function renderLayout(body, callback) { - var context = extend({}, options, {body: body}); - this.render(layoutPath, context, callback); - } - - // Simple render when no layout is used. - if (!layoutPath) { - this.render.apply(this, arguments); - return; - } - - // Force `{precompiled: false}` option, before passing options along to - // `getPartials()` and `getTemplate()` methods. - if (options.precompiled) { - options = extend({}, options, {precompiled: false}); - } - - async.waterfall([ - this.render.bind(this, viewPath, options), - renderLayout.bind(this) - ], callback); - }, - - // -- Private Methods ------------------------------------------------------ - - _getPartialName: function (filePath) { - var extRegex = new RegExp(this.extname + '$'), - name = filePath.replace(extRegex, ''), - version = this.handlebarsVersion; - - // Fixes a Handlebars bug in versions prior to 1.0.rc.2 which caused - // partials with "/"s in their name to not be found. - // https://github.com/wycats/handlebars.js/pull/389 - if (version && !semver.satisfies(version, '>=1.0.0-rc.2')) { - name = name.replace('/', '.'); - } - - return name; - }, - - _loadDir: function (dirPath, options, callback) { - dirPath = path.resolve(dirPath); - - var dirCache = ExpressHandlebars._dirCache, - pendingReads = ExpressHandlebars._pendingReads, - dir = options.cache && dirCache[dirPath], - callbacks, pattern; - - if (dir) { - callback(null, dir.concat()); - return; - } - - callbacks = pendingReads[dirPath]; - - if (callbacks) { - callbacks.push(callback); - return; - } - - callbacks = pendingReads[dirPath] = [callback]; - pattern = '**/*' + this.extname; - - glob(pattern, {cwd: dirPath}, function (err, dir) { - if (!err) { - dirCache[dirPath] = dir; - } - - while (callbacks.length) { - callbacks.shift().call(null, err, dir && dir.concat()); - } - - delete pendingReads[dirPath]; - }); - }, - - _loadFile: function (filePath, options, callback) { - filePath = path.resolve(filePath); - - var fileCache = ExpressHandlebars._fileCache, - pendingReads = ExpressHandlebars._pendingReads, - file = options.cache && fileCache[filePath], - callbacks; - - if (file) { - callback(null, file); - return; - } - - callbacks = pendingReads[filePath]; - - if (callbacks) { - callbacks.push(callback); - return; - } - - callbacks = pendingReads[filePath] = [callback]; - - fs.readFile(filePath, 'utf8', function (err, file) { - if (!err) { - fileCache[filePath] = file; - } - - while (callbacks.length) { - callbacks.shift().call(null, err, file); - } - - delete pendingReads[filePath]; - }); - }, - - _renderTemplate: function (template, context, options, callback) { - var output; - - try { - output = template(context, options); - callback(null, output); - } catch (ex) { - callback(ex); - } - }, - - _resolveLayoutPath: function (options) { - // Makes sure to interpret falsy `options.layout` values as no layout. - var layoutPath = 'layout' in options ? options.layout : - this.defaultLayout; - - if (!layoutPath) { - return null; - } - - if (!path.extname(layoutPath)) { - layoutPath += this.extname; - } - - if (layoutPath[0] !== '/') { - layoutPath = path.join(this.layoutsDir, layoutPath); - } - - return layoutPath; - } -}); - -// -- Exports ------------------------------------------------------------------ - -module.exports = ExpressHandlebars; diff --git a/node_modules/express3-handlebars/node_modules/.bin/handlebars b/node_modules/express3-handlebars/node_modules/.bin/handlebars deleted file mode 120000 index fb7d090fc..000000000 --- a/node_modules/express3-handlebars/node_modules/.bin/handlebars +++ /dev/null @@ -1 +0,0 @@ -../handlebars/bin/handlebars \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/.bin/semver b/node_modules/express3-handlebars/node_modules/.bin/semver deleted file mode 120000 index 317eb293d..000000000 --- a/node_modules/express3-handlebars/node_modules/.bin/semver +++ /dev/null @@ -1 +0,0 @@ -../semver/bin/semver \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/async/LICENSE b/node_modules/express3-handlebars/node_modules/async/LICENSE deleted file mode 100644 index b7f9d5001..000000000 --- a/node_modules/express3-handlebars/node_modules/async/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Caolan McMahon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express3-handlebars/node_modules/async/README.md b/node_modules/express3-handlebars/node_modules/async/README.md deleted file mode 100644 index 951f76e9f..000000000 --- a/node_modules/express3-handlebars/node_modules/async/README.md +++ /dev/null @@ -1,1425 +0,0 @@ -# Async.js - -Async is a utility module which provides straight-forward, powerful functions -for working with asynchronous JavaScript. Although originally designed for -use with [node.js](http://nodejs.org), it can also be used directly in the -browser. Also supports [component](https://github.com/component/component). - -Async provides around 20 functions that include the usual 'functional' -suspects (map, reduce, filter, each…) as well as some common patterns -for asynchronous control flow (parallel, series, waterfall…). All these -functions assume you follow the node.js convention of providing a single -callback as the last argument of your async function. - - -## Quick Examples - -```javascript -async.map(['file1','file2','file3'], fs.stat, function(err, results){ - // results is now an array of stats for each file -}); - -async.filter(['file1','file2','file3'], fs.exists, function(results){ - // results now equals an array of the existing files -}); - -async.parallel([ - function(){ ... }, - function(){ ... } -], callback); - -async.series([ - function(){ ... }, - function(){ ... } -]); -``` - -There are many more functions available so take a look at the docs below for a -full list. This module aims to be comprehensive, so if you feel anything is -missing please create a GitHub issue for it. - -## Common Pitfalls - -### Binding a context to an iterator - -This section is really about bind, not about async. If you are wondering how to -make async execute your iterators in a given context, or are confused as to why -a method of another library isn't working as an iterator, study this example: - -```js -// Here is a simple object with an (unnecessarily roundabout) squaring method -var AsyncSquaringLibrary = { - squareExponent: 2, - square: function(number, callback){ - var result = Math.pow(number, this.squareExponent); - setTimeout(function(){ - callback(null, result); - }, 200); - } -}; - -async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){ - // result is [NaN, NaN, NaN] - // This fails because the `this.squareExponent` expression in the square - // function is not evaluated in the context of AsyncSquaringLibrary, and is - // therefore undefined. -}); - -async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){ - // result is [1, 4, 9] - // With the help of bind we can attach a context to the iterator before - // passing it to async. Now the square function will be executed in its - // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent` - // will be as expected. -}); -``` - -## Download - -The source is available for download from -[GitHub](http://github.com/caolan/async). -Alternatively, you can install using Node Package Manager (npm): - - npm install async - -__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed - -## In the Browser - -So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage: - -```html - - -``` - -## Documentation - -### Collections - -* [each](#each) -* [eachSeries](#eachSeries) -* [eachLimit](#eachLimit) -* [map](#map) -* [mapSeries](#mapSeries) -* [mapLimit](#mapLimit) -* [filter](#filter) -* [filterSeries](#filterSeries) -* [reject](#reject) -* [rejectSeries](#rejectSeries) -* [reduce](#reduce) -* [reduceRight](#reduceRight) -* [detect](#detect) -* [detectSeries](#detectSeries) -* [sortBy](#sortBy) -* [some](#some) -* [every](#every) -* [concat](#concat) -* [concatSeries](#concatSeries) - -### Control Flow - -* [series](#series) -* [parallel](#parallel) -* [parallelLimit](#parallellimittasks-limit-callback) -* [whilst](#whilst) -* [doWhilst](#doWhilst) -* [until](#until) -* [doUntil](#doUntil) -* [forever](#forever) -* [waterfall](#waterfall) -* [compose](#compose) -* [applyEach](#applyEach) -* [applyEachSeries](#applyEachSeries) -* [queue](#queue) -* [cargo](#cargo) -* [auto](#auto) -* [iterator](#iterator) -* [apply](#apply) -* [nextTick](#nextTick) -* [times](#times) -* [timesSeries](#timesSeries) - -### Utils - -* [memoize](#memoize) -* [unmemoize](#unmemoize) -* [log](#log) -* [dir](#dir) -* [noConflict](#noConflict) - - -## Collections - - - -### each(arr, iterator, callback) - -Applies an iterator function to each item in an array, in parallel. -The iterator is called with an item from the list and a callback for when it -has finished. If the iterator passes an error to this callback, the main -callback for the each function is immediately called with the error. - -Note, that since this function applies the iterator to each item in parallel -there is no guarantee that the iterator functions will complete in order. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback(err) which must be called once it has - completed. If no error has occured, the callback should be run without - arguments or with an explicit null argument. -* callback(err) - A callback which is called after all the iterator functions - have finished, or an error has occurred. - -__Example__ - -```js -// assuming openFiles is an array of file names and saveFile is a function -// to save the modified contents of that file: - -async.each(openFiles, saveFile, function(err){ - // if any of the saves produced an error, err would equal that error -}); -``` - ---------------------------------------- - - - -### eachSeries(arr, iterator, callback) - -The same as each only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. This means the iterator functions will complete in order. - - ---------------------------------------- - - - -### eachLimit(arr, limit, iterator, callback) - -The same as each only no more than "limit" iterators will be simultaneously -running at any time. - -Note that the items are not processed in batches, so there is no guarantee that - the first "limit" iterator functions will complete before any others are -started. - -__Arguments__ - -* arr - An array to iterate over. -* limit - The maximum number of iterators to run at any time. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback(err) which must be called once it has - completed. If no error has occured, the callback should be run without - arguments or with an explicit null argument. -* callback(err) - A callback which is called after all the iterator functions - have finished, or an error has occurred. - -__Example__ - -```js -// Assume documents is an array of JSON objects and requestApi is a -// function that interacts with a rate-limited REST api. - -async.eachLimit(documents, 20, requestApi, function(err){ - // if any of the saves produced an error, err would equal that error -}); -``` - ---------------------------------------- - - -### map(arr, iterator, callback) - -Produces a new array of values by mapping each value in the given array through -the iterator function. The iterator is called with an item from the array and a -callback for when it has finished processing. The callback takes 2 arguments, -an error and the transformed item from the array. If the iterator passes an -error to this callback, the main callback for the map function is immediately -called with the error. - -Note, that since this function applies the iterator to each item in parallel -there is no guarantee that the iterator functions will complete in order, however -the results array will be in the same order as the original array. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback(err, transformed) which must be called once - it has completed with an error (which can be null) and a transformed item. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is an array of the - transformed items from the original array. - -__Example__ - -```js -async.map(['file1','file2','file3'], fs.stat, function(err, results){ - // results is now an array of stats for each file -}); -``` - ---------------------------------------- - - -### mapSeries(arr, iterator, callback) - -The same as map only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. The results array will be in the same order as the original. - - ---------------------------------------- - - -### mapLimit(arr, limit, iterator, callback) - -The same as map only no more than "limit" iterators will be simultaneously -running at any time. - -Note that the items are not processed in batches, so there is no guarantee that - the first "limit" iterator functions will complete before any others are -started. - -__Arguments__ - -* arr - An array to iterate over. -* limit - The maximum number of iterators to run at any time. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback(err, transformed) which must be called once - it has completed with an error (which can be null) and a transformed item. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is an array of the - transformed items from the original array. - -__Example__ - -```js -async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){ - // results is now an array of stats for each file -}); -``` - ---------------------------------------- - - -### filter(arr, iterator, callback) - -__Alias:__ select - -Returns a new array of all the values which pass an async truth test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like fs.exists. This operation is -performed in parallel, but the results array will be in the same order as the -original. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback(truthValue) which must be called with a - boolean argument once it has completed. -* callback(results) - A callback which is called after all the iterator - functions have finished. - -__Example__ - -```js -async.filter(['file1','file2','file3'], fs.exists, function(results){ - // results now equals an array of the existing files -}); -``` - ---------------------------------------- - - -### filterSeries(arr, iterator, callback) - -__alias:__ selectSeries - -The same as filter only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. The results array will be in the same order as the original. - ---------------------------------------- - - -### reject(arr, iterator, callback) - -The opposite of filter. Removes values that pass an async truth test. - ---------------------------------------- - - -### rejectSeries(arr, iterator, callback) - -The same as reject, only the iterator is applied to each item in the array -in series. - - ---------------------------------------- - - -### reduce(arr, memo, iterator, callback) - -__aliases:__ inject, foldl - -Reduces a list of values into a single value using an async iterator to return -each successive step. Memo is the initial state of the reduction. This -function only operates in series. For performance reasons, it may make sense to -split a call to this function into a parallel map, then use the normal -Array.prototype.reduce on the results. This function is for situations where -each step in the reduction needs to be async, if you can get the data before -reducing it then it's probably a good idea to do so. - -__Arguments__ - -* arr - An array to iterate over. -* memo - The initial state of the reduction. -* iterator(memo, item, callback) - A function applied to each item in the - array to produce the next step in the reduction. The iterator is passed a - callback(err, reduction) which accepts an optional error as its first - argument, and the state of the reduction as the second. If an error is - passed to the callback, the reduction is stopped and the main callback is - immediately called with the error. -* callback(err, result) - A callback which is called after all the iterator - functions have finished. Result is the reduced value. - -__Example__ - -```js -async.reduce([1,2,3], 0, function(memo, item, callback){ - // pointless async: - process.nextTick(function(){ - callback(null, memo + item) - }); -}, function(err, result){ - // result is now equal to the last value of memo, which is 6 -}); -``` - ---------------------------------------- - - -### reduceRight(arr, memo, iterator, callback) - -__Alias:__ foldr - -Same as reduce, only operates on the items in the array in reverse order. - - ---------------------------------------- - - -### detect(arr, iterator, callback) - -Returns the first value in a list that passes an async truth test. The -iterator is applied in parallel, meaning the first iterator to return true will -fire the detect callback with that result. That means the result might not be -the first item in the original array (in terms of order) that passes the test. - -If order within the original array is important then look at detectSeries. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback(truthValue) which must be called with a - boolean argument once it has completed. -* callback(result) - A callback which is called as soon as any iterator returns - true, or after all the iterator functions have finished. Result will be - the first item in the array that passes the truth test (iterator) or the - value undefined if none passed. - -__Example__ - -```js -async.detect(['file1','file2','file3'], fs.exists, function(result){ - // result now equals the first file in the list that exists -}); -``` - ---------------------------------------- - - -### detectSeries(arr, iterator, callback) - -The same as detect, only the iterator is applied to each item in the array -in series. This means the result is always the first in the original array (in -terms of array order) that passes the truth test. - - ---------------------------------------- - - -### sortBy(arr, iterator, callback) - -Sorts a list by the results of running each value through an async iterator. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback(err, sortValue) which must be called once it - has completed with an error (which can be null) and a value to use as the sort - criteria. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is the items from - the original array sorted by the values returned by the iterator calls. - -__Example__ - -```js -async.sortBy(['file1','file2','file3'], function(file, callback){ - fs.stat(file, function(err, stats){ - callback(err, stats.mtime); - }); -}, function(err, results){ - // results is now the original array of files sorted by - // modified date -}); -``` - ---------------------------------------- - - -### some(arr, iterator, callback) - -__Alias:__ any - -Returns true if at least one element in the array satisfies an async test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like fs.exists. Once any iterator -call returns true, the main callback is immediately called. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback(truthValue) which must be called with a - boolean argument once it has completed. -* callback(result) - A callback which is called as soon as any iterator returns - true, or after all the iterator functions have finished. Result will be - either true or false depending on the values of the async tests. - -__Example__ - -```js -async.some(['file1','file2','file3'], fs.exists, function(result){ - // if result is true then at least one of the files exists -}); -``` - ---------------------------------------- - - -### every(arr, iterator, callback) - -__Alias:__ all - -Returns true if every element in the array satisfies an async test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like fs.exists. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback(truthValue) which must be called with a - boolean argument once it has completed. -* callback(result) - A callback which is called after all the iterator - functions have finished. Result will be either true or false depending on - the values of the async tests. - -__Example__ - -```js -async.every(['file1','file2','file3'], fs.exists, function(result){ - // if result is true then every file exists -}); -``` - ---------------------------------------- - - -### concat(arr, iterator, callback) - -Applies an iterator to each item in a list, concatenating the results. Returns the -concatenated list. The iterators are called in parallel, and the results are -concatenated as they return. There is no guarantee that the results array will -be returned in the original order of the arguments passed to the iterator function. - -__Arguments__ - -* arr - An array to iterate over -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback(err, results) which must be called once it - has completed with an error (which can be null) and an array of results. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is an array containing - the concatenated results of the iterator function. - -__Example__ - -```js -async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ - // files is now a list of filenames that exist in the 3 directories -}); -``` - ---------------------------------------- - - -### concatSeries(arr, iterator, callback) - -Same as async.concat, but executes in series instead of parallel. - - -## Control Flow - - -### series(tasks, [callback]) - -Run an array of functions in series, each one running once the previous -function has completed. If any functions in the series pass an error to its -callback, no more functions are run and the callback for the series is -immediately called with the value of the error. Once the tasks have completed, -the results are passed to the final callback as an array. - -It is also possible to use an object instead of an array. Each property will be -run as a function and the results will be passed to the final callback as an object -instead of an array. This can be a more readable way of handling results from -async.series. - - -__Arguments__ - -* tasks - An array or object containing functions to run, each function is passed - a callback(err, result) it must call on completion with an error (which can - be null) and an optional result value. -* callback(err, results) - An optional callback to run once all the functions - have completed. This function gets a results array (or object) containing all - the result arguments passed to the task callbacks. - -__Example__ - -```js -async.series([ - function(callback){ - // do some stuff ... - callback(null, 'one'); - }, - function(callback){ - // do some more stuff ... - callback(null, 'two'); - } -], -// optional callback -function(err, results){ - // results is now equal to ['one', 'two'] -}); - - -// an example using an object instead of an array -async.series({ - one: function(callback){ - setTimeout(function(){ - callback(null, 1); - }, 200); - }, - two: function(callback){ - setTimeout(function(){ - callback(null, 2); - }, 100); - } -}, -function(err, results) { - // results is now equal to: {one: 1, two: 2} -}); -``` - ---------------------------------------- - - -### parallel(tasks, [callback]) - -Run an array of functions in parallel, without waiting until the previous -function has completed. If any of the functions pass an error to its -callback, the main callback is immediately called with the value of the error. -Once the tasks have completed, the results are passed to the final callback as an -array. - -It is also possible to use an object instead of an array. Each property will be -run as a function and the results will be passed to the final callback as an object -instead of an array. This can be a more readable way of handling results from -async.parallel. - - -__Arguments__ - -* tasks - An array or object containing functions to run, each function is passed - a callback(err, result) it must call on completion with an error (which can - be null) and an optional result value. -* callback(err, results) - An optional callback to run once all the functions - have completed. This function gets a results array (or object) containing all - the result arguments passed to the task callbacks. - -__Example__ - -```js -async.parallel([ - function(callback){ - setTimeout(function(){ - callback(null, 'one'); - }, 200); - }, - function(callback){ - setTimeout(function(){ - callback(null, 'two'); - }, 100); - } -], -// optional callback -function(err, results){ - // the results array will equal ['one','two'] even though - // the second function had a shorter timeout. -}); - - -// an example using an object instead of an array -async.parallel({ - one: function(callback){ - setTimeout(function(){ - callback(null, 1); - }, 200); - }, - two: function(callback){ - setTimeout(function(){ - callback(null, 2); - }, 100); - } -}, -function(err, results) { - // results is now equals to: {one: 1, two: 2} -}); -``` - ---------------------------------------- - - -### parallelLimit(tasks, limit, [callback]) - -The same as parallel only the tasks are executed in parallel with a maximum of "limit" -tasks executing at any time. - -Note that the tasks are not executed in batches, so there is no guarantee that -the first "limit" tasks will complete before any others are started. - -__Arguments__ - -* tasks - An array or object containing functions to run, each function is passed - a callback(err, result) it must call on completion with an error (which can - be null) and an optional result value. -* limit - The maximum number of tasks to run at any time. -* callback(err, results) - An optional callback to run once all the functions - have completed. This function gets a results array (or object) containing all - the result arguments passed to the task callbacks. - ---------------------------------------- - - -### whilst(test, fn, callback) - -Repeatedly call fn, while test returns true. Calls the callback when stopped, -or an error occurs. - -__Arguments__ - -* test() - synchronous truth test to perform before each execution of fn. -* fn(callback) - A function to call each time the test passes. The function is - passed a callback(err) which must be called once it has completed with an - optional error argument. -* callback(err) - A callback which is called after the test fails and repeated - execution of fn has stopped. - -__Example__ - -```js -var count = 0; - -async.whilst( - function () { return count < 5; }, - function (callback) { - count++; - setTimeout(callback, 1000); - }, - function (err) { - // 5 seconds have passed - } -); -``` - ---------------------------------------- - - -### doWhilst(fn, test, callback) - -The post check version of whilst. To reflect the difference in the order of operations `test` and `fn` arguments are switched. `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - ---------------------------------------- - - -### until(test, fn, callback) - -Repeatedly call fn, until test returns true. Calls the callback when stopped, -or an error occurs. - -The inverse of async.whilst. - ---------------------------------------- - - -### doUntil(fn, test, callback) - -Like doWhilst except the test is inverted. Note the argument ordering differs from `until`. - ---------------------------------------- - - -### forever(fn, callback) - -Calls the asynchronous function 'fn' repeatedly, in series, indefinitely. -If an error is passed to fn's callback then 'callback' is called with the -error, otherwise it will never be called. - ---------------------------------------- - - -### waterfall(tasks, [callback]) - -Runs an array of functions in series, each passing their results to the next in -the array. However, if any of the functions pass an error to the callback, the -next function is not executed and the main callback is immediately called with -the error. - -__Arguments__ - -* tasks - An array of functions to run, each function is passed a - callback(err, result1, result2, ...) it must call on completion. The first - argument is an error (which can be null) and any further arguments will be - passed as arguments in order to the next task. -* callback(err, [results]) - An optional callback to run once all the functions - have completed. This will be passed the results of the last task's callback. - - - -__Example__ - -```js -async.waterfall([ - function(callback){ - callback(null, 'one', 'two'); - }, - function(arg1, arg2, callback){ - callback(null, 'three'); - }, - function(arg1, callback){ - // arg1 now equals 'three' - callback(null, 'done'); - } -], function (err, result) { - // result now equals 'done' -}); -``` - ---------------------------------------- - -### compose(fn1, fn2...) - -Creates a function which is a composition of the passed asynchronous -functions. Each function consumes the return value of the function that -follows. Composing functions f(), g() and h() would produce the result of -f(g(h())), only this version uses callbacks to obtain the return values. - -Each function is executed with the `this` binding of the composed function. - -__Arguments__ - -* functions... - the asynchronous functions to compose - - -__Example__ - -```js -function add1(n, callback) { - setTimeout(function () { - callback(null, n + 1); - }, 10); -} - -function mul3(n, callback) { - setTimeout(function () { - callback(null, n * 3); - }, 10); -} - -var add1mul3 = async.compose(mul3, add1); - -add1mul3(4, function (err, result) { - // result now equals 15 -}); -``` - ---------------------------------------- - -### applyEach(fns, args..., callback) - -Applies the provided arguments to each function in the array, calling the -callback after all functions have completed. If you only provide the first -argument then it will return a function which lets you pass in the -arguments as if it were a single function call. - -__Arguments__ - -* fns - the asynchronous functions to all call with the same arguments -* args... - any number of separate arguments to pass to the function -* callback - the final argument should be the callback, called when all - functions have completed processing - - -__Example__ - -```js -async.applyEach([enableSearch, updateSchema], 'bucket', callback); - -// partial application example: -async.each( - buckets, - async.applyEach([enableSearch, updateSchema]), - callback -); -``` - ---------------------------------------- - - -### applyEachSeries(arr, iterator, callback) - -The same as applyEach only the functions are applied in series. - ---------------------------------------- - - -### queue(worker, concurrency) - -Creates a queue object with the specified concurrency. Tasks added to the -queue will be processed in parallel (up to the concurrency limit). If all -workers are in progress, the task is queued until one is available. Once -a worker has completed a task, the task's callback is called. - -__Arguments__ - -* worker(task, callback) - An asynchronous function for processing a queued - task, which must call its callback(err) argument when finished, with an - optional error as an argument. -* concurrency - An integer for determining how many worker functions should be - run in parallel. - -__Queue objects__ - -The queue object returned by this function has the following properties and -methods: - -* length() - a function returning the number of items waiting to be processed. -* concurrency - an integer for determining how many worker functions should be - run in parallel. This property can be changed after a queue is created to - alter the concurrency on-the-fly. -* push(task, [callback]) - add a new task to the queue, the callback is called - once the worker has finished processing the task. - instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list. -* unshift(task, [callback]) - add a new task to the front of the queue. -* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued -* empty - a callback that is called when the last item from the queue is given to a worker -* drain - a callback that is called when the last item from the queue has returned from the worker - -__Example__ - -```js -// create a queue object with concurrency 2 - -var q = async.queue(function (task, callback) { - console.log('hello ' + task.name); - callback(); -}, 2); - - -// assign a callback -q.drain = function() { - console.log('all items have been processed'); -} - -// add some items to the queue - -q.push({name: 'foo'}, function (err) { - console.log('finished processing foo'); -}); -q.push({name: 'bar'}, function (err) { - console.log('finished processing bar'); -}); - -// add some items to the queue (batch-wise) - -q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { - console.log('finished processing bar'); -}); - -// add some items to the front of the queue - -q.unshift({name: 'bar'}, function (err) { - console.log('finished processing bar'); -}); -``` - ---------------------------------------- - - -### cargo(worker, [payload]) - -Creates a cargo object with the specified payload. Tasks added to the -cargo will be processed altogether (up to the payload limit). If the -worker is in progress, the task is queued until it is available. Once -the worker has completed some tasks, each callback of those tasks is called. - -__Arguments__ - -* worker(tasks, callback) - An asynchronous function for processing an array of - queued tasks, which must call its callback(err) argument when finished, with - an optional error as an argument. -* payload - An optional integer for determining how many tasks should be - processed per round; if omitted, the default is unlimited. - -__Cargo objects__ - -The cargo object returned by this function has the following properties and -methods: - -* length() - a function returning the number of items waiting to be processed. -* payload - an integer for determining how many tasks should be - process per round. This property can be changed after a cargo is created to - alter the payload on-the-fly. -* push(task, [callback]) - add a new task to the queue, the callback is called - once the worker has finished processing the task. - instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list. -* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued -* empty - a callback that is called when the last item from the queue is given to a worker -* drain - a callback that is called when the last item from the queue has returned from the worker - -__Example__ - -```js -// create a cargo object with payload 2 - -var cargo = async.cargo(function (tasks, callback) { - for(var i=0; i -### auto(tasks, [callback]) - -Determines the best order for running functions based on their requirements. -Each function can optionally depend on other functions being completed first, -and each function is run as soon as its requirements are satisfied. If any of -the functions pass an error to their callback, that function will not complete -(so any other functions depending on it will not run) and the main callback -will be called immediately with the error. Functions also receive an object -containing the results of functions which have completed so far. - -Note, all functions are called with a results object as a second argument, -so it is unsafe to pass functions in the tasks object which cannot handle the -extra argument. For example, this snippet of code: - -```js -async.auto({ - readData: async.apply(fs.readFile, 'data.txt', 'utf-8') -}, callback); -``` - -will have the effect of calling readFile with the results object as the last -argument, which will fail: - -```js -fs.readFile('data.txt', 'utf-8', cb, {}); -``` - -Instead, wrap the call to readFile in a function which does not forward the -results object: - -```js -async.auto({ - readData: function(cb, results){ - fs.readFile('data.txt', 'utf-8', cb); - } -}, callback); -``` - -__Arguments__ - -* tasks - An object literal containing named functions or an array of - requirements, with the function itself the last item in the array. The key - used for each function or array is used when specifying requirements. The - function receives two arguments: (1) a callback(err, result) which must be - called when finished, passing an error (which can be null) and the result of - the function's execution, and (2) a results object, containing the results of - the previously executed functions. -* callback(err, results) - An optional callback which is called when all the - tasks have been completed. The callback will receive an error as an argument - if any tasks pass an error to their callback. Results will always be passed - but if an error occurred, no other tasks will be performed, and the results - object will only contain partial results. - - -__Example__ - -```js -async.auto({ - get_data: function(callback){ - // async code to get some data - }, - make_folder: function(callback){ - // async code to create a directory to store a file in - // this is run at the same time as getting the data - }, - write_file: ['get_data', 'make_folder', function(callback){ - // once there is some data and the directory exists, - // write the data to a file in the directory - callback(null, filename); - }], - email_link: ['write_file', function(callback, results){ - // once the file is written let's email a link to it... - // results.write_file contains the filename returned by write_file. - }] -}); -``` - -This is a fairly trivial example, but to do this using the basic parallel and -series functions would look like this: - -```js -async.parallel([ - function(callback){ - // async code to get some data - }, - function(callback){ - // async code to create a directory to store a file in - // this is run at the same time as getting the data - } -], -function(err, results){ - async.series([ - function(callback){ - // once there is some data and the directory exists, - // write the data to a file in the directory - }, - function(callback){ - // once the file is written let's email a link to it... - } - ]); -}); -``` - -For a complicated series of async tasks using the auto function makes adding -new tasks much easier and makes the code more readable. - - ---------------------------------------- - - -### iterator(tasks) - -Creates an iterator function which calls the next function in the array, -returning a continuation to call the next one after that. It's also possible to -'peek' the next iterator by doing iterator.next(). - -This function is used internally by the async module but can be useful when -you want to manually control the flow of functions in series. - -__Arguments__ - -* tasks - An array of functions to run. - -__Example__ - -```js -var iterator = async.iterator([ - function(){ sys.p('one'); }, - function(){ sys.p('two'); }, - function(){ sys.p('three'); } -]); - -node> var iterator2 = iterator(); -'one' -node> var iterator3 = iterator2(); -'two' -node> iterator3(); -'three' -node> var nextfn = iterator2.next(); -node> nextfn(); -'three' -``` - ---------------------------------------- - - -### apply(function, arguments..) - -Creates a continuation function with some arguments already applied, a useful -shorthand when combined with other control flow functions. Any arguments -passed to the returned function are added to the arguments originally passed -to apply. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to automatically apply when the - continuation is called. - -__Example__ - -```js -// using apply - -async.parallel([ - async.apply(fs.writeFile, 'testfile1', 'test1'), - async.apply(fs.writeFile, 'testfile2', 'test2'), -]); - - -// the same process without using apply - -async.parallel([ - function(callback){ - fs.writeFile('testfile1', 'test1', callback); - }, - function(callback){ - fs.writeFile('testfile2', 'test2', callback); - } -]); -``` - -It's possible to pass any number of additional arguments when calling the -continuation: - -```js -node> var fn = async.apply(sys.puts, 'one'); -node> fn('two', 'three'); -one -two -three -``` - ---------------------------------------- - - -### nextTick(callback) - -Calls the callback on a later loop around the event loop. In node.js this just -calls process.nextTick, in the browser it falls back to setImmediate(callback) -if available, otherwise setTimeout(callback, 0), which means other higher priority -events may precede the execution of the callback. - -This is used internally for browser-compatibility purposes. - -__Arguments__ - -* callback - The function to call on a later loop around the event loop. - -__Example__ - -```js -var call_order = []; -async.nextTick(function(){ - call_order.push('two'); - // call_order now equals ['one','two'] -}); -call_order.push('one') -``` - - -### times(n, callback) - -Calls the callback n times and accumulates results in the same manner -you would use with async.map. - -__Arguments__ - -* n - The number of times to run the function. -* callback - The function to call n times. - -__Example__ - -```js -// Pretend this is some complicated async factory -var createUser = function(id, callback) { - callback(null, { - id: 'user' + id - }) -} -// generate 5 users -async.times(5, function(n, next){ - createUser(n, function(err, user) { - next(err, user) - }) -}, function(err, users) { - // we should now have 5 users -}); -``` - - -### timesSeries(n, callback) - -The same as times only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. The results array will be in the same order as the original. - - -## Utils - - -### memoize(fn, [hasher]) - -Caches the results of an async function. When creating a hash to store function -results against, the callback is omitted from the hash and an optional hash -function can be used. - -The cache of results is exposed as the `memo` property of the function returned -by `memoize`. - -__Arguments__ - -* fn - the function you to proxy and cache results from. -* hasher - an optional function for generating a custom hash for storing - results, it has all the arguments applied to it apart from the callback, and - must be synchronous. - -__Example__ - -```js -var slow_fn = function (name, callback) { - // do something - callback(null, result); -}; -var fn = async.memoize(slow_fn); - -// fn can now be used as if it were slow_fn -fn('some name', function () { - // callback -}); -``` - - -### unmemoize(fn) - -Undoes a memoized function, reverting it to the original, unmemoized -form. Comes handy in tests. - -__Arguments__ - -* fn - the memoized function - - -### log(function, arguments) - -Logs the result of an async function to the console. Only works in node.js or -in browsers that support console.log and console.error (such as FF and Chrome). -If multiple arguments are returned from the async function, console.log is -called on each argument in order. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to apply to the function. - -__Example__ - -```js -var hello = function(name, callback){ - setTimeout(function(){ - callback(null, 'hello ' + name); - }, 1000); -}; -``` -```js -node> async.log(hello, 'world'); -'hello world' -``` - ---------------------------------------- - - -### dir(function, arguments) - -Logs the result of an async function to the console using console.dir to -display the properties of the resulting object. Only works in node.js or -in browsers that support console.dir and console.error (such as FF and Chrome). -If multiple arguments are returned from the async function, console.dir is -called on each argument in order. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to apply to the function. - -__Example__ - -```js -var hello = function(name, callback){ - setTimeout(function(){ - callback(null, {hello: name}); - }, 1000); -}; -``` -```js -node> async.dir(hello, 'world'); -{hello: 'world'} -``` - ---------------------------------------- - - -### noConflict() - -Changes the value of async back to its original value, returning a reference to the -async object. diff --git a/node_modules/express3-handlebars/node_modules/async/component.json b/node_modules/express3-handlebars/node_modules/async/component.json deleted file mode 100644 index bbb011548..000000000 --- a/node_modules/express3-handlebars/node_modules/async/component.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "async", - "repo": "caolan/async", - "description": "Higher-order functions and common patterns for asynchronous code", - "version": "0.1.23", - "keywords": [], - "dependencies": {}, - "development": {}, - "main": "lib/async.js", - "scripts": [ "lib/async.js" ] -} diff --git a/node_modules/express3-handlebars/node_modules/async/lib/async.js b/node_modules/express3-handlebars/node_modules/async/lib/async.js deleted file mode 100644 index 1eebb153f..000000000 --- a/node_modules/express3-handlebars/node_modules/async/lib/async.js +++ /dev/null @@ -1,958 +0,0 @@ -/*global setImmediate: false, setTimeout: false, console: false */ -(function () { - - var async = {}; - - // global on the server, window in the browser - var root, previous_async; - - root = this; - if (root != null) { - previous_async = root.async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - function only_once(fn) { - var called = false; - return function() { - if (called) throw new Error("Callback was already called."); - called = true; - fn.apply(root, arguments); - } - } - - //// cross-browser compatiblity functions //// - - var _each = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _each(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _each(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - if (typeof process === 'undefined' || !(process.nextTick)) { - if (typeof setImmediate === 'function') { - async.nextTick = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - async.setImmediate = async.nextTick; - } - else { - async.nextTick = function (fn) { - setTimeout(fn, 0); - }; - async.setImmediate = async.nextTick; - } - } - else { - async.nextTick = process.nextTick; - if (typeof setImmediate !== 'undefined') { - async.setImmediate = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - } - else { - async.setImmediate = async.nextTick; - } - } - - async.each = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - _each(arr, function (x) { - iterator(x, only_once(function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(null); - } - } - })); - }); - }; - async.forEach = async.each; - - async.eachSeries = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(null); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - async.forEachSeries = async.eachSeries; - - async.eachLimit = function (arr, limit, iterator, callback) { - var fn = _eachLimit(limit); - fn.apply(null, [arr, iterator, callback]); - }; - async.forEachLimit = async.eachLimit; - - var _eachLimit = function (limit) { - - return function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length || limit <= 0) { - return callback(); - } - var completed = 0; - var started = 0; - var running = 0; - - (function replenish () { - if (completed >= arr.length) { - return callback(); - } - - while (running < limit && started < arr.length) { - started += 1; - running += 1; - iterator(arr[started - 1], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - running -= 1; - if (completed >= arr.length) { - callback(); - } - else { - replenish(); - } - } - }); - } - })(); - }; - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.each].concat(args)); - }; - }; - var doParallelLimit = function(limit, fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [_eachLimit(limit)].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.eachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - async.mapLimit = function (arr, limit, iterator, callback) { - return _mapLimit(limit)(arr, iterator, callback); - }; - - var _mapLimit = function(limit) { - return doParallelLimit(limit, _asyncMap); - }; - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.eachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - main_callback = function () {}; - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var results = {}; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _each(listeners.slice(0), function (fn) { - fn(); - }); - }; - - addListener(function () { - if (_keys(results).length === keys.length) { - callback(null, results); - callback = function () {}; - } - }); - - _each(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - if (err) { - var safeResults = {}; - _each(_keys(results), function(rkey) { - safeResults[rkey] = results[rkey]; - }); - safeResults[k] = args; - callback(err, safeResults); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - results[k] = args; - async.setImmediate(taskComplete); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && results.hasOwnProperty(x)); - }, true) && !results.hasOwnProperty(k); - }; - if (ready()) { - task[task.length - 1](taskCallback, results); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback, results); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor !== Array) { - var err = new Error('First argument to waterfall must be an array of functions'); - return callback(err); - } - if (!tasks.length) { - return callback(); - } - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback.apply(null, arguments); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.setImmediate(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - var _parallel = function(eachfn, tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - eachfn.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - eachfn.each(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.parallel = function (tasks, callback) { - _parallel({ map: async.map, each: async.each }, tasks, callback); - }; - - async.parallelLimit = function(tasks, limit, callback) { - _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.eachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doWhilst = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - if (test()) { - async.doWhilst(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doUntil = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - if (!test()) { - async.doUntil(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.queue = function (worker, concurrency) { - if (concurrency === undefined) { - concurrency = 1; - } - function _insert(q, data, pos, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _each(data, function(task) { - var item = { - data: task, - callback: typeof callback === 'function' ? callback : null - }; - - if (pos) { - q.tasks.unshift(item); - } else { - q.tasks.push(item); - } - - if (q.saturated && q.tasks.length === concurrency) { - q.saturated(); - } - async.setImmediate(q.process); - }); - } - - var workers = 0; - var q = { - tasks: [], - concurrency: concurrency, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - _insert(q, data, false, callback); - }, - unshift: function (data, callback) { - _insert(q, data, true, callback); - }, - process: function () { - if (workers < q.concurrency && q.tasks.length) { - var task = q.tasks.shift(); - if (q.empty && q.tasks.length === 0) { - q.empty(); - } - workers += 1; - var next = function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - if (q.drain && q.tasks.length + workers === 0) { - q.drain(); - } - q.process(); - }; - var cb = only_once(next); - worker(task.data, cb); - } - }, - length: function () { - return q.tasks.length; - }, - running: function () { - return workers; - } - }; - return q; - }; - - async.cargo = function (worker, payload) { - var working = false, - tasks = []; - - var cargo = { - tasks: tasks, - payload: payload, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _each(data, function(task) { - tasks.push({ - data: task, - callback: typeof callback === 'function' ? callback : null - }); - if (cargo.saturated && tasks.length === payload) { - cargo.saturated(); - } - }); - async.setImmediate(cargo.process); - }, - process: function process() { - if (working) return; - if (tasks.length === 0) { - if(cargo.drain) cargo.drain(); - return; - } - - var ts = typeof payload === 'number' - ? tasks.splice(0, payload) - : tasks.splice(0); - - var ds = _map(ts, function (task) { - return task.data; - }); - - if(cargo.empty) cargo.empty(); - working = true; - worker(ds, function () { - working = false; - - var args = arguments; - _each(ts, function (data) { - if (data.callback) { - data.callback.apply(null, args); - } - }); - - process(); - }); - }, - length: function () { - return tasks.length; - }, - running: function () { - return working; - } - }; - return cargo; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _each(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - var queues = {}; - hasher = hasher || function (x) { - return x; - }; - var memoized = function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else if (key in queues) { - queues[key].push(callback); - } - else { - queues[key] = [callback]; - fn.apply(null, args.concat([function () { - memo[key] = arguments; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, arguments); - } - }])); - } - }; - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; - }; - - async.unmemoize = function (fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; - }; - - async.times = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.map(counter, iterator, callback); - }; - - async.timesSeries = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.mapSeries(counter, iterator, callback); - }; - - async.compose = function (/* functions... */) { - var fns = Array.prototype.reverse.call(arguments); - return function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - async.reduce(fns, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat([function () { - var err = arguments[0]; - var nextargs = Array.prototype.slice.call(arguments, 1); - cb(err, nextargs); - }])) - }, - function (err, results) { - callback.apply(that, [err].concat(results)); - }); - }; - }; - - var _applyEach = function (eachfn, fns /*args...*/) { - var go = function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - return eachfn(fns, function (fn, cb) { - fn.apply(that, args.concat([cb])); - }, - callback); - }; - if (arguments.length > 2) { - var args = Array.prototype.slice.call(arguments, 2); - return go.apply(this, args); - } - else { - return go; - } - }; - async.applyEach = doParallel(_applyEach); - async.applyEachSeries = doSeries(_applyEach); - - async.forever = function (fn, callback) { - function next(err) { - if (err) { - if (callback) { - return callback(err); - } - throw err; - } - fn(next); - } - next(); - }; - - // AMD / RequireJS - if (typeof define !== 'undefined' && define.amd) { - define([], function () { - return async; - }); - } - // Node.js - else if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - // included directly via \n\n```\n\n## Documentation\n\n### Collections\n\n* [each](#each)\n* [eachSeries](#eachSeries)\n* [eachLimit](#eachLimit)\n* [map](#map)\n* [mapSeries](#mapSeries)\n* [mapLimit](#mapLimit)\n* [filter](#filter)\n* [filterSeries](#filterSeries)\n* [reject](#reject)\n* [rejectSeries](#rejectSeries)\n* [reduce](#reduce)\n* [reduceRight](#reduceRight)\n* [detect](#detect)\n* [detectSeries](#detectSeries)\n* [sortBy](#sortBy)\n* [some](#some)\n* [every](#every)\n* [concat](#concat)\n* [concatSeries](#concatSeries)\n\n### Control Flow\n\n* [series](#series)\n* [parallel](#parallel)\n* [parallelLimit](#parallellimittasks-limit-callback)\n* [whilst](#whilst)\n* [doWhilst](#doWhilst)\n* [until](#until)\n* [doUntil](#doUntil)\n* [forever](#forever)\n* [waterfall](#waterfall)\n* [compose](#compose)\n* [applyEach](#applyEach)\n* [applyEachSeries](#applyEachSeries)\n* [queue](#queue)\n* [cargo](#cargo)\n* [auto](#auto)\n* [iterator](#iterator)\n* [apply](#apply)\n* [nextTick](#nextTick)\n* [times](#times)\n* [timesSeries](#timesSeries)\n\n### Utils\n\n* [memoize](#memoize)\n* [unmemoize](#unmemoize)\n* [log](#log)\n* [dir](#dir)\n* [noConflict](#noConflict)\n\n\n## Collections\n\n\n\n### each(arr, iterator, callback)\n\nApplies an iterator function to each item in an array, in parallel.\nThe iterator is called with an item from the list and a callback for when it\nhas finished. If the iterator passes an error to this callback, the main\ncallback for the each function is immediately called with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err) which must be called once it has \n completed. If no error has occured, the callback should be run without \n arguments or with an explicit null argument.\n* callback(err) - A callback which is called after all the iterator functions\n have finished, or an error has occurred.\n\n__Example__\n\n```js\n// assuming openFiles is an array of file names and saveFile is a function\n// to save the modified contents of that file:\n\nasync.each(openFiles, saveFile, function(err){\n // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n\n\n### eachSeries(arr, iterator, callback)\n\nThe same as each only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. This means the iterator functions will complete in order.\n\n\n---------------------------------------\n\n\n\n### eachLimit(arr, limit, iterator, callback)\n\nThe same as each only no more than \"limit\" iterators will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that\n the first \"limit\" iterator functions will complete before any others are \nstarted.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - The maximum number of iterators to run at any time.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err) which must be called once it has \n completed. If no error has occured, the callback should be run without \n arguments or with an explicit null argument.\n* callback(err) - A callback which is called after all the iterator functions\n have finished, or an error has occurred.\n\n__Example__\n\n```js\n// Assume documents is an array of JSON objects and requestApi is a\n// function that interacts with a rate-limited REST api.\n\nasync.eachLimit(documents, 20, requestApi, function(err){\n // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n\n### map(arr, iterator, callback)\n\nProduces a new array of values by mapping each value in the given array through\nthe iterator function. The iterator is called with an item from the array and a\ncallback for when it has finished processing. The callback takes 2 arguments, \nan error and the transformed item from the array. If the iterator passes an\nerror to this callback, the main callback for the map function is immediately\ncalled with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order, however\nthe results array will be in the same order as the original array.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err, transformed) which must be called once \n it has completed with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is an array of the\n transformed items from the original array.\n\n__Example__\n\n```js\nasync.map(['file1','file2','file3'], fs.stat, function(err, results){\n // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n\n### mapSeries(arr, iterator, callback)\n\nThe same as map only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n---------------------------------------\n\n\n### mapLimit(arr, limit, iterator, callback)\n\nThe same as map only no more than \"limit\" iterators will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that\n the first \"limit\" iterator functions will complete before any others are \nstarted.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - The maximum number of iterators to run at any time.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err, transformed) which must be called once \n it has completed with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is an array of the\n transformed items from the original array.\n\n__Example__\n\n```js\nasync.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){\n // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n\n### filter(arr, iterator, callback)\n\n__Alias:__ select\n\nReturns a new array of all the values which pass an async truth test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists. This operation is\nperformed in parallel, but the results array will be in the same order as the\noriginal.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback(truthValue) which must be called with a \n boolean argument once it has completed.\n* callback(results) - A callback which is called after all the iterator\n functions have finished.\n\n__Example__\n\n```js\nasync.filter(['file1','file2','file3'], fs.exists, function(results){\n // results now equals an array of the existing files\n});\n```\n\n---------------------------------------\n\n\n### filterSeries(arr, iterator, callback)\n\n__alias:__ selectSeries\n\nThe same as filter only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n---------------------------------------\n\n\n### reject(arr, iterator, callback)\n\nThe opposite of filter. Removes values that pass an async truth test.\n\n---------------------------------------\n\n\n### rejectSeries(arr, iterator, callback)\n\nThe same as reject, only the iterator is applied to each item in the array\nin series.\n\n\n---------------------------------------\n\n\n### reduce(arr, memo, iterator, callback)\n\n__aliases:__ inject, foldl\n\nReduces a list of values into a single value using an async iterator to return\neach successive step. Memo is the initial state of the reduction. This\nfunction only operates in series. For performance reasons, it may make sense to\nsplit a call to this function into a parallel map, then use the normal\nArray.prototype.reduce on the results. This function is for situations where\neach step in the reduction needs to be async, if you can get the data before\nreducing it then it's probably a good idea to do so.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* memo - The initial state of the reduction.\n* iterator(memo, item, callback) - A function applied to each item in the\n array to produce the next step in the reduction. The iterator is passed a\n callback(err, reduction) which accepts an optional error as its first \n argument, and the state of the reduction as the second. If an error is \n passed to the callback, the reduction is stopped and the main callback is \n immediately called with the error.\n* callback(err, result) - A callback which is called after all the iterator\n functions have finished. Result is the reduced value.\n\n__Example__\n\n```js\nasync.reduce([1,2,3], 0, function(memo, item, callback){\n // pointless async:\n process.nextTick(function(){\n callback(null, memo + item)\n });\n}, function(err, result){\n // result is now equal to the last value of memo, which is 6\n});\n```\n\n---------------------------------------\n\n\n### reduceRight(arr, memo, iterator, callback)\n\n__Alias:__ foldr\n\nSame as reduce, only operates on the items in the array in reverse order.\n\n\n---------------------------------------\n\n\n### detect(arr, iterator, callback)\n\nReturns the first value in a list that passes an async truth test. The\niterator is applied in parallel, meaning the first iterator to return true will\nfire the detect callback with that result. That means the result might not be\nthe first item in the original array (in terms of order) that passes the test.\n\nIf order within the original array is important then look at detectSeries.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback(truthValue) which must be called with a \n boolean argument once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n true, or after all the iterator functions have finished. Result will be\n the first item in the array that passes the truth test (iterator) or the\n value undefined if none passed.\n\n__Example__\n\n```js\nasync.detect(['file1','file2','file3'], fs.exists, function(result){\n // result now equals the first file in the list that exists\n});\n```\n\n---------------------------------------\n\n\n### detectSeries(arr, iterator, callback)\n\nThe same as detect, only the iterator is applied to each item in the array\nin series. This means the result is always the first in the original array (in\nterms of array order) that passes the truth test.\n\n\n---------------------------------------\n\n\n### sortBy(arr, iterator, callback)\n\nSorts a list by the results of running each value through an async iterator.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err, sortValue) which must be called once it\n has completed with an error (which can be null) and a value to use as the sort\n criteria.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is the items from\n the original array sorted by the values returned by the iterator calls.\n\n__Example__\n\n```js\nasync.sortBy(['file1','file2','file3'], function(file, callback){\n fs.stat(file, function(err, stats){\n callback(err, stats.mtime);\n });\n}, function(err, results){\n // results is now the original array of files sorted by\n // modified date\n});\n```\n\n---------------------------------------\n\n\n### some(arr, iterator, callback)\n\n__Alias:__ any\n\nReturns true if at least one element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists. Once any iterator\ncall returns true, the main callback is immediately called.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback(truthValue) which must be called with a \n boolean argument once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n true, or after all the iterator functions have finished. Result will be\n either true or false depending on the values of the async tests.\n\n__Example__\n\n```js\nasync.some(['file1','file2','file3'], fs.exists, function(result){\n // if result is true then at least one of the files exists\n});\n```\n\n---------------------------------------\n\n\n### every(arr, iterator, callback)\n\n__Alias:__ all\n\nReturns true if every element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like fs.exists.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback(truthValue) which must be called with a \n boolean argument once it has completed.\n* callback(result) - A callback which is called after all the iterator\n functions have finished. Result will be either true or false depending on\n the values of the async tests.\n\n__Example__\n\n```js\nasync.every(['file1','file2','file3'], fs.exists, function(result){\n // if result is true then every file exists\n});\n```\n\n---------------------------------------\n\n\n### concat(arr, iterator, callback)\n\nApplies an iterator to each item in a list, concatenating the results. Returns the\nconcatenated list. The iterators are called in parallel, and the results are\nconcatenated as they return. There is no guarantee that the results array will\nbe returned in the original order of the arguments passed to the iterator function.\n\n__Arguments__\n\n* arr - An array to iterate over\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err, results) which must be called once it \n has completed with an error (which can be null) and an array of results.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is an array containing\n the concatenated results of the iterator function.\n\n__Example__\n\n```js\nasync.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){\n // files is now a list of filenames that exist in the 3 directories\n});\n```\n\n---------------------------------------\n\n\n### concatSeries(arr, iterator, callback)\n\nSame as async.concat, but executes in series instead of parallel.\n\n\n## Control Flow\n\n\n### series(tasks, [callback])\n\nRun an array of functions in series, each one running once the previous\nfunction has completed. If any functions in the series pass an error to its\ncallback, no more functions are run and the callback for the series is\nimmediately called with the value of the error. Once the tasks have completed,\nthe results are passed to the final callback as an array.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.series.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed\n a callback(err, result) it must call on completion with an error (which can\n be null) and an optional result value.\n* callback(err, results) - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.series([\n function(callback){\n // do some stuff ...\n callback(null, 'one');\n },\n function(callback){\n // do some more stuff ...\n callback(null, 'two');\n }\n],\n// optional callback\nfunction(err, results){\n // results is now equal to ['one', 'two']\n});\n\n\n// an example using an object instead of an array\nasync.series({\n one: function(callback){\n setTimeout(function(){\n callback(null, 1);\n }, 200);\n },\n two: function(callback){\n setTimeout(function(){\n callback(null, 2);\n }, 100);\n }\n},\nfunction(err, results) {\n // results is now equal to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n\n### parallel(tasks, [callback])\n\nRun an array of functions in parallel, without waiting until the previous\nfunction has completed. If any of the functions pass an error to its\ncallback, the main callback is immediately called with the value of the error.\nOnce the tasks have completed, the results are passed to the final callback as an\narray.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.parallel.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed \n a callback(err, result) it must call on completion with an error (which can\n be null) and an optional result value.\n* callback(err, results) - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.parallel([\n function(callback){\n setTimeout(function(){\n callback(null, 'one');\n }, 200);\n },\n function(callback){\n setTimeout(function(){\n callback(null, 'two');\n }, 100);\n }\n],\n// optional callback\nfunction(err, results){\n // the results array will equal ['one','two'] even though\n // the second function had a shorter timeout.\n});\n\n\n// an example using an object instead of an array\nasync.parallel({\n one: function(callback){\n setTimeout(function(){\n callback(null, 1);\n }, 200);\n },\n two: function(callback){\n setTimeout(function(){\n callback(null, 2);\n }, 100);\n }\n},\nfunction(err, results) {\n // results is now equals to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n\n### parallelLimit(tasks, limit, [callback])\n\nThe same as parallel only the tasks are executed in parallel with a maximum of \"limit\" \ntasks executing at any time.\n\nNote that the tasks are not executed in batches, so there is no guarantee that \nthe first \"limit\" tasks will complete before any others are started.\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed \n a callback(err, result) it must call on completion with an error (which can\n be null) and an optional result value.\n* limit - The maximum number of tasks to run at any time.\n* callback(err, results) - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the task callbacks.\n\n---------------------------------------\n\n\n### whilst(test, fn, callback)\n\nRepeatedly call fn, while test returns true. Calls the callback when stopped,\nor an error occurs.\n\n__Arguments__\n\n* test() - synchronous truth test to perform before each execution of fn.\n* fn(callback) - A function to call each time the test passes. The function is\n passed a callback(err) which must be called once it has completed with an \n optional error argument.\n* callback(err) - A callback which is called after the test fails and repeated\n execution of fn has stopped.\n\n__Example__\n\n```js\nvar count = 0;\n\nasync.whilst(\n function () { return count < 5; },\n function (callback) {\n count++;\n setTimeout(callback, 1000);\n },\n function (err) {\n // 5 seconds have passed\n }\n);\n```\n\n---------------------------------------\n\n\n### doWhilst(fn, test, callback)\n\nThe post check version of whilst. To reflect the difference in the order of operations `test` and `fn` arguments are switched. `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.\n\n---------------------------------------\n\n\n### until(test, fn, callback)\n\nRepeatedly call fn, until test returns true. Calls the callback when stopped,\nor an error occurs.\n\nThe inverse of async.whilst.\n\n---------------------------------------\n\n\n### doUntil(fn, test, callback)\n\nLike doWhilst except the test is inverted. Note the argument ordering differs from `until`.\n\n---------------------------------------\n\n\n### forever(fn, callback)\n\nCalls the asynchronous function 'fn' repeatedly, in series, indefinitely.\nIf an error is passed to fn's callback then 'callback' is called with the\nerror, otherwise it will never be called.\n\n---------------------------------------\n\n\n### waterfall(tasks, [callback])\n\nRuns an array of functions in series, each passing their results to the next in\nthe array. However, if any of the functions pass an error to the callback, the\nnext function is not executed and the main callback is immediately called with\nthe error.\n\n__Arguments__\n\n* tasks - An array of functions to run, each function is passed a \n callback(err, result1, result2, ...) it must call on completion. The first\n argument is an error (which can be null) and any further arguments will be \n passed as arguments in order to the next task.\n* callback(err, [results]) - An optional callback to run once all the functions\n have completed. This will be passed the results of the last task's callback.\n\n\n\n__Example__\n\n```js\nasync.waterfall([\n function(callback){\n callback(null, 'one', 'two');\n },\n function(arg1, arg2, callback){\n callback(null, 'three');\n },\n function(arg1, callback){\n // arg1 now equals 'three'\n callback(null, 'done');\n }\n], function (err, result) {\n // result now equals 'done' \n});\n```\n\n---------------------------------------\n\n### compose(fn1, fn2...)\n\nCreates a function which is a composition of the passed asynchronous\nfunctions. Each function consumes the return value of the function that\nfollows. Composing functions f(), g() and h() would produce the result of\nf(g(h())), only this version uses callbacks to obtain the return values.\n\nEach function is executed with the `this` binding of the composed function.\n\n__Arguments__\n\n* functions... - the asynchronous functions to compose\n\n\n__Example__\n\n```js\nfunction add1(n, callback) {\n setTimeout(function () {\n callback(null, n + 1);\n }, 10);\n}\n\nfunction mul3(n, callback) {\n setTimeout(function () {\n callback(null, n * 3);\n }, 10);\n}\n\nvar add1mul3 = async.compose(mul3, add1);\n\nadd1mul3(4, function (err, result) {\n // result now equals 15\n});\n```\n\n---------------------------------------\n\n### applyEach(fns, args..., callback)\n\nApplies the provided arguments to each function in the array, calling the\ncallback after all functions have completed. If you only provide the first\nargument then it will return a function which lets you pass in the\narguments as if it were a single function call.\n\n__Arguments__\n\n* fns - the asynchronous functions to all call with the same arguments\n* args... - any number of separate arguments to pass to the function\n* callback - the final argument should be the callback, called when all\n functions have completed processing\n\n\n__Example__\n\n```js\nasync.applyEach([enableSearch, updateSchema], 'bucket', callback);\n\n// partial application example:\nasync.each(\n buckets,\n async.applyEach([enableSearch, updateSchema]),\n callback\n);\n```\n\n---------------------------------------\n\n\n### applyEachSeries(arr, iterator, callback)\n\nThe same as applyEach only the functions are applied in series.\n\n---------------------------------------\n\n\n### queue(worker, concurrency)\n\nCreates a queue object with the specified concurrency. Tasks added to the\nqueue will be processed in parallel (up to the concurrency limit). If all\nworkers are in progress, the task is queued until one is available. Once\na worker has completed a task, the task's callback is called.\n\n__Arguments__\n\n* worker(task, callback) - An asynchronous function for processing a queued\n task, which must call its callback(err) argument when finished, with an \n optional error as an argument.\n* concurrency - An integer for determining how many worker functions should be\n run in parallel.\n\n__Queue objects__\n\nThe queue object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* concurrency - an integer for determining how many worker functions should be\n run in parallel. This property can be changed after a queue is created to\n alter the concurrency on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n once the worker has finished processing the task.\n instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* unshift(task, [callback]) - add a new task to the front of the queue.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n```js\n// create a queue object with concurrency 2\n\nvar q = async.queue(function (task, callback) {\n console.log('hello ' + task.name);\n callback();\n}, 2);\n\n\n// assign a callback\nq.drain = function() {\n console.log('all items have been processed');\n}\n\n// add some items to the queue\n\nq.push({name: 'foo'}, function (err) {\n console.log('finished processing foo');\n});\nq.push({name: 'bar'}, function (err) {\n console.log('finished processing bar');\n});\n\n// add some items to the queue (batch-wise)\n\nq.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {\n console.log('finished processing bar');\n});\n\n// add some items to the front of the queue\n\nq.unshift({name: 'bar'}, function (err) {\n console.log('finished processing bar');\n});\n```\n\n---------------------------------------\n\n\n### cargo(worker, [payload])\n\nCreates a cargo object with the specified payload. Tasks added to the\ncargo will be processed altogether (up to the payload limit). If the\nworker is in progress, the task is queued until it is available. Once\nthe worker has completed some tasks, each callback of those tasks is called.\n\n__Arguments__\n\n* worker(tasks, callback) - An asynchronous function for processing an array of\n queued tasks, which must call its callback(err) argument when finished, with \n an optional error as an argument.\n* payload - An optional integer for determining how many tasks should be\n processed per round; if omitted, the default is unlimited.\n\n__Cargo objects__\n\nThe cargo object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* payload - an integer for determining how many tasks should be\n process per round. This property can be changed after a cargo is created to\n alter the payload on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n once the worker has finished processing the task.\n instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n```js\n// create a cargo object with payload 2\n\nvar cargo = async.cargo(function (tasks, callback) {\n for(var i=0; i\n### auto(tasks, [callback])\n\nDetermines the best order for running functions based on their requirements.\nEach function can optionally depend on other functions being completed first,\nand each function is run as soon as its requirements are satisfied. If any of\nthe functions pass an error to their callback, that function will not complete\n(so any other functions depending on it will not run) and the main callback\nwill be called immediately with the error. Functions also receive an object\ncontaining the results of functions which have completed so far.\n\nNote, all functions are called with a results object as a second argument, \nso it is unsafe to pass functions in the tasks object which cannot handle the\nextra argument. For example, this snippet of code:\n\n```js\nasync.auto({\n readData: async.apply(fs.readFile, 'data.txt', 'utf-8')\n}, callback);\n```\n\nwill have the effect of calling readFile with the results object as the last\nargument, which will fail:\n\n```js\nfs.readFile('data.txt', 'utf-8', cb, {});\n```\n\nInstead, wrap the call to readFile in a function which does not forward the \nresults object:\n\n```js\nasync.auto({\n readData: function(cb, results){\n fs.readFile('data.txt', 'utf-8', cb);\n }\n}, callback);\n```\n\n__Arguments__\n\n* tasks - An object literal containing named functions or an array of\n requirements, with the function itself the last item in the array. The key\n used for each function or array is used when specifying requirements. The \n function receives two arguments: (1) a callback(err, result) which must be \n called when finished, passing an error (which can be null) and the result of \n the function's execution, and (2) a results object, containing the results of\n the previously executed functions.\n* callback(err, results) - An optional callback which is called when all the\n tasks have been completed. The callback will receive an error as an argument\n if any tasks pass an error to their callback. Results will always be passed\n\tbut if an error occurred, no other tasks will be performed, and the results\n\tobject will only contain partial results.\n \n\n__Example__\n\n```js\nasync.auto({\n get_data: function(callback){\n // async code to get some data\n },\n make_folder: function(callback){\n // async code to create a directory to store a file in\n // this is run at the same time as getting the data\n },\n write_file: ['get_data', 'make_folder', function(callback){\n // once there is some data and the directory exists,\n // write the data to a file in the directory\n callback(null, filename);\n }],\n email_link: ['write_file', function(callback, results){\n // once the file is written let's email a link to it...\n // results.write_file contains the filename returned by write_file.\n }]\n});\n```\n\nThis is a fairly trivial example, but to do this using the basic parallel and\nseries functions would look like this:\n\n```js\nasync.parallel([\n function(callback){\n // async code to get some data\n },\n function(callback){\n // async code to create a directory to store a file in\n // this is run at the same time as getting the data\n }\n],\nfunction(err, results){\n async.series([\n function(callback){\n // once there is some data and the directory exists,\n // write the data to a file in the directory\n },\n function(callback){\n // once the file is written let's email a link to it...\n }\n ]);\n});\n```\n\nFor a complicated series of async tasks using the auto function makes adding\nnew tasks much easier and makes the code more readable.\n\n\n---------------------------------------\n\n\n### iterator(tasks)\n\nCreates an iterator function which calls the next function in the array,\nreturning a continuation to call the next one after that. It's also possible to\n'peek' the next iterator by doing iterator.next().\n\nThis function is used internally by the async module but can be useful when\nyou want to manually control the flow of functions in series.\n\n__Arguments__\n\n* tasks - An array of functions to run.\n\n__Example__\n\n```js\nvar iterator = async.iterator([\n function(){ sys.p('one'); },\n function(){ sys.p('two'); },\n function(){ sys.p('three'); }\n]);\n\nnode> var iterator2 = iterator();\n'one'\nnode> var iterator3 = iterator2();\n'two'\nnode> iterator3();\n'three'\nnode> var nextfn = iterator2.next();\nnode> nextfn();\n'three'\n```\n\n---------------------------------------\n\n\n### apply(function, arguments..)\n\nCreates a continuation function with some arguments already applied, a useful\nshorthand when combined with other control flow functions. Any arguments\npassed to the returned function are added to the arguments originally passed\nto apply.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to automatically apply when the\n continuation is called.\n\n__Example__\n\n```js\n// using apply\n\nasync.parallel([\n async.apply(fs.writeFile, 'testfile1', 'test1'),\n async.apply(fs.writeFile, 'testfile2', 'test2'),\n]);\n\n\n// the same process without using apply\n\nasync.parallel([\n function(callback){\n fs.writeFile('testfile1', 'test1', callback);\n },\n function(callback){\n fs.writeFile('testfile2', 'test2', callback);\n }\n]);\n```\n\nIt's possible to pass any number of additional arguments when calling the\ncontinuation:\n\n```js\nnode> var fn = async.apply(sys.puts, 'one');\nnode> fn('two', 'three');\none\ntwo\nthree\n```\n\n---------------------------------------\n\n\n### nextTick(callback)\n\nCalls the callback on a later loop around the event loop. In node.js this just\ncalls process.nextTick, in the browser it falls back to setImmediate(callback)\nif available, otherwise setTimeout(callback, 0), which means other higher priority\nevents may precede the execution of the callback.\n\nThis is used internally for browser-compatibility purposes.\n\n__Arguments__\n\n* callback - The function to call on a later loop around the event loop.\n\n__Example__\n\n```js\nvar call_order = [];\nasync.nextTick(function(){\n call_order.push('two');\n // call_order now equals ['one','two']\n});\ncall_order.push('one')\n```\n\n\n### times(n, callback)\n\nCalls the callback n times and accumulates results in the same manner\nyou would use with async.map.\n\n__Arguments__\n\n* n - The number of times to run the function.\n* callback - The function to call n times.\n\n__Example__\n\n```js\n// Pretend this is some complicated async factory\nvar createUser = function(id, callback) {\n callback(null, {\n id: 'user' + id\n })\n}\n// generate 5 users\nasync.times(5, function(n, next){\n createUser(n, function(err, user) {\n next(err, user)\n })\n}, function(err, users) {\n // we should now have 5 users\n});\n```\n\n\n### timesSeries(n, callback)\n\nThe same as times only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n## Utils\n\n\n### memoize(fn, [hasher])\n\nCaches the results of an async function. When creating a hash to store function\nresults against, the callback is omitted from the hash and an optional hash\nfunction can be used.\n\nThe cache of results is exposed as the `memo` property of the function returned\nby `memoize`.\n\n__Arguments__\n\n* fn - the function you to proxy and cache results from.\n* hasher - an optional function for generating a custom hash for storing\n results, it has all the arguments applied to it apart from the callback, and\n must be synchronous.\n\n__Example__\n\n```js\nvar slow_fn = function (name, callback) {\n // do something\n callback(null, result);\n};\nvar fn = async.memoize(slow_fn);\n\n// fn can now be used as if it were slow_fn\nfn('some name', function () {\n // callback\n});\n```\n\n\n### unmemoize(fn)\n\nUndoes a memoized function, reverting it to the original, unmemoized\nform. Comes handy in tests.\n\n__Arguments__\n\n* fn - the memoized function\n\n\n### log(function, arguments)\n\nLogs the result of an async function to the console. Only works in node.js or\nin browsers that support console.log and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.log is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n setTimeout(function(){\n callback(null, 'hello ' + name);\n }, 1000);\n};\n```\n```js\nnode> async.log(hello, 'world');\n'hello world'\n```\n\n---------------------------------------\n\n\n### dir(function, arguments)\n\nLogs the result of an async function to the console using console.dir to\ndisplay the properties of the resulting object. Only works in node.js or\nin browsers that support console.dir and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.dir is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n setTimeout(function(){\n callback(null, {hello: name});\n }, 1000);\n};\n```\n```js\nnode> async.dir(hello, 'world');\n{hello: 'world'}\n```\n\n---------------------------------------\n\n\n### noConflict()\n\nChanges the value of async back to its original value, returning a reference to the\nasync object.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/caolan/async", - "_id": "async@0.2.10", - "dist": { - "shasum": "6fd106274306f9b5343b1502a0cb4377cfd72dac" - }, - "_from": "async@~0.2", - "_resolved": "https://registry.npmjs.org/async/-/async-0.2.10.tgz" -} diff --git a/node_modules/express3-handlebars/node_modules/glob/.npmignore b/node_modules/express3-handlebars/node_modules/glob/.npmignore deleted file mode 100644 index 2af4b71c9..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -.*.swp -test/a/ diff --git a/node_modules/express3-handlebars/node_modules/glob/.travis.yml b/node_modules/express3-handlebars/node_modules/glob/.travis.yml deleted file mode 100644 index baa0031d5..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: node_js -node_js: - - 0.8 diff --git a/node_modules/express3-handlebars/node_modules/glob/LICENSE b/node_modules/express3-handlebars/node_modules/glob/LICENSE deleted file mode 100644 index 0c44ae716..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) Isaac Z. Schlueter ("Author") -All rights reserved. - -The BSD License - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/express3-handlebars/node_modules/glob/README.md b/node_modules/express3-handlebars/node_modules/glob/README.md deleted file mode 100644 index cc6916451..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/README.md +++ /dev/null @@ -1,250 +0,0 @@ -# Glob - -Match files using the patterns the shell uses, like stars and stuff. - -This is a glob implementation in JavaScript. It uses the `minimatch` -library to do its matching. - -## Attention: node-glob users! - -The API has changed dramatically between 2.x and 3.x. This library is -now 100% JavaScript, and the integer flags have been replaced with an -options object. - -Also, there's an event emitter class, proper tests, and all the other -things you've come to expect from node modules. - -And best of all, no compilation! - -## Usage - -```javascript -var glob = require("glob") - -// options is optional -glob("**/*.js", options, function (er, files) { - // files is an array of filenames. - // If the `nonull` option is set, and nothing - // was found, then files is ["**/*.js"] - // er is an error object or null. -}) -``` - -## Features - -Please see the [minimatch -documentation](https://github.com/isaacs/minimatch) for more details. - -Supports these glob features: - -* Brace Expansion -* Extended glob matching -* "Globstar" `**` matching - -See: - -* `man sh` -* `man bash` -* `man 3 fnmatch` -* `man 5 gitignore` -* [minimatch documentation](https://github.com/isaacs/minimatch) - -## glob(pattern, [options], cb) - -* `pattern` {String} Pattern to be matched -* `options` {Object} -* `cb` {Function} - * `err` {Error | null} - * `matches` {Array} filenames found matching the pattern - -Perform an asynchronous glob search. - -## glob.sync(pattern, [options]) - -* `pattern` {String} Pattern to be matched -* `options` {Object} -* return: {Array} filenames found matching the pattern - -Perform a synchronous glob search. - -## Class: glob.Glob - -Create a Glob object by instanting the `glob.Glob` class. - -```javascript -var Glob = require("glob").Glob -var mg = new Glob(pattern, options, cb) -``` - -It's an EventEmitter, and starts walking the filesystem to find matches -immediately. - -### new glob.Glob(pattern, [options], [cb]) - -* `pattern` {String} pattern to search for -* `options` {Object} -* `cb` {Function} Called when an error occurs, or matches are found - * `err` {Error | null} - * `matches` {Array} filenames found matching the pattern - -Note that if the `sync` flag is set in the options, then matches will -be immediately available on the `g.found` member. - -### Properties - -* `minimatch` The minimatch object that the glob uses. -* `options` The options object passed in. -* `error` The error encountered. When an error is encountered, the - glob object is in an undefined state, and should be discarded. -* `aborted` Boolean which is set to true when calling `abort()`. There - is no way at this time to continue a glob search after aborting, but - you can re-use the statCache to avoid having to duplicate syscalls. -* `statCache` Collection of all the stat results the glob search - performed. -* `cache` Convenience object. Each field has the following possible - values: - * `false` - Path does not exist - * `true` - Path exists - * `1` - Path exists, and is not a directory - * `2` - Path exists, and is a directory - * `[file, entries, ...]` - Path exists, is a directory, and the - array value is the results of `fs.readdir` - -### Events - -* `end` When the matching is finished, this is emitted with all the - matches found. If the `nonull` option is set, and no match was found, - then the `matches` list contains the original pattern. The matches - are sorted, unless the `nosort` flag is set. -* `match` Every time a match is found, this is emitted with the matched. -* `error` Emitted when an unexpected error is encountered, or whenever - any fs error occurs if `options.strict` is set. -* `abort` When `abort()` is called, this event is raised. - -### Methods - -* `abort` Stop the search. - -### Options - -All the options that can be passed to Minimatch can also be passed to -Glob to change pattern matching behavior. Also, some have been added, -or have glob-specific ramifications. - -All options are false by default, unless otherwise noted. - -All options are added to the glob object, as well. - -* `cwd` The current working directory in which to search. Defaults - to `process.cwd()`. -* `root` The place where patterns starting with `/` will be mounted - onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix - systems, and `C:\` or some such on Windows.) -* `dot` Include `.dot` files in normal matches and `globstar` matches. - Note that an explicit dot in a portion of the pattern will always - match dot files. -* `nomount` By default, a pattern starting with a forward-slash will be - "mounted" onto the root setting, so that a valid filesystem path is - returned. Set this flag to disable that behavior. -* `mark` Add a `/` character to directory matches. Note that this - requires additional stat calls. -* `nosort` Don't sort the results. -* `stat` Set to true to stat *all* results. This reduces performance - somewhat, and is completely unnecessary, unless `readdir` is presumed - to be an untrustworthy indicator of file existence. It will cause - ELOOP to be triggered one level sooner in the case of cyclical - symbolic links. -* `silent` When an unusual error is encountered - when attempting to read a directory, a warning will be printed to - stderr. Set the `silent` option to true to suppress these warnings. -* `strict` When an unusual error is encountered - when attempting to read a directory, the process will just continue on - in search of other matches. Set the `strict` option to raise an error - in these cases. -* `cache` See `cache` property above. Pass in a previously generated - cache object to save some fs calls. -* `statCache` A cache of results of filesystem information, to prevent - unnecessary stat calls. While it should not normally be necessary to - set this, you may pass the statCache from one glob() call to the - options object of another, if you know that the filesystem will not - change between calls. (See "Race Conditions" below.) -* `sync` Perform a synchronous glob search. -* `nounique` In some cases, brace-expanded patterns can result in the - same file showing up multiple times in the result set. By default, - this implementation prevents duplicates in the result set. - Set this flag to disable that behavior. -* `nonull` Set to never return an empty set, instead returning a set - containing the pattern itself. This is the default in glob(3). -* `nocase` Perform a case-insensitive match. Note that case-insensitive - filesystems will sometimes result in glob returning results that are - case-insensitively matched anyway, since readdir and stat will not - raise an error. -* `debug` Set to enable debug logging in minimatch and glob. -* `globDebug` Set to enable debug logging in glob, but not minimatch. - -## Comparisons to other fnmatch/glob implementations - -While strict compliance with the existing standards is a worthwhile -goal, some discrepancies exist between node-glob and other -implementations, and are intentional. - -If the pattern starts with a `!` character, then it is negated. Set the -`nonegate` flag to suppress this behavior, and treat leading `!` -characters normally. This is perhaps relevant if you wish to start the -pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` -characters at the start of a pattern will negate the pattern multiple -times. - -If a pattern starts with `#`, then it is treated as a comment, and -will not match anything. Use `\#` to match a literal `#` at the -start of a line, or set the `nocomment` flag to suppress this behavior. - -The double-star character `**` is supported by default, unless the -`noglobstar` flag is set. This is supported in the manner of bsdglob -and bash 4.1, where `**` only has special significance if it is the only -thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but -`a/**b` will not. - -If an escaped pattern has no matches, and the `nonull` flag is set, -then glob returns the pattern as-provided, rather than -interpreting the character escapes. For example, -`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than -`"*a?"`. This is akin to setting the `nullglob` option in bash, except -that it does not resolve escaped pattern characters. - -If brace expansion is not disabled, then it is performed before any -other interpretation of the glob pattern. Thus, a pattern like -`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded -**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are -checked for validity. Since those two are valid, matching proceeds. - -## Windows - -**Please only use forward-slashes in glob expressions.** - -Though windows uses either `/` or `\` as its path separator, only `/` -characters are used by this glob implementation. You must use -forward-slashes **only** in glob expressions. Back-slashes will always -be interpreted as escape characters, not path separators. - -Results from absolute patterns such as `/foo/*` are mounted onto the -root setting using `path.join`. On windows, this will by default result -in `/foo/*` matching `C:\foo\bar.txt`. - -## Race Conditions - -Glob searching, by its very nature, is susceptible to race conditions, -since it relies on directory walking and such. - -As a result, it is possible that a file that exists when glob looks for -it may have been deleted or modified by the time it returns the result. - -As part of its internal implementation, this program caches all stat -and readdir calls that it makes, in order to cut down on system -overhead. However, this also makes it even more susceptible to races, -especially if the cache or statCache objects are reused between glob -calls. - -Users are thus advised not to use a glob result as a guarantee of -filesystem state in the face of rapid changes. For the vast majority -of operations, this is never a problem. diff --git a/node_modules/express3-handlebars/node_modules/glob/examples/g.js b/node_modules/express3-handlebars/node_modules/glob/examples/g.js deleted file mode 100644 index be122df00..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/examples/g.js +++ /dev/null @@ -1,9 +0,0 @@ -var Glob = require("../").Glob - -var pattern = "test/a/**/[cg]/../[cg]" -console.log(pattern) - -var mg = new Glob(pattern, {mark: true, sync:true}, function (er, matches) { - console.log("matches", matches) -}) -console.log("after") diff --git a/node_modules/express3-handlebars/node_modules/glob/examples/usr-local.js b/node_modules/express3-handlebars/node_modules/glob/examples/usr-local.js deleted file mode 100644 index 327a425e4..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/examples/usr-local.js +++ /dev/null @@ -1,9 +0,0 @@ -var Glob = require("../").Glob - -var pattern = "{./*/*,/*,/usr/local/*}" -console.log(pattern) - -var mg = new Glob(pattern, {mark: true}, function (er, matches) { - console.log("matches", matches) -}) -console.log("after") diff --git a/node_modules/express3-handlebars/node_modules/glob/glob.js b/node_modules/express3-handlebars/node_modules/glob/glob.js deleted file mode 100644 index f4c69e973..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/glob.js +++ /dev/null @@ -1,690 +0,0 @@ -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// readdir(PREFIX) as ENTRIES -// If fails, END -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $]) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $]) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. - - - -module.exports = glob - -var fs = require("fs") -, minimatch = require("minimatch") -, Minimatch = minimatch.Minimatch -, inherits = require("inherits") -, EE = require("events").EventEmitter -, path = require("path") -, isDir = {} -, assert = require("assert").ok - -function glob (pattern, options, cb) { - if (typeof options === "function") cb = options, options = {} - if (!options) options = {} - - if (typeof options === "number") { - deprecated() - return - } - - var g = new Glob(pattern, options, cb) - return g.sync ? g.found : g -} - -glob.fnmatch = deprecated - -function deprecated () { - throw new Error("glob's interface has changed. Please see the docs.") -} - -glob.sync = globSync -function globSync (pattern, options) { - if (typeof options === "number") { - deprecated() - return - } - - options = options || {} - options.sync = true - return glob(pattern, options) -} - - -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (!(this instanceof Glob)) { - return new Glob(pattern, options, cb) - } - - if (typeof options === "function") { - cb = options - options = null - } - - if (typeof cb === "function") { - this.on("error", cb) - this.on("end", function (matches) { - cb(null, matches) - }) - } - - options = options || {} - - this.EOF = {} - this._emitQueue = [] - - this.maxDepth = options.maxDepth || 1000 - this.maxLength = options.maxLength || Infinity - this.cache = options.cache || {} - this.statCache = options.statCache || {} - - this.changedCwd = false - var cwd = process.cwd() - if (!options.hasOwnProperty("cwd")) this.cwd = cwd - else { - this.cwd = options.cwd - this.changedCwd = path.resolve(options.cwd) !== cwd - } - - this.root = options.root || path.resolve(this.cwd, "/") - this.root = path.resolve(this.root) - if (process.platform === "win32") - this.root = this.root.replace(/\\/g, "/") - - this.nomount = !!options.nomount - - if (!pattern) { - throw new Error("must provide pattern") - } - - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern - } - - this.strict = options.strict !== false - this.dot = !!options.dot - this.mark = !!options.mark - this.sync = !!options.sync - this.nounique = !!options.nounique - this.nonull = !!options.nonull - this.nosort = !!options.nosort - this.nocase = !!options.nocase - this.stat = !!options.stat - - this.debug = !!options.debug || !!options.globDebug - if (this.debug) - this.log = console.error - - this.silent = !!options.silent - - var mm = this.minimatch = new Minimatch(pattern, options) - this.options = mm.options - pattern = this.pattern = mm.pattern - - this.error = null - this.aborted = false - - // list of all the patterns that ** has resolved do, so - // we can avoid visiting multiple times. - this._globstars = {} - - EE.call(this) - - // process each pattern in the minimatch set - var n = this.minimatch.set.length - - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) - - this.minimatch.set.forEach(iterator.bind(this)) - function iterator (pattern, i, set) { - this._process(pattern, 0, i, function (er) { - if (er) this.emit("error", er) - if (-- n <= 0) this._finish() - }) - } -} - -Glob.prototype.log = function () {} - -Glob.prototype._finish = function () { - assert(this instanceof Glob) - - var nou = this.nounique - , all = nou ? [] : {} - - for (var i = 0, l = this.matches.length; i < l; i ++) { - var matches = this.matches[i] - this.log("matches[%d] =", i, matches) - // do like the shell, and spit out the literal glob - if (!matches) { - if (this.nonull) { - var literal = this.minimatch.globSet[i] - if (nou) all.push(literal) - else all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) all.push.apply(all, m) - else m.forEach(function (m) { - all[m] = true - }) - } - } - - if (!nou) all = Object.keys(all) - - if (!this.nosort) { - all = all.sort(this.nocase ? alphasorti : alphasort) - } - - this.log("emitting end", all) - - this.EOF = this.found = all - this.emitMatch(this.EOF, -1) -} - -function alphasorti (a, b) { - a = a.toLowerCase() - b = b.toLowerCase() - return alphasort(a, b) -} - -function alphasort (a, b) { - return a > b ? 1 : a < b ? -1 : 0 -} - -Glob.prototype.abort = function () { - this.aborted = true - this.emit("abort") -} - -Glob.prototype.pause = function () { - if (this.paused) return - if (this.sync) - this.emit("error", new Error("Can't pause/resume sync glob")) - this.paused = true - this.emit("pause") -} - -Glob.prototype.resume = function () { - if (!this.paused) return - if (this.sync) - this.emit("error", new Error("Can't pause/resume sync glob")) - this.paused = false - this.emit("resume") - this._processEmitQueue() - //process.nextTick(this.emit.bind(this, "resume")) -} - -Glob.prototype._mark = function (p) { - var c = this.cache[p] - var m = p - if (c) { - var isDir = c === 2 || Array.isArray(c) - var slash = p.slice(-1) === '/' - - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) - - if (m !== p) { - this.statCache[m] = this.statCache[p] - this.cache[m] = this.cache[p] - } - } - - return m -} - -Glob.prototype._pushMatch = function(m, index) { - if (this.mark && m !== this.EOF) - m = this._mark(m) - - if (m !== this.EOF) { - this.matches[index] = this.matches[index] || {} - this.matches[index][m] = true - } - - this._emitQueue.push(m) - this._processEmitQueue() -} - -Glob.prototype.emitMatch = function (m, index) { - if ((!this.stat && !this.mark) || this.statCache[m] || m === this.EOF) { - this._pushMatch(m, index) - } else { - this._stat(m, function(exists, isDir) { - if (exists) - this._pushMatch(m, index) - }) - } -} - -Glob.prototype._processEmitQueue = function (m) { - while (!this._processingEmitQueue && - !this.paused) { - this._processingEmitQueue = true - var m = this._emitQueue.shift() - if (!m) { - this._processingEmitQueue = false - break - } - - this.log('emit!', m === this.EOF ? "end" : "match") - - this.emit(m === this.EOF ? "end" : "match", m) - this._processingEmitQueue = false - } -} - -Glob.prototype._process = function (pattern, depth, index, cb_) { - assert(this instanceof Glob) - - var cb = function cb (er, res) { - assert(this instanceof Glob) - if (this.paused) { - if (!this._processQueue) { - this._processQueue = [] - this.once("resume", function () { - var q = this._processQueue - this._processQueue = null - q.forEach(function (cb) { cb() }) - }) - } - this._processQueue.push(cb_.bind(this, er, res)) - } else { - cb_.call(this, er, res) - } - }.bind(this) - - if (this.aborted) return cb() - - if (depth > this.maxDepth) return cb() - - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === "string") { - n ++ - } - // now n is the index of the first one that is *not* a string. - - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - prefix = pattern.join("/") - this._stat(prefix, function (exists, isDir) { - // either it's there, or it isn't. - // nothing more to do, either way. - if (exists) { - if (prefix && isAbsolute(prefix) && !this.nomount) { - if (prefix.charAt(0) === "/") { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - } - } - - if (process.platform === "win32") - prefix = prefix.replace(/\\/g, "/") - - this.emitMatch(prefix, index) - } - return cb() - }) - return - - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break - - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's "absolute" like /foo/bar, - // or "relative" like "../baz" - prefix = pattern.slice(0, n) - prefix = prefix.join("/") - break - } - - // get the list of entries. - var read - if (prefix === null) read = "." - else if (isAbsolute(prefix) || isAbsolute(pattern.join("/"))) { - if (!prefix || !isAbsolute(prefix)) { - prefix = path.join("/", prefix) - } - read = prefix = path.resolve(prefix) - - // if (process.platform === "win32") - // read = prefix = prefix.replace(/^[a-zA-Z]:|\\/g, "/") - - this.log('absolute: ', prefix, this.root, pattern, read) - } else { - read = prefix - } - - this.log('readdir(%j)', read, this.cwd, this.root) - - return this._readdir(read, function (er, entries) { - if (er) { - // not a directory! - // this means that, whatever else comes after this, it can never match - return cb() - } - - // globstar is special - if (pattern[n] === minimatch.GLOBSTAR) { - // test without the globstar, and with every child both below - // and replacing the globstar. - var s = [ pattern.slice(0, n).concat(pattern.slice(n + 1)) ] - entries.forEach(function (e) { - if (e.charAt(0) === "." && !this.dot) return - // instead of the globstar - s.push(pattern.slice(0, n).concat(e).concat(pattern.slice(n + 1))) - // below the globstar - s.push(pattern.slice(0, n).concat(e).concat(pattern.slice(n))) - }, this) - - s = s.filter(function (pattern) { - var key = gsKey(pattern) - var seen = !this._globstars[key] - this._globstars[key] = true - return seen - }, this) - - if (!s.length) - return cb() - - // now asyncForEach over this - var l = s.length - , errState = null - s.forEach(function (gsPattern) { - this._process(gsPattern, depth + 1, index, function (er) { - if (errState) return - if (er) return cb(errState = er) - if (--l <= 0) return cb() - }) - }, this) - - return - } - - // not a globstar - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = pattern[n] - var rawGlob = pattern[n]._glob - , dotOk = this.dot || rawGlob.charAt(0) === "." - - entries = entries.filter(function (e) { - return (e.charAt(0) !== "." || dotOk) && - e.match(pattern[n]) - }) - - // If n === pattern.length - 1, then there's no need for the extra stat - // *unless* the user has specified "mark" or "stat" explicitly. - // We know that they exist, since the readdir returned them. - if (n === pattern.length - 1 && - !this.mark && - !this.stat) { - entries.forEach(function (e) { - if (prefix) { - if (prefix !== "/") e = prefix + "/" + e - else e = prefix + e - } - if (e.charAt(0) === "/" && !this.nomount) { - e = path.join(this.root, e) - } - - if (process.platform === "win32") - e = e.replace(/\\/g, "/") - - this.emitMatch(e, index) - }, this) - return cb.call(this) - } - - - // now test all the remaining entries as stand-ins for that part - // of the pattern. - var l = entries.length - , errState = null - if (l === 0) return cb() // no matches possible - entries.forEach(function (e) { - var p = pattern.slice(0, n).concat(e).concat(pattern.slice(n + 1)) - this._process(p, depth + 1, index, function (er) { - if (errState) return - if (er) return cb(errState = er) - if (--l === 0) return cb.call(this) - }) - }, this) - }) - -} - -function gsKey (pattern) { - return '**' + pattern.map(function (p) { - return (p === minimatch.GLOBSTAR) ? '**' : (''+p) - }).join('/') -} - -Glob.prototype._stat = function (f, cb) { - assert(this instanceof Glob) - var abs = f - if (f.charAt(0) === "/") { - abs = path.join(this.root, f) - } else if (this.changedCwd) { - abs = path.resolve(this.cwd, f) - } - - if (f.length > this.maxLength) { - var er = new Error("Path name too long") - er.code = "ENAMETOOLONG" - er.path = f - return this._afterStat(f, abs, cb, er) - } - - this.log('stat', [this.cwd, f, '=', abs]) - - if (!this.stat && this.cache.hasOwnProperty(f)) { - var exists = this.cache[f] - , isDir = exists && (Array.isArray(exists) || exists === 2) - if (this.sync) return cb.call(this, !!exists, isDir) - return process.nextTick(cb.bind(this, !!exists, isDir)) - } - - var stat = this.statCache[abs] - if (this.sync || stat) { - var er - try { - stat = fs.statSync(abs) - } catch (e) { - er = e - } - this._afterStat(f, abs, cb, er, stat) - } else { - fs.stat(abs, this._afterStat.bind(this, f, abs, cb)) - } -} - -Glob.prototype._afterStat = function (f, abs, cb, er, stat) { - var exists - assert(this instanceof Glob) - - if (abs.slice(-1) === "/" && stat && !stat.isDirectory()) { - this.log("should be ENOTDIR, fake it") - - er = new Error("ENOTDIR, not a directory '" + abs + "'") - er.path = abs - er.code = "ENOTDIR" - stat = null - } - - var emit = !this.statCache[abs] - this.statCache[abs] = stat - - if (er || !stat) { - exists = false - } else { - exists = stat.isDirectory() ? 2 : 1 - if (emit) - this.emit('stat', f, stat) - } - this.cache[f] = this.cache[f] || exists - cb.call(this, !!exists, exists === 2) -} - -Glob.prototype._readdir = function (f, cb) { - assert(this instanceof Glob) - var abs = f - if (f.charAt(0) === "/") { - abs = path.join(this.root, f) - } else if (isAbsolute(f)) { - abs = f - } else if (this.changedCwd) { - abs = path.resolve(this.cwd, f) - } - - if (f.length > this.maxLength) { - var er = new Error("Path name too long") - er.code = "ENAMETOOLONG" - er.path = f - return this._afterReaddir(f, abs, cb, er) - } - - this.log('readdir', [this.cwd, f, abs]) - if (this.cache.hasOwnProperty(f)) { - var c = this.cache[f] - if (Array.isArray(c)) { - if (this.sync) return cb.call(this, null, c) - return process.nextTick(cb.bind(this, null, c)) - } - - if (!c || c === 1) { - // either ENOENT or ENOTDIR - var code = c ? "ENOTDIR" : "ENOENT" - , er = new Error((c ? "Not a directory" : "Not found") + ": " + f) - er.path = f - er.code = code - this.log(f, er) - if (this.sync) return cb.call(this, er) - return process.nextTick(cb.bind(this, er)) - } - - // at this point, c === 2, meaning it's a dir, but we haven't - // had to read it yet, or c === true, meaning it's *something* - // but we don't have any idea what. Need to read it, either way. - } - - if (this.sync) { - var er, entries - try { - entries = fs.readdirSync(abs) - } catch (e) { - er = e - } - return this._afterReaddir(f, abs, cb, er, entries) - } - - fs.readdir(abs, this._afterReaddir.bind(this, f, abs, cb)) -} - -Glob.prototype._afterReaddir = function (f, abs, cb, er, entries) { - assert(this instanceof Glob) - if (entries && !er) { - this.cache[f] = entries - // if we haven't asked to stat everything for suresies, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. This also gets us one step - // further into ELOOP territory. - if (!this.mark && !this.stat) { - entries.forEach(function (e) { - if (f === "/") e = f + e - else e = f + "/" + e - this.cache[e] = true - }, this) - } - - return cb.call(this, er, entries) - } - - // now handle errors, and cache the information - if (er) switch (er.code) { - case "ENOTDIR": // totally normal. means it *does* exist. - this.cache[f] = 1 - return cb.call(this, er) - case "ENOENT": // not terribly unusual - case "ELOOP": - case "ENAMETOOLONG": - case "UNKNOWN": - this.cache[f] = false - return cb.call(this, er) - default: // some unusual error. Treat as failure. - this.cache[f] = false - if (this.strict) this.emit("error", er) - if (!this.silent) console.error("glob error", er) - return cb.call(this, er) - } -} - -var isAbsolute = process.platform === "win32" ? absWin : absUnix - -function absWin (p) { - if (absUnix(p)) return true - // pull off the device/UNC bit from a windows path. - // from node's lib/path.js - var splitDeviceRe = - /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/ - , result = splitDeviceRe.exec(p) - , device = result[1] || '' - , isUnc = device && device.charAt(1) !== ':' - , isAbsolute = !!result[2] || isUnc // UNC paths are always absolute - - return isAbsolute -} - -function absUnix (p) { - return p.charAt(0) === "/" || p === "" -} diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/LICENSE b/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013d6..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/README.md b/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/README.md deleted file mode 100644 index b1c566585..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/inherits.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/inherits.js deleted file mode 100644 index 29f5e24f5..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/inherits.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('util').inherits diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/inherits_browser.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/inherits_browser.js deleted file mode 100644 index c1e78a75e..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,23 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/package.json b/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/package.json deleted file mode 100644 index 5bf0db561..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "inherits", - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "version": "2.0.1", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "main": "./inherits.js", - "browser": "./inherits_browser.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits" - }, - "license": "ISC", - "scripts": { - "test": "node test" - }, - "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n superclass\n* new version overwrites current prototype while old one preserves any\n existing fields on it\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "homepage": "https://github.com/isaacs/inherits", - "_id": "inherits@2.0.1", - "_from": "inherits@2" -} diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/test.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/test.js deleted file mode 100644 index fc53012d3..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/inherits/test.js +++ /dev/null @@ -1,25 +0,0 @@ -var inherits = require('./inherits.js') -var assert = require('assert') - -function test(c) { - assert(c.constructor === Child) - assert(c.constructor.super_ === Parent) - assert(Object.getPrototypeOf(c) === Child.prototype) - assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) - assert(c instanceof Child) - assert(c instanceof Parent) -} - -function Child() { - Parent.call(this) - test(this) -} - -function Parent() {} - -inherits(Child, Parent) - -var c = new Child -test(c) - -console.log('ok') diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/.npmignore b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/.npmignore deleted file mode 100644 index 3c3629e64..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/LICENSE b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/LICENSE deleted file mode 100644 index 05a401094..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright 2009, 2010, 2011 Isaac Z. Schlueter. -All rights reserved. - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/README.md b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/README.md deleted file mode 100644 index 978268e27..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/README.md +++ /dev/null @@ -1,218 +0,0 @@ -# minimatch - -A minimal matching utility. - -[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch) - - -This is the matching library used internally by npm. - -Eventually, it will replace the C binding in node-glob. - -It works by converting glob expressions into JavaScript `RegExp` -objects. - -## Usage - -```javascript -var minimatch = require("minimatch") - -minimatch("bar.foo", "*.foo") // true! -minimatch("bar.foo", "*.bar") // false! -minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! -``` - -## Features - -Supports these glob features: - -* Brace Expansion -* Extended glob matching -* "Globstar" `**` matching - -See: - -* `man sh` -* `man bash` -* `man 3 fnmatch` -* `man 5 gitignore` - -## Minimatch Class - -Create a minimatch object by instanting the `minimatch.Minimatch` class. - -```javascript -var Minimatch = require("minimatch").Minimatch -var mm = new Minimatch(pattern, options) -``` - -### Properties - -* `pattern` The original pattern the minimatch object represents. -* `options` The options supplied to the constructor. -* `set` A 2-dimensional array of regexp or string expressions. - Each row in the - array corresponds to a brace-expanded pattern. Each item in the row - corresponds to a single path-part. For example, the pattern - `{a,b/c}/d` would expand to a set of patterns like: - - [ [ a, d ] - , [ b, c, d ] ] - - If a portion of the pattern doesn't have any "magic" in it - (that is, it's something like `"foo"` rather than `fo*o?`), then it - will be left as a string rather than converted to a regular - expression. - -* `regexp` Created by the `makeRe` method. A single regular expression - expressing the entire pattern. This is useful in cases where you wish - to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. -* `negate` True if the pattern is negated. -* `comment` True if the pattern is a comment. -* `empty` True if the pattern is `""`. - -### Methods - -* `makeRe` Generate the `regexp` member if necessary, and return it. - Will return `false` if the pattern is invalid. -* `match(fname)` Return true if the filename matches the pattern, or - false otherwise. -* `matchOne(fileArray, patternArray, partial)` Take a `/`-split - filename, and match it against a single row in the `regExpSet`. This - method is mainly for internal use, but is exposed so that it can be - used by a glob-walker that needs to avoid excessive filesystem calls. - -All other methods are internal, and will be called as necessary. - -## Functions - -The top-level exported function has a `cache` property, which is an LRU -cache set to store 100 items. So, calling these methods repeatedly -with the same pattern and options will use the same Minimatch object, -saving the cost of parsing it multiple times. - -### minimatch(path, pattern, options) - -Main export. Tests a path against the pattern using the options. - -```javascript -var isJS = minimatch(file, "*.js", { matchBase: true }) -``` - -### minimatch.filter(pattern, options) - -Returns a function that tests its -supplied argument, suitable for use with `Array.filter`. Example: - -```javascript -var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) -``` - -### minimatch.match(list, pattern, options) - -Match against the list of -files, in the style of fnmatch or glob. If nothing is matched, and -options.nonull is set, then return a list containing the pattern itself. - -```javascript -var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) -``` - -### minimatch.makeRe(pattern, options) - -Make a regular expression object from the pattern. - -## Options - -All options are `false` by default. - -### debug - -Dump a ton of stuff to stderr. - -### nobrace - -Do not expand `{a,b}` and `{1..3}` brace sets. - -### noglobstar - -Disable `**` matching against multiple folder names. - -### dot - -Allow patterns to match filenames starting with a period, even if -the pattern does not explicitly have a period in that spot. - -Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` -is set. - -### noext - -Disable "extglob" style patterns like `+(a|b)`. - -### nocase - -Perform a case-insensitive match. - -### nonull - -When a match is not found by `minimatch.match`, return a list containing -the pattern itself. When set, an empty list is returned if there are -no matches. - -### matchBase - -If set, then patterns without slashes will be matched -against the basename of the path if it contains slashes. For example, -`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. - -### nocomment - -Suppress the behavior of treating `#` at the start of a pattern as a -comment. - -### nonegate - -Suppress the behavior of treating a leading `!` character as negation. - -### flipNegate - -Returns from negate expressions the same as if they were not negated. -(Ie, true on a hit, false on a miss.) - - -## Comparisons to other fnmatch/glob implementations - -While strict compliance with the existing standards is a worthwhile -goal, some discrepancies exist between minimatch and other -implementations, and are intentional. - -If the pattern starts with a `!` character, then it is negated. Set the -`nonegate` flag to suppress this behavior, and treat leading `!` -characters normally. This is perhaps relevant if you wish to start the -pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` -characters at the start of a pattern will negate the pattern multiple -times. - -If a pattern starts with `#`, then it is treated as a comment, and -will not match anything. Use `\#` to match a literal `#` at the -start of a line, or set the `nocomment` flag to suppress this behavior. - -The double-star character `**` is supported by default, unless the -`noglobstar` flag is set. This is supported in the manner of bsdglob -and bash 4.1, where `**` only has special significance if it is the only -thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but -`a/**b` will not. - -If an escaped pattern has no matches, and the `nonull` flag is set, -then minimatch.match returns the pattern as-provided, rather than -interpreting the character escapes. For example, -`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than -`"*a?"`. This is akin to setting the `nullglob` option in bash, except -that it does not resolve escaped pattern characters. - -If brace expansion is not disabled, then it is performed before any -other interpretation of the glob pattern. Thus, a pattern like -`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded -**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are -checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/minimatch.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/minimatch.js deleted file mode 100644 index c633f89fa..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/minimatch.js +++ /dev/null @@ -1,1055 +0,0 @@ -;(function (require, exports, module, platform) { - -if (module) module.exports = minimatch -else exports.minimatch = minimatch - -if (!require) { - require = function (id) { - switch (id) { - case "sigmund": return function sigmund (obj) { - return JSON.stringify(obj) - } - case "path": return { basename: function (f) { - f = f.split(/[\/\\]/) - var e = f.pop() - if (!e) e = f.pop() - return e - }} - case "lru-cache": return function LRUCache () { - // not quite an LRU, but still space-limited. - var cache = {} - var cnt = 0 - this.set = function (k, v) { - cnt ++ - if (cnt >= 100) cache = {} - cache[k] = v - } - this.get = function (k) { return cache[k] } - } - } - } -} - -minimatch.Minimatch = Minimatch - -var LRU = require("lru-cache") - , cache = minimatch.cache = new LRU({max: 100}) - , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} - , sigmund = require("sigmund") - -var path = require("path") - // any single thing other than / - // don't need to escape / when using new RegExp() - , qmark = "[^/]" - - // * => any number of characters - , star = qmark + "*?" - - // ** when dots are allowed. Anything goes, except .. and . - // not (^ or / followed by one or two dots followed by $ or /), - // followed by anything, any number of times. - , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" - - // not a ^ or / followed by a dot, - // followed by anything, any number of times. - , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" - - // characters that need to be escaped in RegExp. - , reSpecials = charSet("().*{}+?[]^$\\!") - -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split("").reduce(function (set, c) { - set[c] = true - return set - }, {}) -} - -// normalizes slashes. -var slashSplit = /\/+/ - -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} - -function ext (a, b) { - a = a || {} - b = b || {} - var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - return t -} - -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch - - var orig = minimatch - - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) - } - - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - - return m -} - -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch -} - - -function minimatch (p, pattern, options) { - if (typeof pattern !== "string") { - throw new TypeError("glob pattern string required") - } - - if (!options) options = {} - - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === "#") { - return false - } - - // "" only matches "" - if (pattern.trim() === "") return p === "" - - return new Minimatch(pattern, options).match(p) -} - -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options, cache) - } - - if (typeof pattern !== "string") { - throw new TypeError("glob pattern string required") - } - - if (!options) options = {} - pattern = pattern.trim() - - // windows: need to use /, not \ - // On other platforms, \ is a valid (albeit bad) filename char. - if (platform === "win32") { - pattern = pattern.split("\\").join("/") - } - - // lru storage. - // these things aren't particularly big, but walking down the string - // and turning it into a regexp can get pretty costly. - var cacheKey = pattern + "\n" + sigmund(options) - var cached = minimatch.cache.get(cacheKey) - if (cached) return cached - minimatch.cache.set(cacheKey, this) - - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - - // make the set of regexps etc. - this.make() -} - -Minimatch.prototype.debug = function() {} - -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return - - var pattern = this.pattern - var options = this.options - - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === "#") { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } - - // step 1: figure out negation, etc. - this.parseNegate() - - // step 2: expand braces - var set = this.globSet = this.braceExpand() - - if (options.debug) this.debug = console.error - - this.debug(this.pattern, set) - - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) - - this.debug(this.pattern, set) - - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) - - this.debug(this.pattern, set) - - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return -1 === s.indexOf(false) - }) - - this.debug(this.pattern, set) - - this.set = set -} - -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - , negate = false - , options = this.options - , negateOffset = 0 - - if (options.nonegate) return - - for ( var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === "!" - ; i ++) { - negate = !negate - negateOffset ++ - } - - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} - -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return new Minimatch(pattern, options).braceExpand() -} - -Minimatch.prototype.braceExpand = braceExpand -function braceExpand (pattern, options) { - options = options || this.options - pattern = typeof pattern === "undefined" - ? this.pattern : pattern - - if (typeof pattern === "undefined") { - throw new Error("undefined pattern") - } - - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } - - var escaping = false - - // examples and comments refer to this crazy pattern: - // a{b,c{d,e},{f,g}h}x{y,z} - // expected: - // abxy - // abxz - // acdxy - // acdxz - // acexy - // acexz - // afhxy - // afhxz - // aghxy - // aghxz - - // everything before the first \{ is just a prefix. - // So, we pluck that off, and work with the rest, - // and then prepend it to everything we find. - if (pattern.charAt(0) !== "{") { - this.debug(pattern) - var prefix = null - for (var i = 0, l = pattern.length; i < l; i ++) { - var c = pattern.charAt(i) - this.debug(i, c) - if (c === "\\") { - escaping = !escaping - } else if (c === "{" && !escaping) { - prefix = pattern.substr(0, i) - break - } - } - - // actually no sets, all { were escaped. - if (prefix === null) { - this.debug("no sets") - return [pattern] - } - - var tail = braceExpand.call(this, pattern.substr(i), options) - return tail.map(function (t) { - return prefix + t - }) - } - - // now we have something like: - // {b,c{d,e},{f,g}h}x{y,z} - // walk through the set, expanding each part, until - // the set ends. then, we'll expand the suffix. - // If the set only has a single member, then'll put the {} back - - // first, handle numeric sets, since they're easier - var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/) - if (numset) { - this.debug("numset", numset[1], numset[2]) - var suf = braceExpand.call(this, pattern.substr(numset[0].length), options) - , start = +numset[1] - , end = +numset[2] - , inc = start > end ? -1 : 1 - , set = [] - for (var i = start; i != (end + inc); i += inc) { - // append all the suffixes - for (var ii = 0, ll = suf.length; ii < ll; ii ++) { - set.push(i + suf[ii]) - } - } - return set - } - - // ok, walk through the set - // We hope, somewhat optimistically, that there - // will be a } at the end. - // If the closing brace isn't found, then the pattern is - // interpreted as braceExpand("\\" + pattern) so that - // the leading \{ will be interpreted literally. - var i = 1 // skip the \{ - , depth = 1 - , set = [] - , member = "" - , sawEnd = false - , escaping = false - - function addMember () { - set.push(member) - member = "" - } - - this.debug("Entering for") - FOR: for (i = 1, l = pattern.length; i < l; i ++) { - var c = pattern.charAt(i) - this.debug("", i, c) - - if (escaping) { - escaping = false - member += "\\" + c - } else { - switch (c) { - case "\\": - escaping = true - continue - - case "{": - depth ++ - member += "{" - continue - - case "}": - depth -- - // if this closes the actual set, then we're done - if (depth === 0) { - addMember() - // pluck off the close-brace - i ++ - break FOR - } else { - member += c - continue - } - - case ",": - if (depth === 1) { - addMember() - } else { - member += c - } - continue - - default: - member += c - continue - } // switch - } // else - } // for - - // now we've either finished the set, and the suffix is - // pattern.substr(i), or we have *not* closed the set, - // and need to escape the leading brace - if (depth !== 0) { - this.debug("didn't close", pattern) - return braceExpand.call(this, "\\" + pattern, options) - } - - // x{y,z} -> ["xy", "xz"] - this.debug("set", set) - this.debug("suffix", pattern.substr(i)) - var suf = braceExpand.call(this, pattern.substr(i), options) - // ["b", "c{d,e}","{f,g}h"] -> - // [["b"], ["cd", "ce"], ["fh", "gh"]] - var addBraces = set.length === 1 - this.debug("set pre-expanded", set) - set = set.map(function (p) { - return braceExpand.call(this, p, options) - }, this) - this.debug("set expanded", set) - - - // [["b"], ["cd", "ce"], ["fh", "gh"]] -> - // ["b", "cd", "ce", "fh", "gh"] - set = set.reduce(function (l, r) { - return l.concat(r) - }) - - if (addBraces) { - set = set.map(function (s) { - return "{" + s + "}" - }) - } - - // now attach the suffixes. - var ret = [] - for (var i = 0, l = set.length; i < l; i ++) { - for (var ii = 0, ll = suf.length; ii < ll; ii ++) { - ret.push(set[i] + suf[ii]) - } - } - return ret -} - -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === "**") return GLOBSTAR - if (pattern === "") return "" - - var re = "" - , hasMagic = !!options.nocase - , escaping = false - // ? => one single character - , patternListStack = [] - , plType - , stateChar - , inClass = false - , reClassStart = -1 - , classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - , patternStart = pattern.charAt(0) === "." ? "" // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" - : "(?!\\.)" - , self = this - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case "*": - re += star - hasMagic = true - break - case "?": - re += qmark - hasMagic = true - break - default: - re += "\\"+stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } - - for ( var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i ++ ) { - - this.debug("%s\t%s %s %j", pattern, i, re, c) - - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += "\\" + c - escaping = false - continue - } - - SWITCH: switch (c) { - case "/": - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - - case "\\": - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case "?": - case "*": - case "+": - case "@": - case "!": - this.debug("%s\t%s %s %j <-- stateChar", pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === "!" && i === classStart + 1) c = "^" - re += c - continue - } - - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case "(": - if (inClass) { - re += "(" - continue - } - - if (!stateChar) { - re += "\\(" - continue - } - - plType = stateChar - patternListStack.push({ type: plType - , start: i - 1 - , reStart: re.length }) - // negation is (?:(?!js)[^/]*) - re += stateChar === "!" ? "(?:(?!" : "(?:" - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue - - case ")": - if (inClass || !patternListStack.length) { - re += "\\)" - continue - } - - clearStateChar() - hasMagic = true - re += ")" - plType = patternListStack.pop().type - // negation is (?:(?!js)[^/]*) - // The others are (?:) - switch (plType) { - case "!": - re += "[^/]*?)" - break - case "?": - case "+": - case "*": re += plType - case "@": break // the default anyway - } - continue - - case "|": - if (inClass || !patternListStack.length || escaping) { - re += "\\|" - escaping = false - continue - } - - clearStateChar() - re += "|" - continue - - // these are mostly the same in regexp and glob - case "[": - // swallow any state-tracking char before the [ - clearStateChar() - - if (inClass) { - re += "\\" + c - continue - } - - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case "]": - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += "\\" + c - escaping = false - continue - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === "^" && inClass)) { - re += "\\" - } - - re += c - - } // switch - } // for - - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - var cs = pattern.substr(classStart + 1) - , sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + "\\[" + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - var pl - while (pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + 3) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = "\\" - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + "|" - }) - - this.debug("tail=%j\n %s", tail, tail) - var t = pl.type === "*" ? star - : pl.type === "?" ? qmark - : "\\" + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) - + t + "\\(" - + tail - } - - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += "\\\\" - } - - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case ".": - case "[": - case "(": addPatternStart = true - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== "" && hasMagic) re = "(?=.)" + re - - if (addPatternStart) re = patternStart + re - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [ re, hasMagic ] - } - - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } - - var flags = options.nocase ? "i" : "" - , regExp = new RegExp("^" + re + "$", flags) - - regExp._glob = pattern - regExp._src = re - - return regExp -} - -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} - -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp - - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set - - if (!set.length) return this.regexp = false - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - , flags = options.nocase ? "i" : "" - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === "string") ? regExpEscape(p) - : p._src - }).join("\\\/") - }).join("|") - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = "^(?:" + re + ")$" - - // can match anything, as long as it's not this. - if (this.negate) re = "^(?!" + re + ").*$" - - try { - return this.regexp = new RegExp(re, flags) - } catch (ex) { - return this.regexp = false - } -} - -minimatch.match = function (list, pattern, options) { - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (options.nonull && !list.length) { - list.push(pattern) - } - return list -} - -Minimatch.prototype.match = match -function match (f, partial) { - this.debug("match", f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === "" - - if (f === "/" && partial) return true - - var options = this.options - - // windows: need to use /, not \ - // On other platforms, \ is a valid (albeit bad) filename char. - if (platform === "win32") { - f = f.split("\\").join("/") - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, "split", f) - - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. - - var set = this.set - this.debug(this.pattern, "set", set) - - var splitFile = path.basename(f.join("/")).split("/") - - for (var i = 0, l = set.length; i < l; i ++) { - var pattern = set[i], file = f - if (options.matchBase && pattern.length === 1) { - file = splitFile - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug("matchOne", - { "this": this - , file: file - , pattern: pattern }) - - this.debug("matchOne", file.length, pattern.length) - - for ( var fi = 0 - , pi = 0 - , fl = file.length - , pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi ++, pi ++ ) { - - this.debug("matchOne loop") - var p = pattern[pi] - , f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - , pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for ( ; fi < fl; fi ++) { - if (file[fi] === "." || file[fi] === ".." || - (!options.dot && file[fi].charAt(0) === ".")) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - WHILE: while (fr < fl) { - var swallowee = file[fr] - - this.debug('\nglobstar while', - file, fr, pattern, pr, swallowee) - - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === "." || swallowee === ".." || - (!options.dot && swallowee.charAt(0) === ".")) { - this.debug("dot detected!", file, fr, pattern, pr) - break WHILE - } - - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr ++ - } - } - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug("\n>>> no match, partial?", file, fr, pattern, pr) - if (fr === fl) return true - } - return false - } - - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === "string") { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p - } - this.debug("string match", p, f, hit) - } else { - hit = f.match(p) - this.debug("pattern match", p, f, hit) - } - - if (!hit) return false - } - - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === "") - return emptyFileEnd - } - - // should be unreachable. - throw new Error("wtf?") -} - - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, "$1") -} - - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") -} - -})( typeof require === "function" ? require : null, - this, - typeof module === "object" ? module : null, - typeof process === "object" ? process.platform : "win32" - ) diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore deleted file mode 100644 index 07e6e472c..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS deleted file mode 100644 index 4a0bc5033..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS +++ /dev/null @@ -1,14 +0,0 @@ -# Authors, sorted by whether or not they are me -Isaac Z. Schlueter -Brian Cottingham -Carlos Brito Lage -Jesse Dailey -Kevin O'Hara -Marco Rogers -Mark Cavage -Marko Mikulicic -Nathan Rajlich -Satheesh Natesan -Trent Mick -ashleybrener -n4kz diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE deleted file mode 100644 index 05a401094..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright 2009, 2010, 2011 Isaac Z. Schlueter. -All rights reserved. - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md deleted file mode 100644 index 03ee0f985..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md +++ /dev/null @@ -1,97 +0,0 @@ -# lru cache - -A cache object that deletes the least-recently-used items. - -## Usage: - -```javascript -var LRU = require("lru-cache") - , options = { max: 500 - , length: function (n) { return n * 2 } - , dispose: function (key, n) { n.close() } - , maxAge: 1000 * 60 * 60 } - , cache = LRU(options) - , otherCache = LRU(50) // sets just the max size - -cache.set("key", "value") -cache.get("key") // "value" - -cache.reset() // empty the cache -``` - -If you put more stuff in it, then items will fall out. - -If you try to put an oversized thing in it, then it'll fall out right -away. - -## Options - -* `max` The maximum size of the cache, checked by applying the length - function to all values in the cache. Not setting this is kind of - silly, since that's the whole purpose of this lib, but it defaults - to `Infinity`. -* `maxAge` Maximum age in ms. Items are not pro-actively pruned out - as they age, but if you try to get an item that is too old, it'll - drop it and return undefined instead of giving it to you. -* `length` Function that is used to calculate the length of stored - items. If you're storing strings or buffers, then you probably want - to do something like `function(n){return n.length}`. The default is - `function(n){return 1}`, which is fine if you want to store `n` - like-sized things. -* `dispose` Function that is called on items when they are dropped - from the cache. This can be handy if you want to close file - descriptors or do other cleanup tasks when items are no longer - accessible. Called with `key, value`. It's called *before* - actually removing the item from the internal cache, so if you want - to immediately put it back in, you'll have to do that in a - `nextTick` or `setTimeout` callback or it won't do anything. -* `stale` By default, if you set a `maxAge`, it'll only actually pull - stale items out of the cache when you `get(key)`. (That is, it's - not pre-emptively doing a `setTimeout` or anything.) If you set - `stale:true`, it'll return the stale value before deleting it. If - you don't set this, then it'll return `undefined` when you try to - get a stale entry, as if it had already been deleted. - -## API - -* `set(key, value)` -* `get(key) => value` - - Both of these will update the "recently used"-ness of the key. - They do what you think. - -* `peek(key)` - - Returns the key value (or `undefined` if not found) without - updating the "recently used"-ness of the key. - - (If you find yourself using this a lot, you *might* be using the - wrong sort of data structure, but there are some use cases where - it's handy.) - -* `del(key)` - - Deletes a key out of the cache. - -* `reset()` - - Clear the cache entirely, throwing away all values. - -* `has(key)` - - Check if a key is in the cache, without updating the recent-ness - or deleting it for being stale. - -* `forEach(function(value,key,cache), [thisp])` - - Just like `Array.prototype.forEach`. Iterates over all the keys - in the cache, in order of recent-ness. (Ie, more recently used - items are iterated over first.) - -* `keys()` - - Return an array of the keys in the cache. - -* `values()` - - Return an array of the values in the cache. diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js deleted file mode 100644 index d1d138172..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js +++ /dev/null @@ -1,252 +0,0 @@ -;(function () { // closure for web browsers - -if (typeof module === 'object' && module.exports) { - module.exports = LRUCache -} else { - // just set the global for non-node platforms. - this.LRUCache = LRUCache -} - -function hOP (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key) -} - -function naiveLength () { return 1 } - -function LRUCache (options) { - if (!(this instanceof LRUCache)) - return new LRUCache(options) - - if (typeof options === 'number') - options = { max: options } - - if (!options) - options = {} - - this._max = options.max - // Kind of weird to have a default max of Infinity, but oh well. - if (!this._max || !(typeof this._max === "number") || this._max <= 0 ) - this._max = Infinity - - this._lengthCalculator = options.length || naiveLength - if (typeof this._lengthCalculator !== "function") - this._lengthCalculator = naiveLength - - this._allowStale = options.stale || false - this._maxAge = options.maxAge || null - this._dispose = options.dispose - this.reset() -} - -// resize the cache when the max changes. -Object.defineProperty(LRUCache.prototype, "max", - { set : function (mL) { - if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity - this._max = mL - if (this._length > this._max) trim(this) - } - , get : function () { return this._max } - , enumerable : true - }) - -// resize the cache when the lengthCalculator changes. -Object.defineProperty(LRUCache.prototype, "lengthCalculator", - { set : function (lC) { - if (typeof lC !== "function") { - this._lengthCalculator = naiveLength - this._length = this._itemCount - for (var key in this._cache) { - this._cache[key].length = 1 - } - } else { - this._lengthCalculator = lC - this._length = 0 - for (var key in this._cache) { - this._cache[key].length = this._lengthCalculator(this._cache[key].value) - this._length += this._cache[key].length - } - } - - if (this._length > this._max) trim(this) - } - , get : function () { return this._lengthCalculator } - , enumerable : true - }) - -Object.defineProperty(LRUCache.prototype, "length", - { get : function () { return this._length } - , enumerable : true - }) - - -Object.defineProperty(LRUCache.prototype, "itemCount", - { get : function () { return this._itemCount } - , enumerable : true - }) - -LRUCache.prototype.forEach = function (fn, thisp) { - thisp = thisp || this - var i = 0; - for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { - i++ - var hit = this._lruList[k] - if (this._maxAge && (Date.now() - hit.now > this._maxAge)) { - del(this, hit) - if (!this._allowStale) hit = undefined - } - if (hit) { - fn.call(thisp, hit.value, hit.key, this) - } - } -} - -LRUCache.prototype.keys = function () { - var keys = new Array(this._itemCount) - var i = 0 - for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { - var hit = this._lruList[k] - keys[i++] = hit.key - } - return keys -} - -LRUCache.prototype.values = function () { - var values = new Array(this._itemCount) - var i = 0 - for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) { - var hit = this._lruList[k] - values[i++] = hit.value - } - return values -} - -LRUCache.prototype.reset = function () { - if (this._dispose && this._cache) { - for (var k in this._cache) { - this._dispose(k, this._cache[k].value) - } - } - - this._cache = Object.create(null) // hash of items by key - this._lruList = Object.create(null) // list of items in order of use recency - this._mru = 0 // most recently used - this._lru = 0 // least recently used - this._length = 0 // number of items in the list - this._itemCount = 0 -} - -// Provided for debugging/dev purposes only. No promises whatsoever that -// this API stays stable. -LRUCache.prototype.dump = function () { - return this._cache -} - -LRUCache.prototype.dumpLru = function () { - return this._lruList -} - -LRUCache.prototype.set = function (key, value) { - if (hOP(this._cache, key)) { - // dispose of the old one before overwriting - if (this._dispose) this._dispose(key, this._cache[key].value) - if (this._maxAge) this._cache[key].now = Date.now() - this._cache[key].value = value - this.get(key) - return true - } - - var len = this._lengthCalculator(value) - var age = this._maxAge ? Date.now() : 0 - var hit = new Entry(key, value, this._mru++, len, age) - - // oversized objects fall out of cache automatically. - if (hit.length > this._max) { - if (this._dispose) this._dispose(key, value) - return false - } - - this._length += hit.length - this._lruList[hit.lu] = this._cache[key] = hit - this._itemCount ++ - - if (this._length > this._max) trim(this) - return true -} - -LRUCache.prototype.has = function (key) { - if (!hOP(this._cache, key)) return false - var hit = this._cache[key] - if (this._maxAge && (Date.now() - hit.now > this._maxAge)) { - return false - } - return true -} - -LRUCache.prototype.get = function (key) { - return get(this, key, true) -} - -LRUCache.prototype.peek = function (key) { - return get(this, key, false) -} - -LRUCache.prototype.pop = function () { - var hit = this._lruList[this._lru] - del(this, hit) - return hit || null -} - -LRUCache.prototype.del = function (key) { - del(this, this._cache[key]) -} - -function get (self, key, doUse) { - var hit = self._cache[key] - if (hit) { - if (self._maxAge && (Date.now() - hit.now > self._maxAge)) { - del(self, hit) - if (!self._allowStale) hit = undefined - } else { - if (doUse) use(self, hit) - } - if (hit) hit = hit.value - } - return hit -} - -function use (self, hit) { - shiftLU(self, hit) - hit.lu = self._mru ++ - self._lruList[hit.lu] = hit -} - -function trim (self) { - while (self._lru < self._mru && self._length > self._max) - del(self, self._lruList[self._lru]) -} - -function shiftLU (self, hit) { - delete self._lruList[ hit.lu ] - while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++ -} - -function del (self, hit) { - if (hit) { - if (self._dispose) self._dispose(hit.key, hit.value) - self._length -= hit.length - self._itemCount -- - delete self._cache[ hit.key ] - shiftLU(self, hit) - } -} - -// classy, since V8 prefers predictable objects. -function Entry (key, value, lu, length, now) { - this.key = key - this.value = value - this.lu = lu - this.length = length - this.now = now -} - -})() diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json deleted file mode 100644 index 4472725df..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "lru-cache", - "description": "A cache object that deletes the least-recently-used items.", - "version": "2.5.0", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "scripts": { - "test": "tap test --gc" - }, - "main": "lib/lru-cache.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-lru-cache.git" - }, - "devDependencies": { - "tap": "", - "weak": "" - }, - "license": { - "type": "MIT", - "url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE" - }, - "readme": "# lru cache\n\nA cache object that deletes the least-recently-used items.\n\n## Usage:\n\n```javascript\nvar LRU = require(\"lru-cache\")\n , options = { max: 500\n , length: function (n) { return n * 2 }\n , dispose: function (key, n) { n.close() }\n , maxAge: 1000 * 60 * 60 }\n , cache = LRU(options)\n , otherCache = LRU(50) // sets just the max size\n\ncache.set(\"key\", \"value\")\ncache.get(\"key\") // \"value\"\n\ncache.reset() // empty the cache\n```\n\nIf you put more stuff in it, then items will fall out.\n\nIf you try to put an oversized thing in it, then it'll fall out right\naway.\n\n## Options\n\n* `max` The maximum size of the cache, checked by applying the length\n function to all values in the cache. Not setting this is kind of\n silly, since that's the whole purpose of this lib, but it defaults\n to `Infinity`.\n* `maxAge` Maximum age in ms. Items are not pro-actively pruned out\n as they age, but if you try to get an item that is too old, it'll\n drop it and return undefined instead of giving it to you.\n* `length` Function that is used to calculate the length of stored\n items. If you're storing strings or buffers, then you probably want\n to do something like `function(n){return n.length}`. The default is\n `function(n){return 1}`, which is fine if you want to store `n`\n like-sized things.\n* `dispose` Function that is called on items when they are dropped\n from the cache. This can be handy if you want to close file\n descriptors or do other cleanup tasks when items are no longer\n accessible. Called with `key, value`. It's called *before*\n actually removing the item from the internal cache, so if you want\n to immediately put it back in, you'll have to do that in a\n `nextTick` or `setTimeout` callback or it won't do anything.\n* `stale` By default, if you set a `maxAge`, it'll only actually pull\n stale items out of the cache when you `get(key)`. (That is, it's\n not pre-emptively doing a `setTimeout` or anything.) If you set\n `stale:true`, it'll return the stale value before deleting it. If\n you don't set this, then it'll return `undefined` when you try to\n get a stale entry, as if it had already been deleted.\n\n## API\n\n* `set(key, value)`\n* `get(key) => value`\n\n Both of these will update the \"recently used\"-ness of the key.\n They do what you think.\n\n* `peek(key)`\n\n Returns the key value (or `undefined` if not found) without\n updating the \"recently used\"-ness of the key.\n\n (If you find yourself using this a lot, you *might* be using the\n wrong sort of data structure, but there are some use cases where\n it's handy.)\n\n* `del(key)`\n\n Deletes a key out of the cache.\n\n* `reset()`\n\n Clear the cache entirely, throwing away all values.\n\n* `has(key)`\n\n Check if a key is in the cache, without updating the recent-ness\n or deleting it for being stale.\n\n* `forEach(function(value,key,cache), [thisp])`\n\n Just like `Array.prototype.forEach`. Iterates over all the keys\n in the cache, in order of recent-ness. (Ie, more recently used\n items are iterated over first.)\n\n* `keys()`\n\n Return an array of the keys in the cache.\n\n* `values()`\n\n Return an array of the values in the cache.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-lru-cache/issues" - }, - "homepage": "https://github.com/isaacs/node-lru-cache", - "_id": "lru-cache@2.5.0", - "_from": "lru-cache@2" -} diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js deleted file mode 100644 index f72697c46..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js +++ /dev/null @@ -1,369 +0,0 @@ -var test = require("tap").test - , LRU = require("../") - -test("basic", function (t) { - var cache = new LRU({max: 10}) - cache.set("key", "value") - t.equal(cache.get("key"), "value") - t.equal(cache.get("nada"), undefined) - t.equal(cache.length, 1) - t.equal(cache.max, 10) - t.end() -}) - -test("least recently set", function (t) { - var cache = new LRU(2) - cache.set("a", "A") - cache.set("b", "B") - cache.set("c", "C") - t.equal(cache.get("c"), "C") - t.equal(cache.get("b"), "B") - t.equal(cache.get("a"), undefined) - t.end() -}) - -test("lru recently gotten", function (t) { - var cache = new LRU(2) - cache.set("a", "A") - cache.set("b", "B") - cache.get("a") - cache.set("c", "C") - t.equal(cache.get("c"), "C") - t.equal(cache.get("b"), undefined) - t.equal(cache.get("a"), "A") - t.end() -}) - -test("del", function (t) { - var cache = new LRU(2) - cache.set("a", "A") - cache.del("a") - t.equal(cache.get("a"), undefined) - t.end() -}) - -test("max", function (t) { - var cache = new LRU(3) - - // test changing the max, verify that the LRU items get dropped. - cache.max = 100 - for (var i = 0; i < 100; i ++) cache.set(i, i) - t.equal(cache.length, 100) - for (var i = 0; i < 100; i ++) { - t.equal(cache.get(i), i) - } - cache.max = 3 - t.equal(cache.length, 3) - for (var i = 0; i < 97; i ++) { - t.equal(cache.get(i), undefined) - } - for (var i = 98; i < 100; i ++) { - t.equal(cache.get(i), i) - } - - // now remove the max restriction, and try again. - cache.max = "hello" - for (var i = 0; i < 100; i ++) cache.set(i, i) - t.equal(cache.length, 100) - for (var i = 0; i < 100; i ++) { - t.equal(cache.get(i), i) - } - // should trigger an immediate resize - cache.max = 3 - t.equal(cache.length, 3) - for (var i = 0; i < 97; i ++) { - t.equal(cache.get(i), undefined) - } - for (var i = 98; i < 100; i ++) { - t.equal(cache.get(i), i) - } - t.end() -}) - -test("reset", function (t) { - var cache = new LRU(10) - cache.set("a", "A") - cache.set("b", "B") - cache.reset() - t.equal(cache.length, 0) - t.equal(cache.max, 10) - t.equal(cache.get("a"), undefined) - t.equal(cache.get("b"), undefined) - t.end() -}) - - -// Note: `.dump()` is a debugging tool only. No guarantees are made -// about the format/layout of the response. -test("dump", function (t) { - var cache = new LRU(10) - var d = cache.dump(); - t.equal(Object.keys(d).length, 0, "nothing in dump for empty cache") - cache.set("a", "A") - var d = cache.dump() // { a: { key: "a", value: "A", lu: 0 } } - t.ok(d.a) - t.equal(d.a.key, "a") - t.equal(d.a.value, "A") - t.equal(d.a.lu, 0) - - cache.set("b", "B") - cache.get("b") - d = cache.dump() - t.ok(d.b) - t.equal(d.b.key, "b") - t.equal(d.b.value, "B") - t.equal(d.b.lu, 2) - - t.end() -}) - - -test("basic with weighed length", function (t) { - var cache = new LRU({ - max: 100, - length: function (item) { return item.size } - }) - cache.set("key", {val: "value", size: 50}) - t.equal(cache.get("key").val, "value") - t.equal(cache.get("nada"), undefined) - t.equal(cache.lengthCalculator(cache.get("key")), 50) - t.equal(cache.length, 50) - t.equal(cache.max, 100) - t.end() -}) - - -test("weighed length item too large", function (t) { - var cache = new LRU({ - max: 10, - length: function (item) { return item.size } - }) - t.equal(cache.max, 10) - - // should fall out immediately - cache.set("key", {val: "value", size: 50}) - - t.equal(cache.length, 0) - t.equal(cache.get("key"), undefined) - t.end() -}) - -test("least recently set with weighed length", function (t) { - var cache = new LRU({ - max:8, - length: function (item) { return item.length } - }) - cache.set("a", "A") - cache.set("b", "BB") - cache.set("c", "CCC") - cache.set("d", "DDDD") - t.equal(cache.get("d"), "DDDD") - t.equal(cache.get("c"), "CCC") - t.equal(cache.get("b"), undefined) - t.equal(cache.get("a"), undefined) - t.end() -}) - -test("lru recently gotten with weighed length", function (t) { - var cache = new LRU({ - max: 8, - length: function (item) { return item.length } - }) - cache.set("a", "A") - cache.set("b", "BB") - cache.set("c", "CCC") - cache.get("a") - cache.get("b") - cache.set("d", "DDDD") - t.equal(cache.get("c"), undefined) - t.equal(cache.get("d"), "DDDD") - t.equal(cache.get("b"), "BB") - t.equal(cache.get("a"), "A") - t.end() -}) - -test("set returns proper booleans", function(t) { - var cache = new LRU({ - max: 5, - length: function (item) { return item.length } - }) - - t.equal(cache.set("a", "A"), true) - - // should return false for max exceeded - t.equal(cache.set("b", "donuts"), false) - - t.equal(cache.set("b", "B"), true) - t.equal(cache.set("c", "CCCC"), true) - t.end() -}) - -test("drop the old items", function(t) { - var cache = new LRU({ - max: 5, - maxAge: 50 - }) - - cache.set("a", "A") - - setTimeout(function () { - cache.set("b", "b") - t.equal(cache.get("a"), "A") - }, 25) - - setTimeout(function () { - cache.set("c", "C") - // timed out - t.notOk(cache.get("a")) - }, 60) - - setTimeout(function () { - t.notOk(cache.get("b")) - t.equal(cache.get("c"), "C") - }, 90) - - setTimeout(function () { - t.notOk(cache.get("c")) - t.end() - }, 155) -}) - -test("disposal function", function(t) { - var disposed = false - var cache = new LRU({ - max: 1, - dispose: function (k, n) { - disposed = n - } - }) - - cache.set(1, 1) - cache.set(2, 2) - t.equal(disposed, 1) - cache.set(3, 3) - t.equal(disposed, 2) - cache.reset() - t.equal(disposed, 3) - t.end() -}) - -test("disposal function on too big of item", function(t) { - var disposed = false - var cache = new LRU({ - max: 1, - length: function (k) { - return k.length - }, - dispose: function (k, n) { - disposed = n - } - }) - var obj = [ 1, 2 ] - - t.equal(disposed, false) - cache.set("obj", obj) - t.equal(disposed, obj) - t.end() -}) - -test("has()", function(t) { - var cache = new LRU({ - max: 1, - maxAge: 10 - }) - - cache.set('foo', 'bar') - t.equal(cache.has('foo'), true) - cache.set('blu', 'baz') - t.equal(cache.has('foo'), false) - t.equal(cache.has('blu'), true) - setTimeout(function() { - t.equal(cache.has('blu'), false) - t.end() - }, 15) -}) - -test("stale", function(t) { - var cache = new LRU({ - maxAge: 10, - stale: true - }) - - cache.set('foo', 'bar') - t.equal(cache.get('foo'), 'bar') - t.equal(cache.has('foo'), true) - setTimeout(function() { - t.equal(cache.has('foo'), false) - t.equal(cache.get('foo'), 'bar') - t.equal(cache.get('foo'), undefined) - t.end() - }, 15) -}) - -test("lru update via set", function(t) { - var cache = LRU({ max: 2 }); - - cache.set('foo', 1); - cache.set('bar', 2); - cache.del('bar'); - cache.set('baz', 3); - cache.set('qux', 4); - - t.equal(cache.get('foo'), undefined) - t.equal(cache.get('bar'), undefined) - t.equal(cache.get('baz'), 3) - t.equal(cache.get('qux'), 4) - t.end() -}) - -test("least recently set w/ peek", function (t) { - var cache = new LRU(2) - cache.set("a", "A") - cache.set("b", "B") - t.equal(cache.peek("a"), "A") - cache.set("c", "C") - t.equal(cache.get("c"), "C") - t.equal(cache.get("b"), "B") - t.equal(cache.get("a"), undefined) - t.end() -}) - -test("pop the least used item", function (t) { - var cache = new LRU(3) - , last - - cache.set("a", "A") - cache.set("b", "B") - cache.set("c", "C") - - t.equal(cache.length, 3) - t.equal(cache.max, 3) - - // Ensure we pop a, c, b - cache.get("b", "B") - - last = cache.pop() - t.equal(last.key, "a") - t.equal(last.value, "A") - t.equal(cache.length, 2) - t.equal(cache.max, 3) - - last = cache.pop() - t.equal(last.key, "c") - t.equal(last.value, "C") - t.equal(cache.length, 1) - t.equal(cache.max, 3) - - last = cache.pop() - t.equal(last.key, "b") - t.equal(last.value, "B") - t.equal(cache.length, 0) - t.equal(cache.max, 3) - - last = cache.pop() - t.equal(last, null) - t.equal(cache.length, 0) - t.equal(cache.max, 3) - - t.end() -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js deleted file mode 100644 index eefb80d9d..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js +++ /dev/null @@ -1,52 +0,0 @@ -var test = require('tap').test -var LRU = require('../') - -test('forEach', function (t) { - var l = new LRU(5) - for (var i = 0; i < 10; i ++) { - l.set(i.toString(), i.toString(2)) - } - - var i = 9 - l.forEach(function (val, key, cache) { - t.equal(cache, l) - t.equal(key, i.toString()) - t.equal(val, i.toString(2)) - i -= 1 - }) - - // get in order of most recently used - l.get(6) - l.get(8) - - var order = [ 8, 6, 9, 7, 5 ] - var i = 0 - - l.forEach(function (val, key, cache) { - var j = order[i ++] - t.equal(cache, l) - t.equal(key, j.toString()) - t.equal(val, j.toString(2)) - }) - - t.end() -}) - -test('keys() and values()', function (t) { - var l = new LRU(5) - for (var i = 0; i < 10; i ++) { - l.set(i.toString(), i.toString(2)) - } - - t.similar(l.keys(), ['9', '8', '7', '6', '5']) - t.similar(l.values(), ['1001', '1000', '111', '110', '101']) - - // get in order of most recently used - l.get(6) - l.get(8) - - t.similar(l.keys(), ['8', '6', '9', '7', '5']) - t.similar(l.values(), ['1000', '110', '1001', '111', '101']) - - t.end() -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js deleted file mode 100644 index 7af45b022..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env node --expose_gc - -var weak = require('weak'); -var test = require('tap').test -var LRU = require('../') -var l = new LRU({ max: 10 }) -var refs = 0 -function X() { - refs ++ - weak(this, deref) -} - -function deref() { - refs -- -} - -test('no leaks', function (t) { - // fill up the cache - for (var i = 0; i < 100; i++) { - l.set(i, new X); - // throw some gets in there, too. - if (i % 2 === 0) - l.get(i / 2) - } - - gc() - - var start = process.memoryUsage() - - // capture the memory - var startRefs = refs - - // do it again, but more - for (var i = 0; i < 10000; i++) { - l.set(i, new X); - // throw some gets in there, too. - if (i % 2 === 0) - l.get(i / 2) - } - - gc() - - var end = process.memoryUsage() - t.equal(refs, startRefs, 'no leaky refs') - - console.error('start: %j\n' + - 'end: %j', start, end); - t.pass(); - t.end(); -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE deleted file mode 100644 index 0c44ae716..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) Isaac Z. Schlueter ("Author") -All rights reserved. - -The BSD License - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md deleted file mode 100644 index 7e365129e..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md +++ /dev/null @@ -1,53 +0,0 @@ -# sigmund - -Quick and dirty signatures for Objects. - -This is like a much faster `deepEquals` comparison, which returns a -string key suitable for caches and the like. - -## Usage - -```javascript -function doSomething (someObj) { - var key = sigmund(someObj, maxDepth) // max depth defaults to 10 - var cached = cache.get(key) - if (cached) return cached) - - var result = expensiveCalculation(someObj) - cache.set(key, result) - return result -} -``` - -The resulting key will be as unique and reproducible as calling -`JSON.stringify` or `util.inspect` on the object, but is much faster. -In order to achieve this speed, some differences are glossed over. -For example, the object `{0:'foo'}` will be treated identically to the -array `['foo']`. - -Also, just as there is no way to summon the soul from the scribblings -of a cocain-addled psychoanalyst, there is no way to revive the object -from the signature string that sigmund gives you. In fact, it's -barely even readable. - -As with `sys.inspect` and `JSON.stringify`, larger objects will -produce larger signature strings. - -Because sigmund is a bit less strict than the more thorough -alternatives, the strings will be shorter, and also there is a -slightly higher chance for collisions. For example, these objects -have the same signature: - - var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]} - var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']} - -Like a good Freudian, sigmund is most effective when you already have -some understanding of what you're looking for. It can help you help -yourself, but you must be willing to do some work as well. - -Cycles are handled, and cyclical objects are silently omitted (though -the key is included in the signature output.) - -The second argument is the maximum depth, which defaults to 10, -because that is the maximum object traversal depth covered by most -insurance carriers. diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js deleted file mode 100644 index 5acfd6d90..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js +++ /dev/null @@ -1,283 +0,0 @@ -// different ways to id objects -// use a req/res pair, since it's crazy deep and cyclical - -// sparseFE10 and sigmund are usually pretty close, which is to be expected, -// since they are essentially the same algorithm, except that sigmund handles -// regular expression objects properly. - - -var http = require('http') -var util = require('util') -var sigmund = require('./sigmund.js') -var sreq, sres, creq, cres, test - -http.createServer(function (q, s) { - sreq = q - sres = s - sres.end('ok') - this.close(function () { setTimeout(function () { - start() - }, 200) }) -}).listen(1337, function () { - creq = http.get({ port: 1337 }) - creq.on('response', function (s) { cres = s }) -}) - -function start () { - test = [sreq, sres, creq, cres] - // test = sreq - // sreq.sres = sres - // sreq.creq = creq - // sreq.cres = cres - - for (var i in exports.compare) { - console.log(i) - var hash = exports.compare[i]() - console.log(hash) - console.log(hash.length) - console.log('') - } - - require('bench').runMain() -} - -function customWs (obj, md, d) { - d = d || 0 - var to = typeof obj - if (to === 'undefined' || to === 'function' || to === null) return '' - if (d > md || !obj || to !== 'object') return ('' + obj).replace(/[\n ]+/g, '') - - if (Array.isArray(obj)) { - return obj.map(function (i, _, __) { - return customWs(i, md, d + 1) - }).reduce(function (a, b) { return a + b }, '') - } - - var keys = Object.keys(obj) - return keys.map(function (k, _, __) { - return k + ':' + customWs(obj[k], md, d + 1) - }).reduce(function (a, b) { return a + b }, '') -} - -function custom (obj, md, d) { - d = d || 0 - var to = typeof obj - if (to === 'undefined' || to === 'function' || to === null) return '' - if (d > md || !obj || to !== 'object') return '' + obj - - if (Array.isArray(obj)) { - return obj.map(function (i, _, __) { - return custom(i, md, d + 1) - }).reduce(function (a, b) { return a + b }, '') - } - - var keys = Object.keys(obj) - return keys.map(function (k, _, __) { - return k + ':' + custom(obj[k], md, d + 1) - }).reduce(function (a, b) { return a + b }, '') -} - -function sparseFE2 (obj, maxDepth) { - var seen = [] - var soFar = '' - function ch (v, depth) { - if (depth > maxDepth) return - if (typeof v === 'function' || typeof v === 'undefined') return - if (typeof v !== 'object' || !v) { - soFar += v - return - } - if (seen.indexOf(v) !== -1 || depth === maxDepth) return - seen.push(v) - soFar += '{' - Object.keys(v).forEach(function (k, _, __) { - // pseudo-private values. skip those. - if (k.charAt(0) === '_') return - var to = typeof v[k] - if (to === 'function' || to === 'undefined') return - soFar += k + ':' - ch(v[k], depth + 1) - }) - soFar += '}' - } - ch(obj, 0) - return soFar -} - -function sparseFE (obj, maxDepth) { - var seen = [] - var soFar = '' - function ch (v, depth) { - if (depth > maxDepth) return - if (typeof v === 'function' || typeof v === 'undefined') return - if (typeof v !== 'object' || !v) { - soFar += v - return - } - if (seen.indexOf(v) !== -1 || depth === maxDepth) return - seen.push(v) - soFar += '{' - Object.keys(v).forEach(function (k, _, __) { - // pseudo-private values. skip those. - if (k.charAt(0) === '_') return - var to = typeof v[k] - if (to === 'function' || to === 'undefined') return - soFar += k - ch(v[k], depth + 1) - }) - } - ch(obj, 0) - return soFar -} - -function sparse (obj, maxDepth) { - var seen = [] - var soFar = '' - function ch (v, depth) { - if (depth > maxDepth) return - if (typeof v === 'function' || typeof v === 'undefined') return - if (typeof v !== 'object' || !v) { - soFar += v - return - } - if (seen.indexOf(v) !== -1 || depth === maxDepth) return - seen.push(v) - soFar += '{' - for (var k in v) { - // pseudo-private values. skip those. - if (k.charAt(0) === '_') continue - var to = typeof v[k] - if (to === 'function' || to === 'undefined') continue - soFar += k - ch(v[k], depth + 1) - } - } - ch(obj, 0) - return soFar -} - -function noCommas (obj, maxDepth) { - var seen = [] - var soFar = '' - function ch (v, depth) { - if (depth > maxDepth) return - if (typeof v === 'function' || typeof v === 'undefined') return - if (typeof v !== 'object' || !v) { - soFar += v - return - } - if (seen.indexOf(v) !== -1 || depth === maxDepth) return - seen.push(v) - soFar += '{' - for (var k in v) { - // pseudo-private values. skip those. - if (k.charAt(0) === '_') continue - var to = typeof v[k] - if (to === 'function' || to === 'undefined') continue - soFar += k + ':' - ch(v[k], depth + 1) - } - soFar += '}' - } - ch(obj, 0) - return soFar -} - - -function flatten (obj, maxDepth) { - var seen = [] - var soFar = '' - function ch (v, depth) { - if (depth > maxDepth) return - if (typeof v === 'function' || typeof v === 'undefined') return - if (typeof v !== 'object' || !v) { - soFar += v - return - } - if (seen.indexOf(v) !== -1 || depth === maxDepth) return - seen.push(v) - soFar += '{' - for (var k in v) { - // pseudo-private values. skip those. - if (k.charAt(0) === '_') continue - var to = typeof v[k] - if (to === 'function' || to === 'undefined') continue - soFar += k + ':' - ch(v[k], depth + 1) - soFar += ',' - } - soFar += '}' - } - ch(obj, 0) - return soFar -} - -exports.compare = -{ - // 'custom 2': function () { - // return custom(test, 2, 0) - // }, - // 'customWs 2': function () { - // return customWs(test, 2, 0) - // }, - 'JSON.stringify (guarded)': function () { - var seen = [] - return JSON.stringify(test, function (k, v) { - if (typeof v !== 'object' || !v) return v - if (seen.indexOf(v) !== -1) return undefined - seen.push(v) - return v - }) - }, - - 'flatten 10': function () { - return flatten(test, 10) - }, - - // 'flattenFE 10': function () { - // return flattenFE(test, 10) - // }, - - 'noCommas 10': function () { - return noCommas(test, 10) - }, - - 'sparse 10': function () { - return sparse(test, 10) - }, - - 'sparseFE 10': function () { - return sparseFE(test, 10) - }, - - 'sparseFE2 10': function () { - return sparseFE2(test, 10) - }, - - sigmund: function() { - return sigmund(test, 10) - }, - - - // 'util.inspect 1': function () { - // return util.inspect(test, false, 1, false) - // }, - // 'util.inspect undefined': function () { - // util.inspect(test) - // }, - // 'util.inspect 2': function () { - // util.inspect(test, false, 2, false) - // }, - // 'util.inspect 3': function () { - // util.inspect(test, false, 3, false) - // }, - // 'util.inspect 4': function () { - // util.inspect(test, false, 4, false) - // }, - // 'util.inspect Infinity': function () { - // util.inspect(test, false, Infinity, false) - // } -} - -/** results -**/ diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json deleted file mode 100644 index cb7e2bd4b..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "sigmund", - "version": "1.0.0", - "description": "Quick and dirty signatures for Objects.", - "main": "sigmund.js", - "directories": { - "test": "test" - }, - "dependencies": {}, - "devDependencies": { - "tap": "~0.3.0" - }, - "scripts": { - "test": "tap test/*.js", - "bench": "node bench.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/sigmund" - }, - "keywords": [ - "object", - "signature", - "key", - "data", - "psychoanalysis" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "BSD", - "readme": "# sigmund\n\nQuick and dirty signatures for Objects.\n\nThis is like a much faster `deepEquals` comparison, which returns a\nstring key suitable for caches and the like.\n\n## Usage\n\n```javascript\nfunction doSomething (someObj) {\n var key = sigmund(someObj, maxDepth) // max depth defaults to 10\n var cached = cache.get(key)\n if (cached) return cached)\n\n var result = expensiveCalculation(someObj)\n cache.set(key, result)\n return result\n}\n```\n\nThe resulting key will be as unique and reproducible as calling\n`JSON.stringify` or `util.inspect` on the object, but is much faster.\nIn order to achieve this speed, some differences are glossed over.\nFor example, the object `{0:'foo'}` will be treated identically to the\narray `['foo']`.\n\nAlso, just as there is no way to summon the soul from the scribblings\nof a cocain-addled psychoanalyst, there is no way to revive the object\nfrom the signature string that sigmund gives you. In fact, it's\nbarely even readable.\n\nAs with `sys.inspect` and `JSON.stringify`, larger objects will\nproduce larger signature strings.\n\nBecause sigmund is a bit less strict than the more thorough\nalternatives, the strings will be shorter, and also there is a\nslightly higher chance for collisions. For example, these objects\nhave the same signature:\n\n var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}\n var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}\n\nLike a good Freudian, sigmund is most effective when you already have\nsome understanding of what you're looking for. It can help you help\nyourself, but you must be willing to do some work as well.\n\nCycles are handled, and cyclical objects are silently omitted (though\nthe key is included in the signature output.)\n\nThe second argument is the maximum depth, which defaults to 10,\nbecause that is the maximum object traversal depth covered by most\ninsurance carriers.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/sigmund/issues" - }, - "homepage": "https://github.com/isaacs/sigmund", - "_id": "sigmund@1.0.0", - "_from": "sigmund@~1.0.0" -} diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js deleted file mode 100644 index 82c7ab8ce..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js +++ /dev/null @@ -1,39 +0,0 @@ -module.exports = sigmund -function sigmund (subject, maxSessions) { - maxSessions = maxSessions || 10; - var notes = []; - var analysis = ''; - var RE = RegExp; - - function psychoAnalyze (subject, session) { - if (session > maxSessions) return; - - if (typeof subject === 'function' || - typeof subject === 'undefined') { - return; - } - - if (typeof subject !== 'object' || !subject || - (subject instanceof RE)) { - analysis += subject; - return; - } - - if (notes.indexOf(subject) !== -1 || session === maxSessions) return; - - notes.push(subject); - analysis += '{'; - Object.keys(subject).forEach(function (issue, _, __) { - // pseudo-private values. skip those. - if (issue.charAt(0) === '_') return; - var to = typeof subject[issue]; - if (to === 'function' || to === 'undefined') return; - analysis += issue; - psychoAnalyze(subject[issue], session + 1); - }); - } - psychoAnalyze(subject, 0); - return analysis; -} - -// vim: set softtabstop=4 shiftwidth=4: diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js deleted file mode 100644 index 50c53a13e..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js +++ /dev/null @@ -1,24 +0,0 @@ -var test = require('tap').test -var sigmund = require('../sigmund.js') - - -// occasionally there are duplicates -// that's an acceptable edge-case. JSON.stringify and util.inspect -// have some collision potential as well, though less, and collision -// detection is expensive. -var hash = '{abc/def/g{0h1i2{jkl' -var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]} -var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']} - -var obj3 = JSON.parse(JSON.stringify(obj1)) -obj3.c = /def/ -obj3.g[2].cycle = obj3 -var cycleHash = '{abc/def/g{0h1i2{jklcycle' - -test('basic', function (t) { - t.equal(sigmund(obj1), hash) - t.equal(sigmund(obj2), hash) - t.equal(sigmund(obj3), cycleHash) - t.end() -}) - diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/package.json b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/package.json deleted file mode 100644 index f8f545aa3..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me" - }, - "name": "minimatch", - "description": "a glob matcher in javascript", - "version": "0.2.14", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/minimatch.git" - }, - "main": "minimatch.js", - "scripts": { - "test": "tap test/*.js" - }, - "engines": { - "node": "*" - }, - "dependencies": { - "lru-cache": "2", - "sigmund": "~1.0.0" - }, - "devDependencies": { - "tap": "" - }, - "license": { - "type": "MIT", - "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" - }, - "readme": "# minimatch\n\nA minimal matching utility.\n\n[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)\n\n\nThis is the matching library used internally by npm.\n\nEventually, it will replace the C binding in node-glob.\n\nIt works by converting glob expressions into JavaScript `RegExp`\nobjects.\n\n## Usage\n\n```javascript\nvar minimatch = require(\"minimatch\")\n\nminimatch(\"bar.foo\", \"*.foo\") // true!\nminimatch(\"bar.foo\", \"*.bar\") // false!\nminimatch(\"bar.foo\", \"*.+(bar|foo)\", { debug: true }) // true, and noisy!\n```\n\n## Features\n\nSupports these glob features:\n\n* Brace Expansion\n* Extended glob matching\n* \"Globstar\" `**` matching\n\nSee:\n\n* `man sh`\n* `man bash`\n* `man 3 fnmatch`\n* `man 5 gitignore`\n\n## Minimatch Class\n\nCreate a minimatch object by instanting the `minimatch.Minimatch` class.\n\n```javascript\nvar Minimatch = require(\"minimatch\").Minimatch\nvar mm = new Minimatch(pattern, options)\n```\n\n### Properties\n\n* `pattern` The original pattern the minimatch object represents.\n* `options` The options supplied to the constructor.\n* `set` A 2-dimensional array of regexp or string expressions.\n Each row in the\n array corresponds to a brace-expanded pattern. Each item in the row\n corresponds to a single path-part. For example, the pattern\n `{a,b/c}/d` would expand to a set of patterns like:\n\n [ [ a, d ]\n , [ b, c, d ] ]\n\n If a portion of the pattern doesn't have any \"magic\" in it\n (that is, it's something like `\"foo\"` rather than `fo*o?`), then it\n will be left as a string rather than converted to a regular\n expression.\n\n* `regexp` Created by the `makeRe` method. A single regular expression\n expressing the entire pattern. This is useful in cases where you wish\n to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.\n* `negate` True if the pattern is negated.\n* `comment` True if the pattern is a comment.\n* `empty` True if the pattern is `\"\"`.\n\n### Methods\n\n* `makeRe` Generate the `regexp` member if necessary, and return it.\n Will return `false` if the pattern is invalid.\n* `match(fname)` Return true if the filename matches the pattern, or\n false otherwise.\n* `matchOne(fileArray, patternArray, partial)` Take a `/`-split\n filename, and match it against a single row in the `regExpSet`. This\n method is mainly for internal use, but is exposed so that it can be\n used by a glob-walker that needs to avoid excessive filesystem calls.\n\nAll other methods are internal, and will be called as necessary.\n\n## Functions\n\nThe top-level exported function has a `cache` property, which is an LRU\ncache set to store 100 items. So, calling these methods repeatedly\nwith the same pattern and options will use the same Minimatch object,\nsaving the cost of parsing it multiple times.\n\n### minimatch(path, pattern, options)\n\nMain export. Tests a path against the pattern using the options.\n\n```javascript\nvar isJS = minimatch(file, \"*.js\", { matchBase: true })\n```\n\n### minimatch.filter(pattern, options)\n\nReturns a function that tests its\nsupplied argument, suitable for use with `Array.filter`. Example:\n\n```javascript\nvar javascripts = fileList.filter(minimatch.filter(\"*.js\", {matchBase: true}))\n```\n\n### minimatch.match(list, pattern, options)\n\nMatch against the list of\nfiles, in the style of fnmatch or glob. If nothing is matched, and\noptions.nonull is set, then return a list containing the pattern itself.\n\n```javascript\nvar javascripts = minimatch.match(fileList, \"*.js\", {matchBase: true}))\n```\n\n### minimatch.makeRe(pattern, options)\n\nMake a regular expression object from the pattern.\n\n## Options\n\nAll options are `false` by default.\n\n### debug\n\nDump a ton of stuff to stderr.\n\n### nobrace\n\nDo not expand `{a,b}` and `{1..3}` brace sets.\n\n### noglobstar\n\nDisable `**` matching against multiple folder names.\n\n### dot\n\nAllow patterns to match filenames starting with a period, even if\nthe pattern does not explicitly have a period in that spot.\n\nNote that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`\nis set.\n\n### noext\n\nDisable \"extglob\" style patterns like `+(a|b)`.\n\n### nocase\n\nPerform a case-insensitive match.\n\n### nonull\n\nWhen a match is not found by `minimatch.match`, return a list containing\nthe pattern itself. When set, an empty list is returned if there are\nno matches.\n\n### matchBase\n\nIf set, then patterns without slashes will be matched\nagainst the basename of the path if it contains slashes. For example,\n`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.\n\n### nocomment\n\nSuppress the behavior of treating `#` at the start of a pattern as a\ncomment.\n\n### nonegate\n\nSuppress the behavior of treating a leading `!` character as negation.\n\n### flipNegate\n\nReturns from negate expressions the same as if they were not negated.\n(Ie, true on a hit, false on a miss.)\n\n\n## Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between minimatch and other\nimplementations, and are intentional.\n\nIf the pattern starts with a `!` character, then it is negated. Set the\n`nonegate` flag to suppress this behavior, and treat leading `!`\ncharacters normally. This is perhaps relevant if you wish to start the\npattern with a negative extglob pattern like `!(a|B)`. Multiple `!`\ncharacters at the start of a pattern will negate the pattern multiple\ntimes.\n\nIf a pattern starts with `#`, then it is treated as a comment, and\nwill not match anything. Use `\\#` to match a literal `#` at the\nstart of a line, or set the `nocomment` flag to suppress this behavior.\n\nThe double-star character `**` is supported by default, unless the\n`noglobstar` flag is set. This is supported in the manner of bsdglob\nand bash 4.1, where `**` only has special significance if it is the only\nthing in a path part. That is, `a/**/b` will match `a/x/y/b`, but\n`a/**b` will not.\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen minimatch.match returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`minimatch.match([], \"\\\\*a\\\\?\")` will return `\"\\\\*a\\\\?\"` rather than\n`\"*a?\"`. This is akin to setting the `nullglob` option in bash, except\nthat it does not resolve escaped pattern characters.\n\nIf brace expansion is not disabled, then it is performed before any\nother interpretation of the glob pattern. Thus, a pattern like\n`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded\n**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are\nchecked for validity. Since those two are valid, matching proceeds.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/minimatch/issues" - }, - "homepage": "https://github.com/isaacs/minimatch", - "_id": "minimatch@0.2.14", - "_from": "minimatch@~0.2.11" -} diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/basic.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/basic.js deleted file mode 100644 index ae7ac73c7..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/basic.js +++ /dev/null @@ -1,399 +0,0 @@ -// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test -// -// TODO: Some of these tests do very bad things with backslashes, and will -// most likely fail badly on windows. They should probably be skipped. - -var tap = require("tap") - , globalBefore = Object.keys(global) - , mm = require("../") - , files = [ "a", "b", "c", "d", "abc" - , "abd", "abe", "bb", "bcd" - , "ca", "cb", "dd", "de" - , "bdir/", "bdir/cfile"] - , next = files.concat([ "a-b", "aXb" - , ".x", ".y" ]) - - -var patterns = - [ "http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test" - , ["a*", ["a", "abc", "abd", "abe"]] - , ["X*", ["X*"], {nonull: true}] - - // allow null glob expansion - , ["X*", []] - - // isaacs: Slightly different than bash/sh/ksh - // \\* is not un-escaped to literal "*" in a failed match, - // but it does make it get treated as a literal star - , ["\\*", ["\\*"], {nonull: true}] - , ["\\**", ["\\**"], {nonull: true}] - , ["\\*\\*", ["\\*\\*"], {nonull: true}] - - , ["b*/", ["bdir/"]] - , ["c*", ["c", "ca", "cb"]] - , ["**", files] - - , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}] - , ["s/\\..*//", ["s/\\..*//"], {nonull: true}] - - , "legendary larry crashes bashes" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}] - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}] - - , "character classes" - , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]] - , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd", - "bdir/", "ca", "cb", "dd", "de"]] - , ["a*[^c]", ["abd", "abe"]] - , function () { files.push("a-b", "aXb") } - , ["a[X-]b", ["a-b", "aXb"]] - , function () { files.push(".x", ".y") } - , ["[^a-c]*", ["d", "dd", "de"]] - , function () { files.push("a*b/", "a*b/ooo") } - , ["a\\*b/*", ["a*b/ooo"]] - , ["a\\*?/*", ["a*b/ooo"]] - , ["*\\\\!*", [], {null: true}, ["echo !7"]] - , ["*\\!*", ["echo !7"], null, ["echo !7"]] - , ["*.\\*", ["r.*"], null, ["r.*"]] - , ["a[b]c", ["abc"]] - , ["a[\\b]c", ["abc"]] - , ["a?c", ["abc"]] - , ["a\\*c", [], {null: true}, ["abc"]] - , ["", [""], { null: true }, [""]] - - , "http://www.opensource.apple.com/source/bash/bash-23/" + - "bash/tests/glob-test" - , function () { files.push("man/", "man/man1/", "man/man1/bash.1") } - , ["*/man*/bash.*", ["man/man1/bash.1"]] - , ["man/man1/bash.1", ["man/man1/bash.1"]] - , ["a***c", ["abc"], null, ["abc"]] - , ["a*****?c", ["abc"], null, ["abc"]] - , ["?*****??", ["abc"], null, ["abc"]] - , ["*****??", ["abc"], null, ["abc"]] - , ["?*****?c", ["abc"], null, ["abc"]] - , ["?***?****c", ["abc"], null, ["abc"]] - , ["?***?****?", ["abc"], null, ["abc"]] - , ["?***?****", ["abc"], null, ["abc"]] - , ["*******c", ["abc"], null, ["abc"]] - , ["*******?", ["abc"], null, ["abc"]] - , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["[-abc]", ["-"], null, ["-"]] - , ["[abc-]", ["-"], null, ["-"]] - , ["\\", ["\\"], null, ["\\"]] - , ["[\\\\]", ["\\"], null, ["\\"]] - , ["[[]", ["["], null, ["["]] - , ["[", ["["], null, ["["]] - , ["[*", ["[abc"], null, ["[abc"]] - , "a right bracket shall lose its special meaning and\n" + - "represent itself in a bracket expression if it occurs\n" + - "first in the list. -- POSIX.2 2.8.3.2" - , ["[]]", ["]"], null, ["]"]] - , ["[]-]", ["]"], null, ["]"]] - , ["[a-\z]", ["p"], null, ["p"]] - , ["??**********?****?", [], { null: true }, ["abc"]] - , ["??**********?****c", [], { null: true }, ["abc"]] - , ["?************c****?****", [], { null: true }, ["abc"]] - , ["*c*?**", [], { null: true }, ["abc"]] - , ["a*****c*?**", [], { null: true }, ["abc"]] - , ["a********???*******", [], { null: true }, ["abc"]] - , ["[]", [], { null: true }, ["a"]] - , ["[abc", [], { null: true }, ["["]] - - , "nocase tests" - , ["XYZ", ["xYz"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - , ["ab*", ["ABC"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - - // [ pattern, [matches], MM opts, files, TAP opts] - , "onestar/twostar" - , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]] - , ["{/?,*}", ["/a", "bb"], {null: true} - , ["/a", "/b/b", "/a/b/c", "bb"]] - - , "dots should not match unless requested" - , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]] - - // .. and . can only match patterns starting with ., - // even when options.dot is set. - , function () { - files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"] - } - , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}] - , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}] - , ["a/*/b", ["a/c/b"], {dot:false}] - , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}] - - - // this also tests that changing the options needs - // to change the cache key, even if the pattern is - // the same! - , ["**", ["a/b","a/.d",".a/.d"], { dot: true } - , [ ".a/.d", "a/.d", "a/b"]] - - , "paren sets cannot contain slashes" - , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]] - - // brace sets trump all else. - // - // invalid glob pattern. fails on bash4 and bsdglob. - // however, in this implementation, it's easier just - // to do the intuitive thing, and let brace-expansion - // actually come before parsing any extglob patterns, - // like the documentation seems to say. - // - // XXX: if anyone complains about this, either fix it - // or tell them to grow up and stop complaining. - // - // bash/bsdglob says this: - // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]] - // but we do this instead: - , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]] - - // test partial parsing in the presence of comment/negation chars - , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]] - , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]] - - // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. - , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" - , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"] - , {} - , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]] - - - // crazy nested {,,} and *(||) tests. - , function () { - files = [ "a", "b", "c", "d" - , "ab", "ac", "ad" - , "bc", "cb" - , "bc,d", "c,db", "c,d" - , "d)", "(b|c", "*(b|c" - , "b|c", "b|cc", "cb|c" - , "x(a|b|c)", "x(a|c)" - , "(a|b|c)", "(a|c)"] - } - , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]] - , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]] - // a - // *(b|c) - // *(b|d) - , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]] - , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]] - - - // test various flag settings. - , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"] - , { noext: true } ] - , ["a?b", ["x/y/acb", "acb/"], {matchBase: true} - , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ] - , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]] - - - // begin channelling Boole and deMorgan... - , "negation tests" - , function () { - files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"] - } - - // anything that is NOT a* matches. - , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]] - - // anything that IS !a* matches. - , ["!a*", ["!ab", "!abc"], {nonegate: true}] - - // anything that IS a* matches - , ["!!a*", ["a!b"]] - - // anything that is NOT !a* matches - , ["!\\!a*", ["a!b", "d", "e", "\\!a"]] - - // negation nestled within a pattern - , function () { - files = [ "foo.js" - , "foo.bar" - // can't match this one without negative lookbehind. - , "foo.js.js" - , "blar.js" - , "foo." - , "boo.js.boo" ] - } - , ["*.!(js)", ["foo.bar", "foo.", "boo.js.boo"] ] - - // https://github.com/isaacs/minimatch/issues/5 - , function () { - files = [ 'a/b/.x/c' - , 'a/b/.x/c/d' - , 'a/b/.x/c/d/e' - , 'a/b/.x' - , 'a/b/.x/' - , 'a/.x/b' - , '.x' - , '.x/' - , '.x/a' - , '.x/a/b' - , 'a/.x/b/.x/c' - , '.x/.x' ] - } - , ["**/.x/**", [ '.x/' - , '.x/a' - , '.x/a/b' - , 'a/.x/b' - , 'a/b/.x/' - , 'a/b/.x/c' - , 'a/b/.x/c/d' - , 'a/b/.x/c/d/e' ] ] - - ] - -var regexps = - [ '/^(?:(?=.)a[^/]*?)$/', - '/^(?:(?=.)X[^/]*?)$/', - '/^(?:(?=.)X[^/]*?)$/', - '/^(?:\\*)$/', - '/^(?:(?=.)\\*[^/]*?)$/', - '/^(?:\\*\\*)$/', - '/^(?:(?=.)b[^/]*?\\/)$/', - '/^(?:(?=.)c[^/]*?)$/', - '/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/', - '/^(?:\\.\\.\\/(?!\\.)(?=.)[^/]*?\\/)$/', - '/^(?:s\\/(?=.)\\.\\.[^/]*?\\/)$/', - '/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/1\\/)$/', - '/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/\u0001\\/)$/', - '/^(?:(?!\\.)(?=.)[a-c]b[^/]*?)$/', - '/^(?:(?!\\.)(?=.)[a-y][^/]*?[^c])$/', - '/^(?:(?=.)a[^/]*?[^c])$/', - '/^(?:(?=.)a[X-]b)$/', - '/^(?:(?!\\.)(?=.)[^a-c][^/]*?)$/', - '/^(?:a\\*b\\/(?!\\.)(?=.)[^/]*?)$/', - '/^(?:(?=.)a\\*[^/]\\/(?!\\.)(?=.)[^/]*?)$/', - '/^(?:(?!\\.)(?=.)[^/]*?\\\\\\![^/]*?)$/', - '/^(?:(?!\\.)(?=.)[^/]*?\\![^/]*?)$/', - '/^(?:(?!\\.)(?=.)[^/]*?\\.\\*)$/', - '/^(?:(?=.)a[b]c)$/', - '/^(?:(?=.)a[b]c)$/', - '/^(?:(?=.)a[^/]c)$/', - '/^(?:a\\*c)$/', - 'false', - '/^(?:(?!\\.)(?=.)[^/]*?\\/(?=.)man[^/]*?\\/(?=.)bash\\.[^/]*?)$/', - '/^(?:man\\/man1\\/bash\\.1)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?c)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/', - '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/', - '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/', - '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/', - '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/', - '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', - '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/', - '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c)$/', - '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', - '/^(?:(?=.)a[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k[^/]*?[^/]*?[^/]*?)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k[^/]*?[^/]*?)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/', - '/^(?:(?!\\.)(?=.)[-abc])$/', - '/^(?:(?!\\.)(?=.)[abc-])$/', - '/^(?:\\\\)$/', - '/^(?:(?!\\.)(?=.)[\\\\])$/', - '/^(?:(?!\\.)(?=.)[\\[])$/', - '/^(?:\\[)$/', - '/^(?:(?=.)\\[(?!\\.)(?=.)[^/]*?)$/', - '/^(?:(?!\\.)(?=.)[\\]])$/', - '/^(?:(?!\\.)(?=.)[\\]-])$/', - '/^(?:(?!\\.)(?=.)[a-z])$/', - '/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/', - '/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/', - '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/', - '/^(?:(?!\\.)(?=.)[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/', - '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/', - '/^(?:\\[\\])$/', - '/^(?:\\[abc)$/', - '/^(?:(?=.)XYZ)$/i', - '/^(?:(?=.)ab[^/]*?)$/i', - '/^(?:(?!\\.)(?=.)[ia][^/][ck])$/i', - '/^(?:\\/(?!\\.)(?=.)[^/]*?|(?!\\.)(?=.)[^/]*?)$/', - '/^(?:\\/(?!\\.)(?=.)[^/]|(?!\\.)(?=.)[^/]*?)$/', - '/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/', - '/^(?:a\\/(?!(?:^|\\/)\\.{1,2}(?:$|\\/))(?=.)[^/]*?\\/b)$/', - '/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/', - '/^(?:a\\/(?!\\.)(?=.)[^/]*?\\/b)$/', - '/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/', - '/^(?:(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?)$/', - '/^(?:(?!\\.)(?=.)[^/]*?\\(a\\/b\\))$/', - '/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/', - '/^(?:(?=.)\\[(?=.)\\!a[^/]*?)$/', - '/^(?:(?=.)\\[(?=.)#a[^/]*?)$/', - '/^(?:(?=.)\\+\\(a\\|[^/]*?\\|c\\\\\\\\\\|d\\\\\\\\\\|e\\\\\\\\\\\\\\\\\\|f\\\\\\\\\\\\\\\\\\|g)$/', - '/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/', - '/^(?:a|(?!\\.)(?=.)[^/]*?\\(b\\|c|d\\))$/', - '/^(?:a|(?!\\.)(?=.)(?:b|c)*|(?!\\.)(?=.)(?:b|d)*)$/', - '/^(?:(?!\\.)(?=.)(?:a|b|c)*|(?!\\.)(?=.)(?:a|c)*)$/', - '/^(?:(?!\\.)(?=.)[^/]*?\\(a\\|b\\|c\\)|(?!\\.)(?=.)[^/]*?\\(a\\|c\\))$/', - '/^(?:(?=.)a[^/]b)$/', - '/^(?:(?=.)#[^/]*?)$/', - '/^(?!^(?:(?=.)a[^/]*?)$).*$/', - '/^(?:(?=.)\\!a[^/]*?)$/', - '/^(?:(?=.)a[^/]*?)$/', - '/^(?!^(?:(?=.)\\!a[^/]*?)$).*$/', - '/^(?:(?!\\.)(?=.)[^/]*?\\.(?:(?!js)[^/]*?))$/', - '/^(?:(?:(?!(?:\\/|^)\\.).)*?\\/\\.x\\/(?:(?!(?:\\/|^)\\.).)*?)$/' ] -var re = 0; - -tap.test("basic tests", function (t) { - var start = Date.now() - - // [ pattern, [matches], MM opts, files, TAP opts] - patterns.forEach(function (c) { - if (typeof c === "function") return c() - if (typeof c === "string") return t.comment(c) - - var pattern = c[0] - , expect = c[1].sort(alpha) - , options = c[2] || {} - , f = c[3] || files - , tapOpts = c[4] || {} - - // options.debug = true - var m = new mm.Minimatch(pattern, options) - var r = m.makeRe() - var expectRe = regexps[re++] - tapOpts.re = String(r) || JSON.stringify(r) - tapOpts.files = JSON.stringify(f) - tapOpts.pattern = pattern - tapOpts.set = m.set - tapOpts.negated = m.negate - - var actual = mm.match(f, pattern, options) - actual.sort(alpha) - - t.equivalent( actual, expect - , JSON.stringify(pattern) + " " + JSON.stringify(expect) - , tapOpts ) - - t.equal(tapOpts.re, expectRe, tapOpts) - }) - - t.comment("time=" + (Date.now() - start) + "ms") - t.end() -}) - -tap.test("global leak test", function (t) { - var globalAfter = Object.keys(global) - t.equivalent(globalAfter, globalBefore, "no new globals, please") - t.end() -}) - -function alpha (a, b) { - return a > b ? 1 : -1 -} diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/brace-expand.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/brace-expand.js deleted file mode 100644 index 7ee278a27..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/brace-expand.js +++ /dev/null @@ -1,33 +0,0 @@ -var tap = require("tap") - , minimatch = require("../") - -tap.test("brace expansion", function (t) { - // [ pattern, [expanded] ] - ; [ [ "a{b,c{d,e},{f,g}h}x{y,z}" - , [ "abxy" - , "abxz" - , "acdxy" - , "acdxz" - , "acexy" - , "acexz" - , "afhxy" - , "afhxz" - , "aghxy" - , "aghxz" ] ] - , [ "a{1..5}b" - , [ "a1b" - , "a2b" - , "a3b" - , "a4b" - , "a5b" ] ] - , [ "a{b}c", ["a{b}c"] ] - ].forEach(function (tc) { - var p = tc[0] - , expect = tc[1] - t.equivalent(minimatch.braceExpand(p), expect, p) - }) - console.error("ending") - t.end() -}) - - diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/caching.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/caching.js deleted file mode 100644 index 0fec4b0fa..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/caching.js +++ /dev/null @@ -1,14 +0,0 @@ -var Minimatch = require("../minimatch.js").Minimatch -var tap = require("tap") -tap.test("cache test", function (t) { - var mm1 = new Minimatch("a?b") - var mm2 = new Minimatch("a?b") - t.equal(mm1, mm2, "should get the same object") - // the lru should drop it after 100 entries - for (var i = 0; i < 100; i ++) { - new Minimatch("a"+i) - } - mm2 = new Minimatch("a?b") - t.notEqual(mm1, mm2, "cache should have dropped") - t.end() -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/defaults.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/defaults.js deleted file mode 100644 index 25f1f601c..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/defaults.js +++ /dev/null @@ -1,274 +0,0 @@ -// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test -// -// TODO: Some of these tests do very bad things with backslashes, and will -// most likely fail badly on windows. They should probably be skipped. - -var tap = require("tap") - , globalBefore = Object.keys(global) - , mm = require("../") - , files = [ "a", "b", "c", "d", "abc" - , "abd", "abe", "bb", "bcd" - , "ca", "cb", "dd", "de" - , "bdir/", "bdir/cfile"] - , next = files.concat([ "a-b", "aXb" - , ".x", ".y" ]) - -tap.test("basic tests", function (t) { - var start = Date.now() - - // [ pattern, [matches], MM opts, files, TAP opts] - ; [ "http://www.bashcookbook.com/bashinfo" + - "/source/bash-1.14.7/tests/glob-test" - , ["a*", ["a", "abc", "abd", "abe"]] - , ["X*", ["X*"], {nonull: true}] - - // allow null glob expansion - , ["X*", []] - - // isaacs: Slightly different than bash/sh/ksh - // \\* is not un-escaped to literal "*" in a failed match, - // but it does make it get treated as a literal star - , ["\\*", ["\\*"], {nonull: true}] - , ["\\**", ["\\**"], {nonull: true}] - , ["\\*\\*", ["\\*\\*"], {nonull: true}] - - , ["b*/", ["bdir/"]] - , ["c*", ["c", "ca", "cb"]] - , ["**", files] - - , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}] - , ["s/\\..*//", ["s/\\..*//"], {nonull: true}] - - , "legendary larry crashes bashes" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}] - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}] - - , "character classes" - , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]] - , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd", - "bdir/", "ca", "cb", "dd", "de"]] - , ["a*[^c]", ["abd", "abe"]] - , function () { files.push("a-b", "aXb") } - , ["a[X-]b", ["a-b", "aXb"]] - , function () { files.push(".x", ".y") } - , ["[^a-c]*", ["d", "dd", "de"]] - , function () { files.push("a*b/", "a*b/ooo") } - , ["a\\*b/*", ["a*b/ooo"]] - , ["a\\*?/*", ["a*b/ooo"]] - , ["*\\\\!*", [], {null: true}, ["echo !7"]] - , ["*\\!*", ["echo !7"], null, ["echo !7"]] - , ["*.\\*", ["r.*"], null, ["r.*"]] - , ["a[b]c", ["abc"]] - , ["a[\\b]c", ["abc"]] - , ["a?c", ["abc"]] - , ["a\\*c", [], {null: true}, ["abc"]] - , ["", [""], { null: true }, [""]] - - , "http://www.opensource.apple.com/source/bash/bash-23/" + - "bash/tests/glob-test" - , function () { files.push("man/", "man/man1/", "man/man1/bash.1") } - , ["*/man*/bash.*", ["man/man1/bash.1"]] - , ["man/man1/bash.1", ["man/man1/bash.1"]] - , ["a***c", ["abc"], null, ["abc"]] - , ["a*****?c", ["abc"], null, ["abc"]] - , ["?*****??", ["abc"], null, ["abc"]] - , ["*****??", ["abc"], null, ["abc"]] - , ["?*****?c", ["abc"], null, ["abc"]] - , ["?***?****c", ["abc"], null, ["abc"]] - , ["?***?****?", ["abc"], null, ["abc"]] - , ["?***?****", ["abc"], null, ["abc"]] - , ["*******c", ["abc"], null, ["abc"]] - , ["*******?", ["abc"], null, ["abc"]] - , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]] - , ["[-abc]", ["-"], null, ["-"]] - , ["[abc-]", ["-"], null, ["-"]] - , ["\\", ["\\"], null, ["\\"]] - , ["[\\\\]", ["\\"], null, ["\\"]] - , ["[[]", ["["], null, ["["]] - , ["[", ["["], null, ["["]] - , ["[*", ["[abc"], null, ["[abc"]] - , "a right bracket shall lose its special meaning and\n" + - "represent itself in a bracket expression if it occurs\n" + - "first in the list. -- POSIX.2 2.8.3.2" - , ["[]]", ["]"], null, ["]"]] - , ["[]-]", ["]"], null, ["]"]] - , ["[a-\z]", ["p"], null, ["p"]] - , ["??**********?****?", [], { null: true }, ["abc"]] - , ["??**********?****c", [], { null: true }, ["abc"]] - , ["?************c****?****", [], { null: true }, ["abc"]] - , ["*c*?**", [], { null: true }, ["abc"]] - , ["a*****c*?**", [], { null: true }, ["abc"]] - , ["a********???*******", [], { null: true }, ["abc"]] - , ["[]", [], { null: true }, ["a"]] - , ["[abc", [], { null: true }, ["["]] - - , "nocase tests" - , ["XYZ", ["xYz"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - , ["ab*", ["ABC"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true } - , ["xYz", "ABC", "IjK"]] - - // [ pattern, [matches], MM opts, files, TAP opts] - , "onestar/twostar" - , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]] - , ["{/?,*}", ["/a", "bb"], {null: true} - , ["/a", "/b/b", "/a/b/c", "bb"]] - - , "dots should not match unless requested" - , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]] - - // .. and . can only match patterns starting with ., - // even when options.dot is set. - , function () { - files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"] - } - , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}] - , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}] - , ["a/*/b", ["a/c/b"], {dot:false}] - , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}] - - - // this also tests that changing the options needs - // to change the cache key, even if the pattern is - // the same! - , ["**", ["a/b","a/.d",".a/.d"], { dot: true } - , [ ".a/.d", "a/.d", "a/b"]] - - , "paren sets cannot contain slashes" - , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]] - - // brace sets trump all else. - // - // invalid glob pattern. fails on bash4 and bsdglob. - // however, in this implementation, it's easier just - // to do the intuitive thing, and let brace-expansion - // actually come before parsing any extglob patterns, - // like the documentation seems to say. - // - // XXX: if anyone complains about this, either fix it - // or tell them to grow up and stop complaining. - // - // bash/bsdglob says this: - // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]] - // but we do this instead: - , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]] - - // test partial parsing in the presence of comment/negation chars - , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]] - , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]] - - // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped. - , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g" - , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"] - , {} - , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]] - - - // crazy nested {,,} and *(||) tests. - , function () { - files = [ "a", "b", "c", "d" - , "ab", "ac", "ad" - , "bc", "cb" - , "bc,d", "c,db", "c,d" - , "d)", "(b|c", "*(b|c" - , "b|c", "b|cc", "cb|c" - , "x(a|b|c)", "x(a|c)" - , "(a|b|c)", "(a|c)"] - } - , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]] - , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]] - // a - // *(b|c) - // *(b|d) - , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]] - , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]] - - - // test various flag settings. - , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"] - , { noext: true } ] - , ["a?b", ["x/y/acb", "acb/"], {matchBase: true} - , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ] - , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]] - - - // begin channelling Boole and deMorgan... - , "negation tests" - , function () { - files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"] - } - - // anything that is NOT a* matches. - , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]] - - // anything that IS !a* matches. - , ["!a*", ["!ab", "!abc"], {nonegate: true}] - - // anything that IS a* matches - , ["!!a*", ["a!b"]] - - // anything that is NOT !a* matches - , ["!\\!a*", ["a!b", "d", "e", "\\!a"]] - - // negation nestled within a pattern - , function () { - files = [ "foo.js" - , "foo.bar" - // can't match this one without negative lookbehind. - , "foo.js.js" - , "blar.js" - , "foo." - , "boo.js.boo" ] - } - , ["*.!(js)", ["foo.bar", "foo.", "boo.js.boo"] ] - - ].forEach(function (c) { - if (typeof c === "function") return c() - if (typeof c === "string") return t.comment(c) - - var pattern = c[0] - , expect = c[1].sort(alpha) - , options = c[2] || {} - , f = c[3] || files - , tapOpts = c[4] || {} - - // options.debug = true - var Class = mm.defaults(options).Minimatch - var m = new Class(pattern, {}) - var r = m.makeRe() - tapOpts.re = String(r) || JSON.stringify(r) - tapOpts.files = JSON.stringify(f) - tapOpts.pattern = pattern - tapOpts.set = m.set - tapOpts.negated = m.negate - - var actual = mm.match(f, pattern, options) - actual.sort(alpha) - - t.equivalent( actual, expect - , JSON.stringify(pattern) + " " + JSON.stringify(expect) - , tapOpts ) - }) - - t.comment("time=" + (Date.now() - start) + "ms") - t.end() -}) - -tap.test("global leak test", function (t) { - var globalAfter = Object.keys(global) - t.equivalent(globalAfter, globalBefore, "no new globals, please") - t.end() -}) - -function alpha (a, b) { - return a > b ? 1 : -1 -} diff --git a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/extglob-ending-with-state-char.js b/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/extglob-ending-with-state-char.js deleted file mode 100644 index 6676e2629..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/node_modules/minimatch/test/extglob-ending-with-state-char.js +++ /dev/null @@ -1,8 +0,0 @@ -var test = require('tap').test -var minimatch = require('../') - -test('extglob ending with statechar', function(t) { - t.notOk(minimatch('ax', 'a?(b*)')) - t.ok(minimatch('ax', '?(a*|b)')) - t.end() -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/package.json b/node_modules/express3-handlebars/node_modules/glob/package.json deleted file mode 100644 index 3fbf80e5b..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "name": "glob", - "description": "a little globber", - "version": "3.2.8", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-glob.git" - }, - "main": "glob.js", - "engines": { - "node": "*" - }, - "dependencies": { - "minimatch": "~0.2.11", - "inherits": "2" - }, - "devDependencies": { - "tap": "~0.4.0", - "mkdirp": "0", - "rimraf": "1" - }, - "scripts": { - "test": "tap test/*.js" - }, - "license": "BSD", - "readme": "# Glob\n\nMatch files using the patterns the shell uses, like stars and stuff.\n\nThis is a glob implementation in JavaScript. It uses the `minimatch`\nlibrary to do its matching.\n\n## Attention: node-glob users!\n\nThe API has changed dramatically between 2.x and 3.x. This library is\nnow 100% JavaScript, and the integer flags have been replaced with an\noptions object.\n\nAlso, there's an event emitter class, proper tests, and all the other\nthings you've come to expect from node modules.\n\nAnd best of all, no compilation!\n\n## Usage\n\n```javascript\nvar glob = require(\"glob\")\n\n// options is optional\nglob(\"**/*.js\", options, function (er, files) {\n // files is an array of filenames.\n // If the `nonull` option is set, and nothing\n // was found, then files is [\"**/*.js\"]\n // er is an error object or null.\n})\n```\n\n## Features\n\nPlease see the [minimatch\ndocumentation](https://github.com/isaacs/minimatch) for more details.\n\nSupports these glob features:\n\n* Brace Expansion\n* Extended glob matching\n* \"Globstar\" `**` matching\n\nSee:\n\n* `man sh`\n* `man bash`\n* `man 3 fnmatch`\n* `man 5 gitignore`\n* [minimatch documentation](https://github.com/isaacs/minimatch)\n\n## glob(pattern, [options], cb)\n\n* `pattern` {String} Pattern to be matched\n* `options` {Object}\n* `cb` {Function}\n * `err` {Error | null}\n * `matches` {Array} filenames found matching the pattern\n\nPerform an asynchronous glob search.\n\n## glob.sync(pattern, [options])\n\n* `pattern` {String} Pattern to be matched\n* `options` {Object}\n* return: {Array} filenames found matching the pattern\n\nPerform a synchronous glob search.\n\n## Class: glob.Glob\n\nCreate a Glob object by instanting the `glob.Glob` class.\n\n```javascript\nvar Glob = require(\"glob\").Glob\nvar mg = new Glob(pattern, options, cb)\n```\n\nIt's an EventEmitter, and starts walking the filesystem to find matches\nimmediately.\n\n### new glob.Glob(pattern, [options], [cb])\n\n* `pattern` {String} pattern to search for\n* `options` {Object}\n* `cb` {Function} Called when an error occurs, or matches are found\n * `err` {Error | null}\n * `matches` {Array} filenames found matching the pattern\n\nNote that if the `sync` flag is set in the options, then matches will\nbe immediately available on the `g.found` member.\n\n### Properties\n\n* `minimatch` The minimatch object that the glob uses.\n* `options` The options object passed in.\n* `error` The error encountered. When an error is encountered, the\n glob object is in an undefined state, and should be discarded.\n* `aborted` Boolean which is set to true when calling `abort()`. There\n is no way at this time to continue a glob search after aborting, but\n you can re-use the statCache to avoid having to duplicate syscalls.\n* `statCache` Collection of all the stat results the glob search\n performed.\n* `cache` Convenience object. Each field has the following possible\n values:\n * `false` - Path does not exist\n * `true` - Path exists\n * `1` - Path exists, and is not a directory\n * `2` - Path exists, and is a directory\n * `[file, entries, ...]` - Path exists, is a directory, and the\n array value is the results of `fs.readdir`\n\n### Events\n\n* `end` When the matching is finished, this is emitted with all the\n matches found. If the `nonull` option is set, and no match was found,\n then the `matches` list contains the original pattern. The matches\n are sorted, unless the `nosort` flag is set.\n* `match` Every time a match is found, this is emitted with the matched.\n* `error` Emitted when an unexpected error is encountered, or whenever\n any fs error occurs if `options.strict` is set.\n* `abort` When `abort()` is called, this event is raised.\n\n### Methods\n\n* `abort` Stop the search.\n\n### Options\n\nAll the options that can be passed to Minimatch can also be passed to\nGlob to change pattern matching behavior. Also, some have been added,\nor have glob-specific ramifications.\n\nAll options are false by default, unless otherwise noted.\n\nAll options are added to the glob object, as well.\n\n* `cwd` The current working directory in which to search. Defaults\n to `process.cwd()`.\n* `root` The place where patterns starting with `/` will be mounted\n onto. Defaults to `path.resolve(options.cwd, \"/\")` (`/` on Unix\n systems, and `C:\\` or some such on Windows.)\n* `dot` Include `.dot` files in normal matches and `globstar` matches.\n Note that an explicit dot in a portion of the pattern will always\n match dot files.\n* `nomount` By default, a pattern starting with a forward-slash will be\n \"mounted\" onto the root setting, so that a valid filesystem path is\n returned. Set this flag to disable that behavior.\n* `mark` Add a `/` character to directory matches. Note that this\n requires additional stat calls.\n* `nosort` Don't sort the results.\n* `stat` Set to true to stat *all* results. This reduces performance\n somewhat, and is completely unnecessary, unless `readdir` is presumed\n to be an untrustworthy indicator of file existence. It will cause\n ELOOP to be triggered one level sooner in the case of cyclical\n symbolic links.\n* `silent` When an unusual error is encountered\n when attempting to read a directory, a warning will be printed to\n stderr. Set the `silent` option to true to suppress these warnings.\n* `strict` When an unusual error is encountered\n when attempting to read a directory, the process will just continue on\n in search of other matches. Set the `strict` option to raise an error\n in these cases.\n* `cache` See `cache` property above. Pass in a previously generated\n cache object to save some fs calls.\n* `statCache` A cache of results of filesystem information, to prevent\n unnecessary stat calls. While it should not normally be necessary to\n set this, you may pass the statCache from one glob() call to the\n options object of another, if you know that the filesystem will not\n change between calls. (See \"Race Conditions\" below.)\n* `sync` Perform a synchronous glob search.\n* `nounique` In some cases, brace-expanded patterns can result in the\n same file showing up multiple times in the result set. By default,\n this implementation prevents duplicates in the result set.\n Set this flag to disable that behavior.\n* `nonull` Set to never return an empty set, instead returning a set\n containing the pattern itself. This is the default in glob(3).\n* `nocase` Perform a case-insensitive match. Note that case-insensitive\n filesystems will sometimes result in glob returning results that are\n case-insensitively matched anyway, since readdir and stat will not\n raise an error.\n* `debug` Set to enable debug logging in minimatch and glob.\n* `globDebug` Set to enable debug logging in glob, but not minimatch.\n\n## Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between node-glob and other\nimplementations, and are intentional.\n\nIf the pattern starts with a `!` character, then it is negated. Set the\n`nonegate` flag to suppress this behavior, and treat leading `!`\ncharacters normally. This is perhaps relevant if you wish to start the\npattern with a negative extglob pattern like `!(a|B)`. Multiple `!`\ncharacters at the start of a pattern will negate the pattern multiple\ntimes.\n\nIf a pattern starts with `#`, then it is treated as a comment, and\nwill not match anything. Use `\\#` to match a literal `#` at the\nstart of a line, or set the `nocomment` flag to suppress this behavior.\n\nThe double-star character `**` is supported by default, unless the\n`noglobstar` flag is set. This is supported in the manner of bsdglob\nand bash 4.1, where `**` only has special significance if it is the only\nthing in a path part. That is, `a/**/b` will match `a/x/y/b`, but\n`a/**b` will not.\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen glob returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`glob.match([], \"\\\\*a\\\\?\")` will return `\"\\\\*a\\\\?\"` rather than\n`\"*a?\"`. This is akin to setting the `nullglob` option in bash, except\nthat it does not resolve escaped pattern characters.\n\nIf brace expansion is not disabled, then it is performed before any\nother interpretation of the glob pattern. Thus, a pattern like\n`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded\n**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are\nchecked for validity. Since those two are valid, matching proceeds.\n\n## Windows\n\n**Please only use forward-slashes in glob expressions.**\n\nThough windows uses either `/` or `\\` as its path separator, only `/`\ncharacters are used by this glob implementation. You must use\nforward-slashes **only** in glob expressions. Back-slashes will always\nbe interpreted as escape characters, not path separators.\n\nResults from absolute patterns such as `/foo/*` are mounted onto the\nroot setting using `path.join`. On windows, this will by default result\nin `/foo/*` matching `C:\\foo\\bar.txt`.\n\n## Race Conditions\n\nGlob searching, by its very nature, is susceptible to race conditions,\nsince it relies on directory walking and such.\n\nAs a result, it is possible that a file that exists when glob looks for\nit may have been deleted or modified by the time it returns the result.\n\nAs part of its internal implementation, this program caches all stat\nand readdir calls that it makes, in order to cut down on system\noverhead. However, this also makes it even more susceptible to races,\nespecially if the cache or statCache objects are reused between glob\ncalls.\n\nUsers are thus advised not to use a glob result as a guarantee of\nfilesystem state in the face of rapid changes. For the vast majority\nof operations, this is never a problem.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-glob/issues" - }, - "homepage": "https://github.com/isaacs/node-glob", - "_id": "glob@3.2.8", - "_from": "glob@3.x" -} diff --git a/node_modules/express3-handlebars/node_modules/glob/test/00-setup.js b/node_modules/express3-handlebars/node_modules/glob/test/00-setup.js deleted file mode 100644 index 245afafda..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/00-setup.js +++ /dev/null @@ -1,176 +0,0 @@ -// just a little pre-run script to set up the fixtures. -// zz-finish cleans it up - -var mkdirp = require("mkdirp") -var path = require("path") -var i = 0 -var tap = require("tap") -var fs = require("fs") -var rimraf = require("rimraf") - -var files = -[ "a/.abcdef/x/y/z/a" -, "a/abcdef/g/h" -, "a/abcfed/g/h" -, "a/b/c/d" -, "a/bc/e/f" -, "a/c/d/c/b" -, "a/cb/e/f" -] - -var symlinkTo = path.resolve(__dirname, "a/symlink/a/b/c") -var symlinkFrom = "../.." - -files = files.map(function (f) { - return path.resolve(__dirname, f) -}) - -tap.test("remove fixtures", function (t) { - rimraf(path.resolve(__dirname, "a"), function (er) { - t.ifError(er, "remove fixtures") - t.end() - }) -}) - -files.forEach(function (f) { - tap.test(f, function (t) { - var d = path.dirname(f) - mkdirp(d, 0755, function (er) { - if (er) { - t.fail(er) - return t.bailout() - } - fs.writeFile(f, "i like tests", function (er) { - t.ifError(er, "make file") - t.end() - }) - }) - }) -}) - -if (process.platform !== "win32") { - tap.test("symlinky", function (t) { - var d = path.dirname(symlinkTo) - console.error("mkdirp", d) - mkdirp(d, 0755, function (er) { - t.ifError(er) - fs.symlink(symlinkFrom, symlinkTo, "dir", function (er) { - t.ifError(er, "make symlink") - t.end() - }) - }) - }) -} - -;["foo","bar","baz","asdf","quux","qwer","rewq"].forEach(function (w) { - w = "/tmp/glob-test/" + w - tap.test("create " + w, function (t) { - mkdirp(w, function (er) { - if (er) - throw er - t.pass(w) - t.end() - }) - }) -}) - - -// generate the bash pattern test-fixtures if possible -if (process.platform === "win32" || !process.env.TEST_REGEN) { - console.error("Windows, or TEST_REGEN unset. Using cached fixtures.") - return -} - -var spawn = require("child_process").spawn; -var globs = - // put more patterns here. - // anything that would be directly in / should be in /tmp/glob-test - ["test/a/*/+(c|g)/./d" - ,"test/a/**/[cg]/../[cg]" - ,"test/a/{b,c,d,e,f}/**/g" - ,"test/a/b/**" - ,"test/**/g" - ,"test/a/abc{fed,def}/g/h" - ,"test/a/abc{fed/g,def}/**/" - ,"test/a/abc{fed/g,def}/**///**/" - ,"test/**/a/**/" - ,"test/+(a|b|c)/a{/,bc*}/**" - ,"test/*/*/*/f" - ,"test/**/f" - ,"test/a/symlink/a/b/c/a/b/c/a/b/c//a/b/c////a/b/c/**/b/c/**" - ,"{./*/*,/tmp/glob-test/*}" - ,"{/tmp/glob-test/*,*}" // evil owl face! how you taunt me! - ,"test/a/!(symlink)/**" - ] -var bashOutput = {} -var fs = require("fs") - -globs.forEach(function (pattern) { - tap.test("generate fixture " + pattern, function (t) { - var cmd = "shopt -s globstar && " + - "shopt -s extglob && " + - "shopt -s nullglob && " + - // "shopt >&2; " + - "eval \'for i in " + pattern + "; do echo $i; done\'" - var cp = spawn("bash", ["-c", cmd], { cwd: path.dirname(__dirname) }) - var out = [] - cp.stdout.on("data", function (c) { - out.push(c) - }) - cp.stderr.pipe(process.stderr) - cp.on("close", function (code) { - out = flatten(out) - if (!out) - out = [] - else - out = cleanResults(out.split(/\r*\n/)) - - bashOutput[pattern] = out - t.notOk(code, "bash test should finish nicely") - t.end() - }) - }) -}) - -tap.test("save fixtures", function (t) { - var fname = path.resolve(__dirname, "bash-results.json") - var data = JSON.stringify(bashOutput, null, 2) + "\n" - fs.writeFile(fname, data, function (er) { - t.ifError(er) - t.end() - }) -}) - -function cleanResults (m) { - // normalize discrepancies in ordering, duplication, - // and ending slashes. - return m.map(function (m) { - return m.replace(/\/+/g, "/").replace(/\/$/, "") - }).sort(alphasort).reduce(function (set, f) { - if (f !== set[set.length - 1]) set.push(f) - return set - }, []).sort(alphasort).map(function (f) { - // de-windows - return (process.platform !== 'win32') ? f - : f.replace(/^[a-zA-Z]:\\\\/, '/').replace(/\\/g, '/') - }) -} - -function flatten (chunks) { - var s = 0 - chunks.forEach(function (c) { s += c.length }) - var out = new Buffer(s) - s = 0 - chunks.forEach(function (c) { - c.copy(out, s) - s += c.length - }) - - return out.toString().trim() -} - -function alphasort (a, b) { - a = a.toLowerCase() - b = b.toLowerCase() - return a > b ? 1 : a < b ? -1 : 0 -} diff --git a/node_modules/express3-handlebars/node_modules/glob/test/bash-comparison.js b/node_modules/express3-handlebars/node_modules/glob/test/bash-comparison.js deleted file mode 100644 index 239ed1a9c..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/bash-comparison.js +++ /dev/null @@ -1,63 +0,0 @@ -// basic test -// show that it does the same thing by default as the shell. -var tap = require("tap") -, child_process = require("child_process") -, bashResults = require("./bash-results.json") -, globs = Object.keys(bashResults) -, glob = require("../") -, path = require("path") - -// run from the root of the project -// this is usually where you're at anyway, but be sure. -process.chdir(path.resolve(__dirname, "..")) - -function alphasort (a, b) { - a = a.toLowerCase() - b = b.toLowerCase() - return a > b ? 1 : a < b ? -1 : 0 -} - -globs.forEach(function (pattern) { - var expect = bashResults[pattern] - // anything regarding the symlink thing will fail on windows, so just skip it - if (process.platform === "win32" && - expect.some(function (m) { - return /\/symlink\//.test(m) - })) - return - - tap.test(pattern, function (t) { - glob(pattern, function (er, matches) { - if (er) - throw er - - // sort and unmark, just to match the shell results - matches = cleanResults(matches) - - t.deepEqual(matches, expect, pattern) - t.end() - }) - }) - - tap.test(pattern + " sync", function (t) { - var matches = cleanResults(glob.sync(pattern)) - - t.deepEqual(matches, expect, "should match shell") - t.end() - }) -}) - -function cleanResults (m) { - // normalize discrepancies in ordering, duplication, - // and ending slashes. - return m.map(function (m) { - return m.replace(/\/+/g, "/").replace(/\/$/, "") - }).sort(alphasort).reduce(function (set, f) { - if (f !== set[set.length - 1]) set.push(f) - return set - }, []).sort(alphasort).map(function (f) { - // de-windows - return (process.platform !== 'win32') ? f - : f.replace(/^[a-zA-Z]:[\/\\]+/, '/').replace(/[\\\/]+/g, '/') - }) -} diff --git a/node_modules/express3-handlebars/node_modules/glob/test/bash-results.json b/node_modules/express3-handlebars/node_modules/glob/test/bash-results.json deleted file mode 100644 index 593215cd9..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/bash-results.json +++ /dev/null @@ -1,350 +0,0 @@ -{ - "test/a/*/+(c|g)/./d": [ - "test/a/b/c/./d" - ], - "test/a/**/[cg]/../[cg]": [ - "test/a/abcdef/g/../g", - "test/a/abcfed/g/../g", - "test/a/b/c/../c", - "test/a/c/../c", - "test/a/c/d/c/../c", - "test/a/symlink/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c" - ], - "test/a/{b,c,d,e,f}/**/g": [], - "test/a/b/**": [ - "test/a/b", - "test/a/b/c", - "test/a/b/c/d" - ], - "test/**/g": [ - "test/a/abcdef/g", - "test/a/abcfed/g" - ], - "test/a/abc{fed,def}/g/h": [ - "test/a/abcdef/g/h", - "test/a/abcfed/g/h" - ], - "test/a/abc{fed/g,def}/**/": [ - "test/a/abcdef", - "test/a/abcdef/g", - "test/a/abcfed/g" - ], - "test/a/abc{fed/g,def}/**///**/": [ - "test/a/abcdef", - "test/a/abcdef/g", - "test/a/abcfed/g" - ], - "test/**/a/**/": [ - "test/a", - "test/a/abcdef", - "test/a/abcdef/g", - "test/a/abcfed", - "test/a/abcfed/g", - "test/a/b", - "test/a/b/c", - "test/a/bc", - "test/a/bc/e", - "test/a/c", - "test/a/c/d", - "test/a/c/d/c", - "test/a/cb", - "test/a/cb/e", - "test/a/symlink", - "test/a/symlink/a", - "test/a/symlink/a/b", - "test/a/symlink/a/b/c", - "test/a/symlink/a/b/c/a", - "test/a/symlink/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b" - ], - "test/+(a|b|c)/a{/,bc*}/**": [ - "test/a/abcdef", - "test/a/abcdef/g", - "test/a/abcdef/g/h", - "test/a/abcfed", - "test/a/abcfed/g", - "test/a/abcfed/g/h" - ], - "test/*/*/*/f": [ - "test/a/bc/e/f", - "test/a/cb/e/f" - ], - "test/**/f": [ - "test/a/bc/e/f", - "test/a/cb/e/f" - ], - "test/a/symlink/a/b/c/a/b/c/a/b/c//a/b/c////a/b/c/**/b/c/**": [ - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b", - "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c" - ], - "{./*/*,/tmp/glob-test/*}": [ - "./examples/g.js", - "./examples/usr-local.js", - "./node_modules/inherits", - "./node_modules/minimatch", - "./node_modules/mkdirp", - "./node_modules/rimraf", - "./node_modules/tap", - "./test/00-setup.js", - "./test/a", - "./test/bash-comparison.js", - "./test/bash-results.json", - "./test/cwd-test.js", - "./test/globstar-match.js", - "./test/mark.js", - "./test/new-glob-optional-options.js", - "./test/nocase-nomagic.js", - "./test/pause-resume.js", - "./test/root-nomount.js", - "./test/root.js", - "./test/stat.js", - "./test/zz-cleanup.js", - "/tmp/glob-test/asdf", - "/tmp/glob-test/bar", - "/tmp/glob-test/baz", - "/tmp/glob-test/foo", - "/tmp/glob-test/quux", - "/tmp/glob-test/qwer", - "/tmp/glob-test/rewq" - ], - "{/tmp/glob-test/*,*}": [ - "/tmp/glob-test/asdf", - "/tmp/glob-test/bar", - "/tmp/glob-test/baz", - "/tmp/glob-test/foo", - "/tmp/glob-test/quux", - "/tmp/glob-test/qwer", - "/tmp/glob-test/rewq", - "examples", - "glob.js", - "LICENSE", - "node_modules", - "package.json", - "README.md", - "test" - ], - "test/a/!(symlink)/**": [ - "test/a/abcdef", - "test/a/abcdef/g", - "test/a/abcdef/g/h", - "test/a/abcfed", - "test/a/abcfed/g", - "test/a/abcfed/g/h", - "test/a/b", - "test/a/b/c", - "test/a/b/c/d", - "test/a/bc", - "test/a/bc/e", - "test/a/bc/e/f", - "test/a/c", - "test/a/c/d", - "test/a/c/d/c", - "test/a/c/d/c/b", - "test/a/cb", - "test/a/cb/e", - "test/a/cb/e/f" - ] -} diff --git a/node_modules/express3-handlebars/node_modules/glob/test/cwd-test.js b/node_modules/express3-handlebars/node_modules/glob/test/cwd-test.js deleted file mode 100644 index 352c27efa..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/cwd-test.js +++ /dev/null @@ -1,55 +0,0 @@ -var tap = require("tap") - -var origCwd = process.cwd() -process.chdir(__dirname) - -tap.test("changing cwd and searching for **/d", function (t) { - var glob = require('../') - var path = require('path') - t.test('.', function (t) { - glob('**/d', function (er, matches) { - t.ifError(er) - t.like(matches, [ 'a/b/c/d', 'a/c/d' ]) - t.end() - }) - }) - - t.test('a', function (t) { - glob('**/d', {cwd:path.resolve('a')}, function (er, matches) { - t.ifError(er) - t.like(matches, [ 'b/c/d', 'c/d' ]) - t.end() - }) - }) - - t.test('a/b', function (t) { - glob('**/d', {cwd:path.resolve('a/b')}, function (er, matches) { - t.ifError(er) - t.like(matches, [ 'c/d' ]) - t.end() - }) - }) - - t.test('a/b/', function (t) { - glob('**/d', {cwd:path.resolve('a/b/')}, function (er, matches) { - t.ifError(er) - t.like(matches, [ 'c/d' ]) - t.end() - }) - }) - - t.test('.', function (t) { - glob('**/d', {cwd: process.cwd()}, function (er, matches) { - t.ifError(er) - t.like(matches, [ 'a/b/c/d', 'a/c/d' ]) - t.end() - }) - }) - - t.test('cd -', function (t) { - process.chdir(origCwd) - t.end() - }) - - t.end() -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/test/globstar-match.js b/node_modules/express3-handlebars/node_modules/glob/test/globstar-match.js deleted file mode 100644 index 9b234fa2a..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/globstar-match.js +++ /dev/null @@ -1,19 +0,0 @@ -var Glob = require("../glob.js").Glob -var test = require('tap').test - -test('globstar should not have dupe matches', function(t) { - var pattern = 'a/**/[gh]' - var g = new Glob(pattern, { cwd: __dirname }) - var matches = [] - g.on('match', function(m) { - console.error('match %j', m) - matches.push(m) - }) - g.on('end', function(set) { - console.error('set', set) - matches = matches.sort() - set = set.sort() - t.same(matches, set, 'should have same set of matches') - t.end() - }) -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/test/mark.js b/node_modules/express3-handlebars/node_modules/glob/test/mark.js deleted file mode 100644 index e74282073..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/mark.js +++ /dev/null @@ -1,82 +0,0 @@ -var test = require("tap").test -var glob = require('../') -process.chdir(__dirname) - -test("mark, no / on pattern", function (t) { - glob("a/*", {mark: true}, function (er, results) { - if (er) - throw er - var expect = [ 'a/abcdef/', - 'a/abcfed/', - 'a/b/', - 'a/bc/', - 'a/c/', - 'a/cb/' ] - - if (process.platform !== "win32") - expect.push('a/symlink/') - - t.same(results, expect) - t.end() - }).on('match', function(m) { - t.similar(m, /\/$/) - }) -}) - -test("mark=false, no / on pattern", function (t) { - glob("a/*", function (er, results) { - if (er) - throw er - var expect = [ 'a/abcdef', - 'a/abcfed', - 'a/b', - 'a/bc', - 'a/c', - 'a/cb' ] - - if (process.platform !== "win32") - expect.push('a/symlink') - t.same(results, expect) - t.end() - }).on('match', function(m) { - t.similar(m, /[^\/]$/) - }) -}) - -test("mark=true, / on pattern", function (t) { - glob("a/*/", {mark: true}, function (er, results) { - if (er) - throw er - var expect = [ 'a/abcdef/', - 'a/abcfed/', - 'a/b/', - 'a/bc/', - 'a/c/', - 'a/cb/' ] - if (process.platform !== "win32") - expect.push('a/symlink/') - t.same(results, expect) - t.end() - }).on('match', function(m) { - t.similar(m, /\/$/) - }) -}) - -test("mark=false, / on pattern", function (t) { - glob("a/*/", function (er, results) { - if (er) - throw er - var expect = [ 'a/abcdef/', - 'a/abcfed/', - 'a/b/', - 'a/bc/', - 'a/c/', - 'a/cb/' ] - if (process.platform !== "win32") - expect.push('a/symlink/') - t.same(results, expect) - t.end() - }).on('match', function(m) { - t.similar(m, /\/$/) - }) -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/test/new-glob-optional-options.js b/node_modules/express3-handlebars/node_modules/glob/test/new-glob-optional-options.js deleted file mode 100644 index 3e7dc5acb..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/new-glob-optional-options.js +++ /dev/null @@ -1,10 +0,0 @@ -var Glob = require('../glob.js').Glob; -var test = require('tap').test; - -test('new glob, with cb, and no options', function (t) { - new Glob(__filename, function(er, results) { - if (er) throw er; - t.same(results, [__filename]); - t.end(); - }); -}); diff --git a/node_modules/express3-handlebars/node_modules/glob/test/nocase-nomagic.js b/node_modules/express3-handlebars/node_modules/glob/test/nocase-nomagic.js deleted file mode 100644 index 2503f2310..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/nocase-nomagic.js +++ /dev/null @@ -1,113 +0,0 @@ -var fs = require('fs'); -var test = require('tap').test; -var glob = require('../'); - -test('mock fs', function(t) { - var stat = fs.stat - var statSync = fs.statSync - var readdir = fs.readdir - var readdirSync = fs.readdirSync - - function fakeStat(path) { - var ret - switch (path.toLowerCase()) { - case '/tmp': case '/tmp/': - ret = { isDirectory: function() { return true } } - break - case '/tmp/a': - ret = { isDirectory: function() { return false } } - break - } - return ret - } - - fs.stat = function(path, cb) { - var f = fakeStat(path); - if (f) { - process.nextTick(function() { - cb(null, f) - }) - } else { - stat.call(fs, path, cb) - } - } - - fs.statSync = function(path) { - return fakeStat(path) || statSync.call(fs, path) - } - - function fakeReaddir(path) { - var ret - switch (path.toLowerCase()) { - case '/tmp': case '/tmp/': - ret = [ 'a', 'A' ] - break - case '/': - ret = ['tmp', 'tMp', 'tMP', 'TMP'] - } - return ret - } - - fs.readdir = function(path, cb) { - var f = fakeReaddir(path) - if (f) - process.nextTick(function() { - cb(null, f) - }) - else - readdir.call(fs, path, cb) - } - - fs.readdirSync = function(path) { - return fakeReaddir(path) || readdirSync.call(fs, path) - } - - t.pass('mocked') - t.end() -}) - -test('nocase, nomagic', function(t) { - var n = 2 - var want = [ '/TMP/A', - '/TMP/a', - '/tMP/A', - '/tMP/a', - '/tMp/A', - '/tMp/a', - '/tmp/A', - '/tmp/a' ] - glob('/tmp/a', { nocase: true }, function(er, res) { - if (er) - throw er - t.same(res.sort(), want) - if (--n === 0) t.end() - }) - glob('/tmp/A', { nocase: true }, function(er, res) { - if (er) - throw er - t.same(res.sort(), want) - if (--n === 0) t.end() - }) -}) - -test('nocase, with some magic', function(t) { - t.plan(2) - var want = [ '/TMP/A', - '/TMP/a', - '/tMP/A', - '/tMP/a', - '/tMp/A', - '/tMp/a', - '/tmp/A', - '/tmp/a' ] - glob('/tmp/*', { nocase: true }, function(er, res) { - if (er) - throw er - t.same(res.sort(), want) - }) - glob('/tmp/*', { nocase: true }, function(er, res) { - if (er) - throw er - t.same(res.sort(), want) - }) -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/test/pause-resume.js b/node_modules/express3-handlebars/node_modules/glob/test/pause-resume.js deleted file mode 100644 index e1ffbab1c..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/pause-resume.js +++ /dev/null @@ -1,73 +0,0 @@ -// show that no match events happen while paused. -var tap = require("tap") -, child_process = require("child_process") -// just some gnarly pattern with lots of matches -, pattern = "test/a/!(symlink)/**" -, bashResults = require("./bash-results.json") -, patterns = Object.keys(bashResults) -, glob = require("../") -, Glob = glob.Glob -, path = require("path") - -// run from the root of the project -// this is usually where you're at anyway, but be sure. -process.chdir(path.resolve(__dirname, "..")) - -function alphasort (a, b) { - a = a.toLowerCase() - b = b.toLowerCase() - return a > b ? 1 : a < b ? -1 : 0 -} - -function cleanResults (m) { - // normalize discrepancies in ordering, duplication, - // and ending slashes. - return m.map(function (m) { - return m.replace(/\/+/g, "/").replace(/\/$/, "") - }).sort(alphasort).reduce(function (set, f) { - if (f !== set[set.length - 1]) set.push(f) - return set - }, []).sort(alphasort).map(function (f) { - // de-windows - return (process.platform !== 'win32') ? f - : f.replace(/^[a-zA-Z]:\\\\/, '/').replace(/\\/g, '/') - }) -} - -var globResults = [] -tap.test("use a Glob object, and pause/resume it", function (t) { - var g = new Glob(pattern) - , paused = false - , res = [] - , expect = bashResults[pattern] - - g.on("pause", function () { - console.error("pause") - }) - - g.on("resume", function () { - console.error("resume") - }) - - g.on("match", function (m) { - t.notOk(g.paused, "must not be paused") - globResults.push(m) - g.pause() - t.ok(g.paused, "must be paused") - setTimeout(g.resume.bind(g), 10) - }) - - g.on("end", function (matches) { - t.pass("reached glob end") - globResults = cleanResults(globResults) - matches = cleanResults(matches) - t.deepEqual(matches, globResults, - "end event matches should be the same as match events") - - t.deepEqual(matches, expect, - "glob matches should be the same as bash results") - - t.end() - }) -}) - diff --git a/node_modules/express3-handlebars/node_modules/glob/test/root-nomount.js b/node_modules/express3-handlebars/node_modules/glob/test/root-nomount.js deleted file mode 100644 index 3ac5979b0..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/root-nomount.js +++ /dev/null @@ -1,39 +0,0 @@ -var tap = require("tap") - -var origCwd = process.cwd() -process.chdir(__dirname) - -tap.test("changing root and searching for /b*/**", function (t) { - var glob = require('../') - var path = require('path') - t.test('.', function (t) { - glob('/b*/**', { globDebug: true, root: '.', nomount: true }, function (er, matches) { - t.ifError(er) - t.like(matches, []) - t.end() - }) - }) - - t.test('a', function (t) { - glob('/b*/**', { globDebug: true, root: path.resolve('a'), nomount: true }, function (er, matches) { - t.ifError(er) - t.like(matches, [ '/b', '/b/c', '/b/c/d', '/bc', '/bc/e', '/bc/e/f' ]) - t.end() - }) - }) - - t.test('root=a, cwd=a/b', function (t) { - glob('/b*/**', { globDebug: true, root: 'a', cwd: path.resolve('a/b'), nomount: true }, function (er, matches) { - t.ifError(er) - t.like(matches, [ '/b', '/b/c', '/b/c/d', '/bc', '/bc/e', '/bc/e/f' ]) - t.end() - }) - }) - - t.test('cd -', function (t) { - process.chdir(origCwd) - t.end() - }) - - t.end() -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/test/root.js b/node_modules/express3-handlebars/node_modules/glob/test/root.js deleted file mode 100644 index 95c23f99c..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/root.js +++ /dev/null @@ -1,46 +0,0 @@ -var t = require("tap") - -var origCwd = process.cwd() -process.chdir(__dirname) - -var glob = require('../') -var path = require('path') - -t.test('.', function (t) { - glob('/b*/**', { globDebug: true, root: '.' }, function (er, matches) { - t.ifError(er) - t.like(matches, []) - t.end() - }) -}) - - -t.test('a', function (t) { - console.error("root=" + path.resolve('a')) - glob('/b*/**', { globDebug: true, root: path.resolve('a') }, function (er, matches) { - t.ifError(er) - var wanted = [ - '/b', '/b/c', '/b/c/d', '/bc', '/bc/e', '/bc/e/f' - ].map(function (m) { - return path.join(path.resolve('a'), m).replace(/\\/g, '/') - }) - - t.like(matches, wanted) - t.end() - }) -}) - -t.test('root=a, cwd=a/b', function (t) { - glob('/b*/**', { globDebug: true, root: 'a', cwd: path.resolve('a/b') }, function (er, matches) { - t.ifError(er) - t.like(matches, [ '/b', '/b/c', '/b/c/d', '/bc', '/bc/e', '/bc/e/f' ].map(function (m) { - return path.join(path.resolve('a'), m).replace(/\\/g, '/') - })) - t.end() - }) -}) - -t.test('cd -', function (t) { - process.chdir(origCwd) - t.end() -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/test/stat.js b/node_modules/express3-handlebars/node_modules/glob/test/stat.js deleted file mode 100644 index 62917114b..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/stat.js +++ /dev/null @@ -1,32 +0,0 @@ -var glob = require('../') -var test = require('tap').test -var path = require('path') - -test('stat all the things', function(t) { - var g = new glob.Glob('a/*abc*/**', { stat: true, cwd: __dirname }) - var matches = [] - g.on('match', function(m) { - matches.push(m) - }) - var stats = [] - g.on('stat', function(m) { - stats.push(m) - }) - g.on('end', function(eof) { - stats = stats.sort() - matches = matches.sort() - eof = eof.sort() - t.same(stats, matches) - t.same(eof, matches) - var cache = Object.keys(this.statCache) - t.same(cache.map(function (f) { - return path.relative(__dirname, f) - }).sort(), matches) - - cache.forEach(function(c) { - t.equal(typeof this.statCache[c], 'object') - }, this) - - t.end() - }) -}) diff --git a/node_modules/express3-handlebars/node_modules/glob/test/zz-cleanup.js b/node_modules/express3-handlebars/node_modules/glob/test/zz-cleanup.js deleted file mode 100644 index e085f0fa7..000000000 --- a/node_modules/express3-handlebars/node_modules/glob/test/zz-cleanup.js +++ /dev/null @@ -1,11 +0,0 @@ -// remove the fixtures -var tap = require("tap") -, rimraf = require("rimraf") -, path = require("path") - -tap.test("cleanup fixtures", function (t) { - rimraf(path.resolve(__dirname, "a"), function (er) { - t.ifError(er, "removed") - t.end() - }) -}) diff --git a/node_modules/express3-handlebars/node_modules/handlebars/.npmignore b/node_modules/express3-handlebars/node_modules/handlebars/.npmignore deleted file mode 100644 index 366b45408..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/.npmignore +++ /dev/null @@ -1,23 +0,0 @@ -.DS_Store -.gitignore -.rvmrc -.jshintrc -.travis.yml -.rspec -Gemfile -Gemfile.lock -Rakefile -Gruntfile.js -*.gemspec -*.nuspec -bench/* -configurations/* -components/* -dist/cdnjs/* -dist/components/* -spec/* -src/* -tasks/* -tmp/* -publish/* -vendor/* diff --git a/node_modules/express3-handlebars/node_modules/handlebars/LICENSE b/node_modules/express3-handlebars/node_modules/handlebars/LICENSE deleted file mode 100644 index f466a93fd..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (C) 2011 by Yehuda Katz - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express3-handlebars/node_modules/handlebars/README.markdown b/node_modules/express3-handlebars/node_modules/handlebars/README.markdown deleted file mode 100644 index 0297c3589..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/README.markdown +++ /dev/null @@ -1,458 +0,0 @@ -[![Travis Build Status](https://travis-ci.org/wycats/handlebars.js.png?branch=master)](https://travis-ci.org/wycats/handlebars.js) -[![Selenium Test Status](https://saucelabs.com/buildstatus/handlebars)](https://saucelabs.com/u/handlebars) - -Handlebars.js -============= - -Handlebars.js is an extension to the [Mustache templating -language](http://mustache.github.com/) created by Chris Wanstrath. -Handlebars.js and Mustache are both logicless templating languages that -keep the view and the code separated like we all know they should be. - -Checkout the official Handlebars docs site at -[http://www.handlebarsjs.com](http://www.handlebarsjs.com). - -Installing ----------- -Installing Handlebars is easy. Simply download the package [from the official site](http://handlebarsjs.com/) or the [bower repository][bower-repo] and add it to your web pages (you should usually use the most recent version). - -Alternatively, if you prefer having the latest version of handlebars from -the 'master' branch, passing builds of the 'master' branch are automatically -published to S3. You may download the latest passing master build by grabbing -a `handlebars-latest.js` file from the [builds page][builds-page]. When the -build is published, it is also available as a `handlebars-gitSHA.js` file on -the builds page if you need a version to refer to others. -`handlebars-runtime.js` builds are also available. - -**Note**: The S3 builds page is provided as a convenience for the community, -but you should not use it for hosting Handlebars in production. - -Usage ------ -In general, the syntax of Handlebars.js templates is a superset -of Mustache templates. For basic syntax, check out the [Mustache -manpage](http://mustache.github.com/mustache.5.html). - -Once you have a template, use the `Handlebars.compile` method to compile -the template into a function. The generated function takes a context -argument, which will be used to render the template. - -```js -var source = "

    Hello, my name is {{name}}. I am from {{hometown}}. I have " + - "{{kids.length}} kids:

    " + - "
      {{#kids}}
    • {{name}} is {{age}}
    • {{/kids}}
    "; -var template = Handlebars.compile(source); - -var data = { "name": "Alan", "hometown": "Somewhere, TX", - "kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]}; -var result = template(data); - -// Would render: -//

    Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:

    -//
      -//
    • Jimmy is 12
    • -//
    • Sally is 4
    • -//
    -``` - - -Registering Helpers -------------------- - -You can register helpers that Handlebars will use when evaluating your -template. Here's an example, which assumes that your objects have a URL -embedded in them, as well as the text for a link: - -```js -Handlebars.registerHelper('link_to', function() { - return "
    " + this.body + ""; -}); - -var context = { posts: [{url: "/hello-world", body: "Hello World!"}] }; -var source = "
      {{#posts}}
    • {{{link_to}}}
    • {{/posts}}
    " - -var template = Handlebars.compile(source); -template(context); - -// Would render: -// -// -``` - -Helpers take precedence over fields defined on the context. To access a field -that is masked by a helper, a path reference may be used. In the example above -a field named `link_to` on the `context` object would be referenced using: - -``` -{{./link_to}} -``` - -Escaping --------- - -By default, the `{{expression}}` syntax will escape its contents. This -helps to protect you against accidental XSS problems caused by malicious -data passed from the server as JSON. - -To explicitly *not* escape the contents, use the triple-mustache -(`{{{}}}`). You have seen this used in the above example. - - -Differences Between Handlebars.js and Mustache ----------------------------------------------- -Handlebars.js adds a couple of additional features to make writing -templates easier and also changes a tiny detail of how partials work. - -### Paths - -Handlebars.js supports an extended expression syntax that we call paths. -Paths are made up of typical expressions and . characters. Expressions -allow you to not only display data from the current context, but to -display data from contexts that are descendants and ancestors of the -current context. - -To display data from descendant contexts, use the `.` character. So, for -example, if your data were structured like: - -```js -var data = {"person": { "name": "Alan" }, "company": {"name": "Rad, Inc." } }; -``` - -You could display the person's name from the top-level context with the -following expression: - -``` -{{person.name}} -``` - -You can backtrack using `../`. For example, if you've already traversed -into the person object you could still display the company's name with -an expression like `{{../company.name}}`, so: - -``` -{{#person}}{{name}} - {{../company.name}}{{/person}} -``` - -would render: - -``` -Alan - Rad, Inc. -``` - -### Strings - -When calling a helper, you can pass paths or Strings as parameters. For -instance: - -```js -Handlebars.registerHelper('link_to', function(title, options) { - return "" + title + "!" -}); - -var context = { posts: [{url: "/hello-world", body: "Hello World!"}] }; -var source = '
      {{#posts}}
    • {{{link_to "Post"}}}
    • {{/posts}}
    ' - -var template = Handlebars.compile(source); -template(context); - -// Would render: -// -// -``` - -When you pass a String as a parameter to a helper, the literal String -gets passed to the helper function. - - -### Block Helpers - -Handlebars.js also adds the ability to define block helpers. Block -helpers are functions that can be called from anywhere in the template. -Here's an example: - -```js -var source = "
      {{#people}}
    • {{#link}}{{name}}{{/link}}
    • {{/people}}
    "; -Handlebars.registerHelper('link', function(options) { - return '' + options.fn(this) + ''; -}); -var template = Handlebars.compile(source); - -var data = { "people": [ - { "name": "Alan", "id": 1 }, - { "name": "Yehuda", "id": 2 } - ]}; -template(data); - -// Should render: -// -``` - -Whenever the block helper is called it is given one or more parameters, -any arguments that are passed in the helper in the call and an `options` -object containing the `fn` function which executes the block's child. -The block's current context may be accessed through `this`. - -Block helpers have the same syntax as mustache sections but should not be -confused with one another. Sections are akin to an implicit `each` or -`with` statement depending on the input data and helpers are explicit -pieces of code that are free to implement whatever behavior they like. -The [mustache spec](http://mustache.github.io/mustache.5.html) -defines the exact behavior of sections. In the case of name conflicts, -helpers are given priority. - -### Partials - -You can register additional templates as partials, which will be used by -Handlebars when it encounters a partial (`{{> partialName}}`). Partials -can either be String templates or compiled template functions. Here's an -example: - -```js -var source = "
      {{#people}}
    • {{> link}}
    • {{/people}}
    "; - -Handlebars.registerPartial('link', '{{name}}') -var template = Handlebars.compile(source); - -var data = { "people": [ - { "name": "Alan", "id": 1 }, - { "name": "Yehuda", "id": 2 } - ]}; - -template(data); - -// Should render: -// -``` - -### Comments - -You can add comments to your templates with the following syntax: - -```js -{{! This is a comment }} -``` - -You can also use real html comments if you want them to end up in the output. - -```html -
    - {{! This comment will not end up in the output }} - -
    -``` - - -Precompiling Templates ----------------------- - -Handlebars allows templates to be precompiled and included as javascript -code rather than the handlebars template allowing for faster startup time. - -### Installation -The precompiler script may be installed via npm using the `npm install -g handlebars` -command. - -### Usage - -
    -Precompile handlebar templates.
    -Usage: handlebars template...
    -
    -Options:
    -  -a, --amd            Create an AMD format function (allows loading with RequireJS)          [boolean]
    -  -f, --output         Output File                                                            [string]
    -  -k, --known          Known helpers                                                          [string]
    -  -o, --knownOnly      Known helpers only                                                     [boolean]
    -  -m, --min            Minimize output                                                        [boolean]
    -  -s, --simple         Output template function only.                                         [boolean]
    -  -r, --root           Template root. Base value that will be stripped from template names.   [string]
    -  -c, --commonjs       Exports CommonJS style, path to Handlebars module                      [string]
    -  -h, --handlebarPath  Path to handlebar.js (only valid for amd-style)                        [string]
    -  -n, --namespace      Template namespace                                                     [string]
    -  -p, --partial        Compiling a partial template                                           [boolean]
    -  -d, --data           Include data when compiling                                            [boolean]
    -  -e, --extension      Template extension.                                                    [string]
    -  -b, --bom            Removes the BOM (Byte Order Mark) from the beginning of the templates. [boolean]
    -
    - -If using the precompiler's normal mode, the resulting templates will be -stored to the `Handlebars.templates` object using the relative template -name sans the extension. These templates may be executed in the same -manner as templates. - -If using the simple mode the precompiler will generate a single -javascript method. To execute this method it must be passed to the using -the `Handlebars.template` method and the resulting object may be as -normal. - -### Optimizations - -- Rather than using the full _handlebars.js_ library, implementations that - do not need to compile templates at runtime may include _handlebars.runtime.js_ - whose min+gzip size is approximately 1k. -- If a helper is known to exist in the target environment they may be defined - using the `--known name` argument may be used to optimize accesses to these - helpers for size and speed. -- When all helpers are known in advance the `--knownOnly` argument may be used - to optimize all block helper references. -- Implementations that do not use `@data` variables can improve performance of - iteration centric templates by specifying `{data: false}` in the compiler options. - -Supported Environments ----------------------- - -Handlebars has been designed to work in any ECMAScript 3 environment. This includes - -- Node.js -- Chrome -- Firefox -- Safari 5+ -- Opera 11+ -- IE 6+ - -Older versions and other runtimes are likely to work but have not been formally -tested. - -[![Selenium Test Status](https://saucelabs.com/browser-matrix/handlebars.svg)](https://saucelabs.com/u/handlebars) - -Performance ------------ - -In a rough performance test, precompiled Handlebars.js templates (in -the original version of Handlebars.js) rendered in about half the -time of Mustache templates. It would be a shame if it were any other -way, since they were precompiled, but the difference in architecture -does have some big performance advantages. Justin Marney, a.k.a. -[gotascii](http://github.com/gotascii), confirmed that with an -[independent test](http://sorescode.com/2010/09/12/benchmarks.html). The -rewritten Handlebars (current version) is faster than the old version, -and we will have some benchmarks in the near future. - - -Building --------- - -To build handlebars, just run `grunt build`, and the build will output to the `dist` directory. - - -Upgrading ---------- - -See [release-notes.md](https://github.com/wycats/handlebars.js/blob/master/release-notes.md) for upgrade notes. - -Known Issues ------------- -* Handlebars.js can be cryptic when there's an error while rendering. -* Using a variable, helper, or partial named `class` causes errors in IE browsers. (Instead, use `className`) - -Handlebars in the Wild ----------------------- - -* [Assemble](http://assemble.io), by [@jonschlinkert](https://github.com/jonschlinkert) - and [@doowb](https://github.com/doowb), is a static site generator that uses Handlebars.js - as its template engine. -* [CoSchedule](http://coschedule.com) An editorial calendar for WordPress that uses Handlebars.js -* [Ember.js](http://www.emberjs.com) makes Handlebars.js the primary way to - structure your views, also with automatic data binding support. -* [Ghost](https://ghost.org/) Just a blogging platform. -* [handlebars_assets](http://github.com/leshill/handlebars_assets): A Rails Asset Pipeline gem - from Les Hill (@leshill). -* [handlebars-helpers](https://github.com/assemble/handlebars-helpers) is an extensive library - with 100+ handlebars helpers. -* [hbs](http://github.com/donpark/hbs): An Express.js view engine adapter for Handlebars.js, - from Don Park. -* [jblotus](http://github.com/jblotus) created [http://tryhandlebarsjs.com](http://tryhandlebarsjs.com) - for anyone who would like to try out Handlebars.js in their browser. -* [jQuery plugin](http://71104.github.io/jquery-handlebars/): allows you to use - Handlebars.js with [jQuery](http://jquery.com/). -* [Lumbar](http://walmartlabs.github.io/lumbar) provides easy module-based template management for - handlebars projects. -* [sammy.js](http://github.com/quirkey/sammy) by Aaron Quint, a.k.a. quirkey, - supports Handlebars.js as one of its template plugins. -* [SproutCore](http://www.sproutcore.com) uses Handlebars.js as its main - templating engine, extending it with automatic data binding support. -* [YUI](http://yuilibrary.com/yui/docs/handlebars/) implements a port of handlebars -* [Swag](https://github.com/elving/swag) by [@elving](https://github.com/elving) is a growing collection of helpers for handlebars.js. Give your handlebars.js templates some swag son! -* [DOMBars](https://github.com/blakeembrey/dombars) is a DOM-based templating engine built on the Handlebars parser and runtime - -External Resources ------------------- - -* [Gist about Synchronous and asynchronous loading of external handlebars templates](https://gist.github.com/2287070) - -Have a project using Handlebars? Send us a [pull request][pull-request]! - -Helping Out ------------ - -To build Handlebars.js you'll need a few things installed. - -* Node.js -* [Grunt](http://gruntjs.com/getting-started) - -Project dependencies may be installed via `npm install`. - -To build Handlebars.js from scratch, you'll want to run `grunt` -in the root of the project. That will build Handlebars and output the -results to the dist/ folder. To re-run tests, run `grunt test` or `npm test`. -You can also run our set of benchmarks with `grunt bench`. - -The `grunt dev` implements watching for tests and allows for in browser testing at `http://localhost:9999/spec/`. - -If you notice any problems, please report them to the GitHub issue tracker at -[http://github.com/wycats/handlebars.js/issues](http://github.com/wycats/handlebars.js/issues). -Feel free to contact commondream or wycats through GitHub with any other -questions or feature requests. To submit changes fork the project and -send a pull request. - -### Ember testing - -The current ember distribution should be tested as part of the handlebars release process. This requires building the `handlebars-source` gem locally and then executing the ember test script. - -```sh -grunt build release -export HANDLEBARS_PATH=`pwd` - -cd $emberRepoDir -bundle exec rake clean -bundle exec rake test -``` - -### Releasing - -Handlebars utilizes the [release yeoman generator][generator-release] to perform most release tasks. - -A full release may be completed with the following: - -``` -yo release:notes patch -yo release:release patch -npm publish -yo release:publish cdnjs handlebars.js dist/cdnjs/ -yo release:publish components handlebars.js dist/components/ - -cd dist/components/ -gem build handlebars-source.gemspec -gem push handlebars-source-*.gem -``` - -After this point the handlebars site needs to be updated to point to the new version numbers. - -License -------- -Handlebars.js is released under the MIT license. - -[bower-repo]: https://github.com/components/handlebars.js -[builds-page]: http://builds.handlebarsjs.com.s3.amazonaws.com/bucket-listing.html?sort=lastmod&sortdir=desc -[generator-release]: https://github.com/walmartlabs/generator-release -[pull-request]: https://github.com/wycats/handlebars.js/pull/new/master diff --git a/node_modules/express3-handlebars/node_modules/handlebars/bin/handlebars b/node_modules/express3-handlebars/node_modules/handlebars/bin/handlebars deleted file mode 100644 index 247ddd540..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/bin/handlebars +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env node - -var optimist = require('optimist') - .usage('Precompile handlebar templates.\nUsage: $0 template...', { - 'f': { - 'type': 'string', - 'description': 'Output File', - 'alias': 'output' - }, - 'a': { - 'type': 'boolean', - 'description': 'Exports amd style (require.js)', - 'alias': 'amd' - }, - 'c': { - 'type': 'string', - 'description': 'Exports CommonJS style, path to Handlebars module', - 'alias': 'commonjs', - 'default': null - }, - 'h': { - 'type': 'string', - 'description': 'Path to handlebar.js (only valid for amd-style)', - 'alias': 'handlebarPath', - 'default': '' - }, - 'k': { - 'type': 'string', - 'description': 'Known helpers', - 'alias': 'known' - }, - 'o': { - 'type': 'boolean', - 'description': 'Known helpers only', - 'alias': 'knownOnly' - }, - 'm': { - 'type': 'boolean', - 'description': 'Minimize output', - 'alias': 'min' - }, - 'n': { - 'type': 'string', - 'description': 'Template namespace', - 'alias': 'namespace', - 'default': 'Handlebars.templates' - }, - 's': { - 'type': 'boolean', - 'description': 'Output template function only.', - 'alias': 'simple' - }, - 'r': { - 'type': 'string', - 'description': 'Template root. Base value that will be stripped from template names.', - 'alias': 'root' - }, - 'p' : { - 'type': 'boolean', - 'description': 'Compiling a partial template', - 'alias': 'partial' - }, - 'd' : { - 'type': 'boolean', - 'description': 'Include data when compiling', - 'alias': 'data' - }, - 'e': { - 'type': 'string', - 'description': 'Template extension.', - 'alias': 'extension', - 'default': 'handlebars' - }, - 'b': { - 'type': 'boolean', - 'description': 'Removes the BOM (Byte Order Mark) from the beginning of the templates.', - 'alias': 'bom' - } - }) - - .check(function(argv) { - var template = [0]; - if (!argv._.length) { - throw 'Must define at least one template or directory.'; - } - - argv._.forEach(function(template) { - try { - fs.statSync(template); - } catch (err) { - throw 'Unable to open template file "' + template + '"'; - } - }); - }) - .check(function(argv) { - if (argv.simple && argv.min) { - throw 'Unable to minimze simple output'; - } - if (argv.simple && (argv._.length !== 1 || fs.statSync(argv._[0]).isDirectory())) { - throw 'Unable to output multiple templates in simple mode'; - } - }); - -var fs = require('fs'), - handlebars = require('../lib'), - basename = require('path').basename, - uglify = require('uglify-js'); - -var argv = optimist.argv, - template = argv._[0]; - -// Convert the known list into a hash -var known = {}; -if (argv.known && !Array.isArray(argv.known)) { - argv.known = [argv.known]; -} -if (argv.known) { - for (var i = 0, len = argv.known.length; i < len; i++) { - known[argv.known[i]] = true; - } -} - -// Build file extension pattern -var extension = argv.extension.replace(/[\\^$*+?.():=!|{}\-\[\]]/g, function(arg) { return '\\' + arg; }); -extension = new RegExp('\\.' + extension + '$'); - -var output = []; -if (!argv.simple) { - if (argv.amd) { - output.push('define([\'' + argv.handlebarPath + 'handlebars.runtime\'], function(Handlebars) {\n Handlebars = Handlebars["default"];'); - } else if (argv.commonjs) { - output.push('var Handlebars = require("' + argv.commonjs + '");'); - } else { - output.push('(function() {\n'); - } - output.push(' var template = Handlebars.template, templates = '); - output.push(argv.namespace); - output.push(' = '); - output.push(argv.namespace); - output.push(' || {};\n'); -} -function processTemplate(template, root) { - var path = template, - stat = fs.statSync(path); - if (stat.isDirectory()) { - fs.readdirSync(template).map(function(file) { - var path = template + '/' + file; - - if (extension.test(path) || fs.statSync(path).isDirectory()) { - processTemplate(path, root || template); - } - }); - } else if (extension.test(path)) { - var data = fs.readFileSync(path, 'utf8'); - - if (argv.bom && data.indexOf('\uFEFF') === 0) { - data = data.substring(1); - } - - var options = { - knownHelpers: known, - knownHelpersOnly: argv.o - }; - - if (argv.data) { - options.data = true; - } - - // Clean the template name - if (!root) { - template = basename(template); - } else if (template.indexOf(root) === 0) { - template = template.substring(root.length+1); - } - template = template.replace(extension, ''); - - if (argv.simple) { - output.push(handlebars.precompile(data, options) + '\n'); - } else if (argv.partial) { - if(argv.amd && (argv._.length == 1 && !fs.statSync(argv._[0]).isDirectory())) { - output.push('return '); - } - output.push('Handlebars.partials[\'' + template + '\'] = template(' + handlebars.precompile(data, options) + ');\n'); - } else { - if(argv.amd && (argv._.length == 1 && !fs.statSync(argv._[0]).isDirectory())) { - output.push('return '); - } - output.push('templates[\'' + template + '\'] = template(' + handlebars.precompile(data, options) + ');\n'); - } - } -} - -argv._.forEach(function(template) { - processTemplate(template, argv.root); -}); - -// Output the content -if (!argv.simple) { - if (argv.amd) { - if(argv._.length > 1 || (argv._.length == 1 && fs.statSync(argv._[0]).isDirectory())) { - if(argv.partial){ - output.push('return Handlebars.partials;\n'); - } else { - output.push('return templates;\n'); - } - } - output.push('});'); - } else if (!argv.commonjs) { - output.push('})();'); - } -} -output = output.join(''); - -if (argv.min) { - output = uglify.minify(output, {fromString: true}).code; -} - -if (argv.output) { - fs.writeFileSync(argv.output, output, 'utf8'); -} else { - console.log(output); -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars.js deleted file mode 100644 index 315fc84b6..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars.js +++ /dev/null @@ -1,41 +0,0 @@ -define( - ["./handlebars.runtime","./handlebars/compiler/ast","./handlebars/compiler/base","./handlebars/compiler/compiler","./handlebars/compiler/javascript-compiler","exports"], - function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { - "use strict"; - /*globals Handlebars: true */ - var Handlebars = __dependency1__["default"]; - - // Compiler imports - var AST = __dependency2__["default"]; - var Parser = __dependency3__.parser; - var parse = __dependency3__.parse; - var Compiler = __dependency4__.Compiler; - var compile = __dependency4__.compile; - var precompile = __dependency4__.precompile; - var JavaScriptCompiler = __dependency5__["default"]; - - var _create = Handlebars.create; - var create = function() { - var hb = _create(); - - hb.compile = function(input, options) { - return compile(input, options, hb); - }; - hb.precompile = function (input, options) { - return precompile(input, options, hb); - }; - - hb.AST = AST; - hb.Compiler = Compiler; - hb.JavaScriptCompiler = JavaScriptCompiler; - hb.Parser = Parser; - hb.parse = parse; - - return hb; - }; - - Handlebars = create(); - Handlebars.create = create; - - __exports__["default"] = Handlebars; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars.runtime.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars.runtime.js deleted file mode 100644 index 7b525b2e2..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars.runtime.js +++ /dev/null @@ -1,36 +0,0 @@ -define( - ["./handlebars/base","./handlebars/safe-string","./handlebars/exception","./handlebars/utils","./handlebars/runtime","exports"], - function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { - "use strict"; - /*globals Handlebars: true */ - var base = __dependency1__; - - // Each of these augment the Handlebars object. No need to setup here. - // (This is done to easily share code between commonjs and browse envs) - var SafeString = __dependency2__["default"]; - var Exception = __dependency3__["default"]; - var Utils = __dependency4__; - var runtime = __dependency5__; - - // For compatibility and usage outside of module systems, make the Handlebars object a namespace - var create = function() { - var hb = new base.HandlebarsEnvironment(); - - Utils.extend(hb, base); - hb.SafeString = SafeString; - hb.Exception = Exception; - hb.Utils = Utils; - - hb.VM = runtime; - hb.template = function(spec) { - return runtime.template(spec, hb); - }; - - return hb; - }; - - var Handlebars = create(); - Handlebars.create = create; - - __exports__["default"] = Handlebars; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/base.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/base.js deleted file mode 100644 index bb664d23f..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/base.js +++ /dev/null @@ -1,184 +0,0 @@ -define( - ["./utils","./exception","exports"], - function(__dependency1__, __dependency2__, __exports__) { - "use strict"; - var Utils = __dependency1__; - var Exception = __dependency2__["default"]; - - var VERSION = "1.3.0"; - __exports__.VERSION = VERSION;var COMPILER_REVISION = 4; - __exports__.COMPILER_REVISION = COMPILER_REVISION; - var REVISION_CHANGES = { - 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '== 1.0.0-rc.3', - 3: '== 1.0.0-rc.4', - 4: '>= 1.0.0' - }; - __exports__.REVISION_CHANGES = REVISION_CHANGES; - var isArray = Utils.isArray, - isFunction = Utils.isFunction, - toString = Utils.toString, - objectType = '[object Object]'; - - function HandlebarsEnvironment(helpers, partials) { - this.helpers = helpers || {}; - this.partials = partials || {}; - - registerDefaultHelpers(this); - } - - __exports__.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = { - constructor: HandlebarsEnvironment, - - logger: logger, - log: log, - - registerHelper: function(name, fn, inverse) { - if (toString.call(name) === objectType) { - if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); } - Utils.extend(this.helpers, name); - } else { - if (inverse) { fn.not = inverse; } - this.helpers[name] = fn; - } - }, - - registerPartial: function(name, str) { - if (toString.call(name) === objectType) { - Utils.extend(this.partials, name); - } else { - this.partials[name] = str; - } - } - }; - - function registerDefaultHelpers(instance) { - instance.registerHelper('helperMissing', function(arg) { - if(arguments.length === 2) { - return undefined; - } else { - throw new Exception("Missing helper: '" + arg + "'"); - } - }); - - instance.registerHelper('blockHelperMissing', function(context, options) { - var inverse = options.inverse || function() {}, fn = options.fn; - - if (isFunction(context)) { context = context.call(this); } - - if(context === true) { - return fn(this); - } else if(context === false || context == null) { - return inverse(this); - } else if (isArray(context)) { - if(context.length > 0) { - return instance.helpers.each(context, options); - } else { - return inverse(this); - } - } else { - return fn(context); - } - }); - - instance.registerHelper('each', function(context, options) { - var fn = options.fn, inverse = options.inverse; - var i = 0, ret = "", data; - - if (isFunction(context)) { context = context.call(this); } - - if (options.data) { - data = createFrame(options.data); - } - - if(context && typeof context === 'object') { - if (isArray(context)) { - for(var j = context.length; i 0) { - throw new Exception("Invalid path: " + original, this); - } else if (part === "..") { - depth++; - } else { - this.isScoped = true; - } - } else { - dig.push(part); - } - } - - this.original = original; - this.parts = dig; - this.string = dig.join('.'); - this.depth = depth; - - // an ID is simple if it only has one part, and that part is not - // `..` or `this`. - this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; - - this.stringModeValue = this.string; - }, - - PartialNameNode: function(name, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "PARTIAL_NAME"; - this.name = name.original; - }, - - DataNode: function(id, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "DATA"; - this.id = id; - }, - - StringNode: function(string, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "STRING"; - this.original = - this.string = - this.stringModeValue = string; - }, - - IntegerNode: function(integer, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "INTEGER"; - this.original = - this.integer = integer; - this.stringModeValue = Number(integer); - }, - - BooleanNode: function(bool, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "BOOLEAN"; - this.bool = bool; - this.stringModeValue = bool === "true"; - }, - - CommentNode: function(comment, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "comment"; - this.comment = comment; - } - }; - - // Must be exported as an object rather than the root of the module as the jison lexer - // most modify the object to operate properly. - __exports__["default"] = AST; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/base.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/base.js deleted file mode 100644 index 643078205..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/base.js +++ /dev/null @@ -1,19 +0,0 @@ -define( - ["./parser","./ast","exports"], - function(__dependency1__, __dependency2__, __exports__) { - "use strict"; - var parser = __dependency1__["default"]; - var AST = __dependency2__["default"]; - - __exports__.parser = parser; - - function parse(input) { - // Just return if an already-compile AST was passed in. - if(input.constructor === AST.ProgramNode) { return input; } - - parser.yy = AST; - return parser.parse(input); - } - - __exports__.parse = parse; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/compiler.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/compiler.js deleted file mode 100644 index a8c359082..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/compiler.js +++ /dev/null @@ -1,473 +0,0 @@ -define( - ["../exception","exports"], - function(__dependency1__, __exports__) { - "use strict"; - var Exception = __dependency1__["default"]; - - function Compiler() {} - - __exports__.Compiler = Compiler;// the foundHelper register will disambiguate helper lookup from finding a - // function in a context. This is necessary for mustache compatibility, which - // requires that context functions in blocks are evaluated by blockHelperMissing, - // and then proceed as if the resulting value was provided to blockHelperMissing. - - Compiler.prototype = { - compiler: Compiler, - - disassemble: function() { - var opcodes = this.opcodes, opcode, out = [], params, param; - - for (var i=0, l=opcodes.length; i 0) { - this.source[1] = this.source[1] + ", " + locals.join(", "); - } - - // Generate minimizer alias mappings - if (!this.isChild) { - for (var alias in this.context.aliases) { - if (this.context.aliases.hasOwnProperty(alias)) { - this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; - } - } - } - - if (this.source[1]) { - this.source[1] = "var " + this.source[1].substring(2) + ";"; - } - - // Merge children - if (!this.isChild) { - this.source[1] += '\n' + this.context.programs.join('\n') + '\n'; - } - - if (!this.environment.isSimple) { - this.pushSource("return buffer;"); - } - - var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"]; - - for(var i=0, l=this.environment.depths.list.length; i this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } - return this.topStackName(); - }, - topStackName: function() { - return "stack" + this.stackSlot; - }, - flushInline: function() { - var inlineStack = this.inlineStack; - if (inlineStack.length) { - this.inlineStack = []; - for (var i = 0, len = inlineStack.length; i < len; i++) { - var entry = inlineStack[i]; - if (entry instanceof Literal) { - this.compileStack.push(entry); - } else { - this.pushStack(entry); - } - } - } - }, - isInline: function() { - return this.inlineStack.length; - }, - - popStack: function(wrapped) { - var inline = this.isInline(), - item = (inline ? this.inlineStack : this.compileStack).pop(); - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - if (!inline) { - if (!this.stackSlot) { - throw new Exception('Invalid stack pop'); - } - this.stackSlot--; - } - return item; - } - }, - - topStack: function(wrapped) { - var stack = (this.isInline() ? this.inlineStack : this.compileStack), - item = stack[stack.length - 1]; - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - return item; - } - }, - - quotedString: function(str) { - return '"' + str - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 - .replace(/\u2029/g, '\\u2029') + '"'; - }, - - setupHelper: function(paramSize, name, missingParams) { - var params = [], - paramsInit = this.setupParams(paramSize, params, missingParams); - var foundHelper = this.nameLookup('helpers', name, 'helper'); - - return { - params: params, - paramsInit: paramsInit, - name: foundHelper, - callParams: ["depth0"].concat(params).join(", "), - helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ") - }; - }, - - setupOptions: function(paramSize, params) { - var options = [], contexts = [], types = [], param, inverse, program; - - options.push("hash:" + this.popStack()); - - if (this.options.stringParams) { - options.push("hashTypes:" + this.popStack()); - options.push("hashContexts:" + this.popStack()); - } - - inverse = this.popStack(); - program = this.popStack(); - - // Avoid setting fn and inverse if neither are set. This allows - // helpers to do a check for `if (options.fn)` - if (program || inverse) { - if (!program) { - this.context.aliases.self = "this"; - program = "self.noop"; - } - - if (!inverse) { - this.context.aliases.self = "this"; - inverse = "self.noop"; - } - - options.push("inverse:" + inverse); - options.push("fn:" + program); - } - - for(var i=0; i 2) { - expected.push("'" + this.terminals_[p] + "'"); - } - if (this.lexer.showPosition) { - errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; - } else { - errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); - } - this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); - } - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) - recovering--; - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; - if (ranges) { - yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; - } - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - if (typeof r !== "undefined") { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } - } - return true; - } - }; - - - function stripFlags(open, close) { - return { - left: open.charAt(2) === '~', - right: close.charAt(0) === '~' || close.charAt(1) === '~' - }; - } - - /* Jison generated lexer */ - var lexer = (function(){ - var lexer = ({EOF:1, - parseError:function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, - setInput:function (input) { - this._input = input; - this._more = this._less = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; - if (this.options.ranges) this.yylloc.range = [0,0]; - this.offset = 0; - return this; - }, - input:function () { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) this.yylloc.range[1]++; - - this._input = this._input.slice(1); - return ch; - }, - unput:function (ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); - - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length-len-1); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length-1); - this.matched = this.matched.substr(0, this.matched.length-1); - - if (lines.length-1) this.yylineno -= lines.length-1; - var r = this.yylloc.range; - - this.yylloc = {first_line: this.yylloc.first_line, - last_line: this.yylineno+1, - first_column: this.yylloc.first_column, - last_column: lines ? - (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: - this.yylloc.first_column - len - }; - - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - return this; - }, - more:function () { - this._more = true; - return this; - }, - less:function (n) { - this.unput(this.match.slice(n)); - }, - pastInput:function () { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); - }, - upcomingInput:function () { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20-next.length); - } - return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); - }, - showPosition:function () { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c+"^"; - }, - next:function () { - if (this.done) { - return this.EOF; - } - if (!this._input) this.done = true; - - var token, - match, - tempMatch, - index, - col, - lines; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i=0;i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (!this.options.flex) break; - } - } - if (match) { - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) this.yylineno += lines.length; - this.yylloc = {first_line: this.yylloc.last_line, - last_line: this.yylineno+1, - first_column: this.yylloc.last_column, - last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); - if (this.done && this._input) this.done = false; - if (token) return token; - else return; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), - {text: "", token: null, line: this.yylineno}); - } - }, - lex:function lex() { - var r = this.next(); - if (typeof r !== 'undefined') { - return r; - } else { - return this.lex(); - } - }, - begin:function begin(condition) { - this.conditionStack.push(condition); - }, - popState:function popState() { - return this.conditionStack.pop(); - }, - _currentRules:function _currentRules() { - return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; - }, - topState:function () { - return this.conditionStack[this.conditionStack.length-2]; - }, - pushState:function begin(condition) { - this.begin(condition); - }}); - lexer.options = {}; - lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { - - - function strip(start, end) { - return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng-end); - } - - - var YYSTATE=YY_START - switch($avoiding_name_collisions) { - case 0: - if(yy_.yytext.slice(-2) === "\\\\") { - strip(0,1); - this.begin("mu"); - } else if(yy_.yytext.slice(-1) === "\\") { - strip(0,1); - this.begin("emu"); - } else { - this.begin("mu"); - } - if(yy_.yytext) return 14; - - break; - case 1:return 14; - break; - case 2: - this.popState(); - return 14; - - break; - case 3:strip(0,4); this.popState(); return 15; - break; - case 4:return 35; - break; - case 5:return 36; - break; - case 6:return 25; - break; - case 7:return 16; - break; - case 8:return 20; - break; - case 9:return 19; - break; - case 10:return 19; - break; - case 11:return 23; - break; - case 12:return 22; - break; - case 13:this.popState(); this.begin('com'); - break; - case 14:strip(3,5); this.popState(); return 15; - break; - case 15:return 22; - break; - case 16:return 41; - break; - case 17:return 40; - break; - case 18:return 40; - break; - case 19:return 44; - break; - case 20:// ignore whitespace - break; - case 21:this.popState(); return 24; - break; - case 22:this.popState(); return 18; - break; - case 23:yy_.yytext = strip(1,2).replace(/\\"/g,'"'); return 32; - break; - case 24:yy_.yytext = strip(1,2).replace(/\\'/g,"'"); return 32; - break; - case 25:return 42; - break; - case 26:return 34; - break; - case 27:return 34; - break; - case 28:return 33; - break; - case 29:return 40; - break; - case 30:yy_.yytext = strip(1,2); return 40; - break; - case 31:return 'INVALID'; - break; - case 32:return 5; - break; - } - }; - lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; - lexer.conditions = {"mu":{"rules":[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"com":{"rules":[3],"inclusive":false},"INITIAL":{"rules":[0,1,32],"inclusive":true}}; - return lexer;})() - parser.lexer = lexer; - function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; - return new Parser; - })();__exports__["default"] = handlebars; - /* jshint ignore:end */ - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/printer.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/printer.js deleted file mode 100644 index 11dc4abb1..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/printer.js +++ /dev/null @@ -1,142 +0,0 @@ -define( - ["./visitor","exports"], - function(__dependency1__, __exports__) { - "use strict"; - var Visitor = __dependency1__["default"]; - - function print(ast) { - return new PrintVisitor().accept(ast); - } - - __exports__.print = print;function PrintVisitor() { - this.padding = 0; - } - - __exports__.PrintVisitor = PrintVisitor;PrintVisitor.prototype = new Visitor(); - - PrintVisitor.prototype.pad = function(string, newline) { - var out = ""; - - for(var i=0,l=this.padding; i " + content + " }}"); - }; - - PrintVisitor.prototype.hash = function(hash) { - var pairs = hash.pairs; - var joinedPairs = [], left, right; - - for(var i=0, l=pairs.length; i 1) { - return "PATH:" + path; - } else { - return "ID:" + path; - } - }; - - PrintVisitor.prototype.PARTIAL_NAME = function(partialName) { - return "PARTIAL:" + partialName.name; - }; - - PrintVisitor.prototype.DATA = function(data) { - return "@" + this.accept(data.id); - }; - - PrintVisitor.prototype.content = function(content) { - return this.pad("CONTENT[ '" + content.string + "' ]"); - }; - - PrintVisitor.prototype.comment = function(comment) { - return this.pad("{{! '" + comment.comment + "' }}"); - }; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/visitor.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/visitor.js deleted file mode 100644 index 325ba0e9b..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/compiler/visitor.js +++ /dev/null @@ -1,16 +0,0 @@ -define( - ["exports"], - function(__exports__) { - "use strict"; - function Visitor() {} - - Visitor.prototype = { - constructor: Visitor, - - accept: function(object) { - return this[object.type](object); - } - }; - - __exports__["default"] = Visitor; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/exception.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/exception.js deleted file mode 100644 index df0b04236..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/exception.js +++ /dev/null @@ -1,32 +0,0 @@ -define( - ["exports"], - function(__exports__) { - "use strict"; - - var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; - - function Exception(message, node) { - var line; - if (node && node.firstLine) { - line = node.firstLine; - - message += ' - ' + line + ':' + node.firstColumn; - } - - var tmp = Error.prototype.constructor.call(this, message); - - // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. - for (var idx = 0; idx < errorProps.length; idx++) { - this[errorProps[idx]] = tmp[errorProps[idx]]; - } - - if (line) { - this.lineNumber = line; - this.column = node.firstColumn; - } - } - - Exception.prototype = new Error(); - - __exports__["default"] = Exception; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/runtime.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/runtime.js deleted file mode 100644 index f70f339c0..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/runtime.js +++ /dev/null @@ -1,141 +0,0 @@ -define( - ["./utils","./exception","./base","exports"], - function(__dependency1__, __dependency2__, __dependency3__, __exports__) { - "use strict"; - var Utils = __dependency1__; - var Exception = __dependency2__["default"]; - var COMPILER_REVISION = __dependency3__.COMPILER_REVISION; - var REVISION_CHANGES = __dependency3__.REVISION_CHANGES; - - function checkRevision(compilerInfo) { - var compilerRevision = compilerInfo && compilerInfo[0] || 1, - currentRevision = COMPILER_REVISION; - - if (compilerRevision !== currentRevision) { - if (compilerRevision < currentRevision) { - var runtimeVersions = REVISION_CHANGES[currentRevision], - compilerVersions = REVISION_CHANGES[compilerRevision]; - throw new Exception("Template was precompiled with an older version of Handlebars than the current runtime. "+ - "Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+")."); - } else { - // Use the embedded version info since the runtime doesn't know about this revision yet - throw new Exception("Template was precompiled with a newer version of Handlebars than the current runtime. "+ - "Please update your runtime to a newer version ("+compilerInfo[1]+")."); - } - } - } - - __exports__.checkRevision = checkRevision;// TODO: Remove this line and break up compilePartial - - function template(templateSpec, env) { - if (!env) { - throw new Exception("No environment passed to template"); - } - - // Note: Using env.VM references rather than local var references throughout this section to allow - // for external users to override these as psuedo-supported APIs. - var invokePartialWrapper = function(partial, name, context, helpers, partials, data) { - var result = env.VM.invokePartial.apply(this, arguments); - if (result != null) { return result; } - - if (env.compile) { - var options = { helpers: helpers, partials: partials, data: data }; - partials[name] = env.compile(partial, { data: data !== undefined }, env); - return partials[name](context, options); - } else { - throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); - } - }; - - // Just add water - var container = { - escapeExpression: Utils.escapeExpression, - invokePartial: invokePartialWrapper, - programs: [], - program: function(i, fn, data) { - var programWrapper = this.programs[i]; - if(data) { - programWrapper = program(i, fn, data); - } else if (!programWrapper) { - programWrapper = this.programs[i] = program(i, fn); - } - return programWrapper; - }, - merge: function(param, common) { - var ret = param || common; - - if (param && common && (param !== common)) { - ret = {}; - Utils.extend(ret, common); - Utils.extend(ret, param); - } - return ret; - }, - programWithDepth: env.VM.programWithDepth, - noop: env.VM.noop, - compilerInfo: null - }; - - return function(context, options) { - options = options || {}; - var namespace = options.partial ? options : env, - helpers, - partials; - - if (!options.partial) { - helpers = options.helpers; - partials = options.partials; - } - var result = templateSpec.call( - container, - namespace, context, - helpers, - partials, - options.data); - - if (!options.partial) { - env.VM.checkRevision(container.compilerInfo); - } - - return result; - }; - } - - __exports__.template = template;function programWithDepth(i, fn, data /*, $depth */) { - var args = Array.prototype.slice.call(arguments, 3); - - var prog = function(context, options) { - options = options || {}; - - return fn.apply(this, [context, options.data || data].concat(args)); - }; - prog.program = i; - prog.depth = args.length; - return prog; - } - - __exports__.programWithDepth = programWithDepth;function program(i, fn, data) { - var prog = function(context, options) { - options = options || {}; - - return fn(context, options.data || data); - }; - prog.program = i; - prog.depth = 0; - return prog; - } - - __exports__.program = program;function invokePartial(partial, name, context, helpers, partials, data) { - var options = { partial: true, helpers: helpers, partials: partials, data: data }; - - if(partial === undefined) { - throw new Exception("The partial " + name + " could not be found"); - } else if(partial instanceof Function) { - return partial(context, options); - } - } - - __exports__.invokePartial = invokePartial;function noop() { return ""; } - - __exports__.noop = noop; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/safe-string.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/safe-string.js deleted file mode 100644 index 5a2ad319c..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/safe-string.js +++ /dev/null @@ -1,15 +0,0 @@ -define( - ["exports"], - function(__exports__) { - "use strict"; - // Build out our basic SafeString type - function SafeString(string) { - this.string = string; - } - - SafeString.prototype.toString = function() { - return "" + this.string; - }; - - __exports__["default"] = SafeString; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/utils.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/utils.js deleted file mode 100644 index 37ec830e7..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/amd/handlebars/utils.js +++ /dev/null @@ -1,80 +0,0 @@ -define( - ["./safe-string","exports"], - function(__dependency1__, __exports__) { - "use strict"; - /*jshint -W004 */ - var SafeString = __dependency1__["default"]; - - var escape = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "`": "`" - }; - - var badChars = /[&<>"'`]/g; - var possible = /[&<>"'`]/; - - function escapeChar(chr) { - return escape[chr] || "&"; - } - - function extend(obj, value) { - for(var key in value) { - if(Object.prototype.hasOwnProperty.call(value, key)) { - obj[key] = value[key]; - } - } - } - - __exports__.extend = extend;var toString = Object.prototype.toString; - __exports__.toString = toString; - // Sourced from lodash - // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt - var isFunction = function(value) { - return typeof value === 'function'; - }; - // fallback for older versions of Chrome and Safari - if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; - } - var isFunction; - __exports__.isFunction = isFunction; - var isArray = Array.isArray || function(value) { - return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false; - }; - __exports__.isArray = isArray; - - function escapeExpression(string) { - // don't escape SafeStrings, since they're already safe - if (string instanceof SafeString) { - return string.toString(); - } else if (!string && string !== 0) { - return ""; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = "" + string; - - if(!possible.test(string)) { return string; } - return string.replace(badChars, escapeChar); - } - - __exports__.escapeExpression = escapeExpression;function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } - } - - __exports__.isEmpty = isEmpty; - }); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars.js deleted file mode 100644 index c8c3195bf..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -/*globals Handlebars: true */ -var Handlebars = require("./handlebars.runtime")["default"]; - -// Compiler imports -var AST = require("./handlebars/compiler/ast")["default"]; -var Parser = require("./handlebars/compiler/base").parser; -var parse = require("./handlebars/compiler/base").parse; -var Compiler = require("./handlebars/compiler/compiler").Compiler; -var compile = require("./handlebars/compiler/compiler").compile; -var precompile = require("./handlebars/compiler/compiler").precompile; -var JavaScriptCompiler = require("./handlebars/compiler/javascript-compiler")["default"]; - -var _create = Handlebars.create; -var create = function() { - var hb = _create(); - - hb.compile = function(input, options) { - return compile(input, options, hb); - }; - hb.precompile = function (input, options) { - return precompile(input, options, hb); - }; - - hb.AST = AST; - hb.Compiler = Compiler; - hb.JavaScriptCompiler = JavaScriptCompiler; - hb.Parser = Parser; - hb.parse = parse; - - return hb; -}; - -Handlebars = create(); -Handlebars.create = create; - -exports["default"] = Handlebars; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars.runtime.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars.runtime.js deleted file mode 100644 index bd1820d6f..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars.runtime.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -/*globals Handlebars: true */ -var base = require("./handlebars/base"); - -// Each of these augment the Handlebars object. No need to setup here. -// (This is done to easily share code between commonjs and browse envs) -var SafeString = require("./handlebars/safe-string")["default"]; -var Exception = require("./handlebars/exception")["default"]; -var Utils = require("./handlebars/utils"); -var runtime = require("./handlebars/runtime"); - -// For compatibility and usage outside of module systems, make the Handlebars object a namespace -var create = function() { - var hb = new base.HandlebarsEnvironment(); - - Utils.extend(hb, base); - hb.SafeString = SafeString; - hb.Exception = Exception; - hb.Utils = Utils; - - hb.VM = runtime; - hb.template = function(spec) { - return runtime.template(spec, hb); - }; - - return hb; -}; - -var Handlebars = create(); -Handlebars.create = create; - -exports["default"] = Handlebars; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/base.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/base.js deleted file mode 100644 index d57bf0648..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/base.js +++ /dev/null @@ -1,180 +0,0 @@ -"use strict"; -var Utils = require("./utils"); -var Exception = require("./exception")["default"]; - -var VERSION = "1.3.0"; -exports.VERSION = VERSION;var COMPILER_REVISION = 4; -exports.COMPILER_REVISION = COMPILER_REVISION; -var REVISION_CHANGES = { - 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '== 1.0.0-rc.3', - 3: '== 1.0.0-rc.4', - 4: '>= 1.0.0' -}; -exports.REVISION_CHANGES = REVISION_CHANGES; -var isArray = Utils.isArray, - isFunction = Utils.isFunction, - toString = Utils.toString, - objectType = '[object Object]'; - -function HandlebarsEnvironment(helpers, partials) { - this.helpers = helpers || {}; - this.partials = partials || {}; - - registerDefaultHelpers(this); -} - -exports.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = { - constructor: HandlebarsEnvironment, - - logger: logger, - log: log, - - registerHelper: function(name, fn, inverse) { - if (toString.call(name) === objectType) { - if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); } - Utils.extend(this.helpers, name); - } else { - if (inverse) { fn.not = inverse; } - this.helpers[name] = fn; - } - }, - - registerPartial: function(name, str) { - if (toString.call(name) === objectType) { - Utils.extend(this.partials, name); - } else { - this.partials[name] = str; - } - } -}; - -function registerDefaultHelpers(instance) { - instance.registerHelper('helperMissing', function(arg) { - if(arguments.length === 2) { - return undefined; - } else { - throw new Exception("Missing helper: '" + arg + "'"); - } - }); - - instance.registerHelper('blockHelperMissing', function(context, options) { - var inverse = options.inverse || function() {}, fn = options.fn; - - if (isFunction(context)) { context = context.call(this); } - - if(context === true) { - return fn(this); - } else if(context === false || context == null) { - return inverse(this); - } else if (isArray(context)) { - if(context.length > 0) { - return instance.helpers.each(context, options); - } else { - return inverse(this); - } - } else { - return fn(context); - } - }); - - instance.registerHelper('each', function(context, options) { - var fn = options.fn, inverse = options.inverse; - var i = 0, ret = "", data; - - if (isFunction(context)) { context = context.call(this); } - - if (options.data) { - data = createFrame(options.data); - } - - if(context && typeof context === 'object') { - if (isArray(context)) { - for(var j = context.length; i 0) { - throw new Exception("Invalid path: " + original, this); - } else if (part === "..") { - depth++; - } else { - this.isScoped = true; - } - } else { - dig.push(part); - } - } - - this.original = original; - this.parts = dig; - this.string = dig.join('.'); - this.depth = depth; - - // an ID is simple if it only has one part, and that part is not - // `..` or `this`. - this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; - - this.stringModeValue = this.string; - }, - - PartialNameNode: function(name, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "PARTIAL_NAME"; - this.name = name.original; - }, - - DataNode: function(id, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "DATA"; - this.id = id; - }, - - StringNode: function(string, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "STRING"; - this.original = - this.string = - this.stringModeValue = string; - }, - - IntegerNode: function(integer, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "INTEGER"; - this.original = - this.integer = integer; - this.stringModeValue = Number(integer); - }, - - BooleanNode: function(bool, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "BOOLEAN"; - this.bool = bool; - this.stringModeValue = bool === "true"; - }, - - CommentNode: function(comment, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "comment"; - this.comment = comment; - } -}; - -// Must be exported as an object rather than the root of the module as the jison lexer -// most modify the object to operate properly. -exports["default"] = AST; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js deleted file mode 100644 index 4c99b9c51..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/base.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -var parser = require("./parser")["default"]; -var AST = require("./ast")["default"]; - -exports.parser = parser; - -function parse(input) { - // Just return if an already-compile AST was passed in. - if(input.constructor === AST.ProgramNode) { return input; } - - parser.yy = AST; - return parser.parse(input); -} - -exports.parse = parse; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js deleted file mode 100644 index 3357ef3dc..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js +++ /dev/null @@ -1,469 +0,0 @@ -"use strict"; -var Exception = require("../exception")["default"]; - -function Compiler() {} - -exports.Compiler = Compiler;// the foundHelper register will disambiguate helper lookup from finding a -// function in a context. This is necessary for mustache compatibility, which -// requires that context functions in blocks are evaluated by blockHelperMissing, -// and then proceed as if the resulting value was provided to blockHelperMissing. - -Compiler.prototype = { - compiler: Compiler, - - disassemble: function() { - var opcodes = this.opcodes, opcode, out = [], params, param; - - for (var i=0, l=opcodes.length; i 0) { - this.source[1] = this.source[1] + ", " + locals.join(", "); - } - - // Generate minimizer alias mappings - if (!this.isChild) { - for (var alias in this.context.aliases) { - if (this.context.aliases.hasOwnProperty(alias)) { - this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; - } - } - } - - if (this.source[1]) { - this.source[1] = "var " + this.source[1].substring(2) + ";"; - } - - // Merge children - if (!this.isChild) { - this.source[1] += '\n' + this.context.programs.join('\n') + '\n'; - } - - if (!this.environment.isSimple) { - this.pushSource("return buffer;"); - } - - var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"]; - - for(var i=0, l=this.environment.depths.list.length; i this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } - return this.topStackName(); - }, - topStackName: function() { - return "stack" + this.stackSlot; - }, - flushInline: function() { - var inlineStack = this.inlineStack; - if (inlineStack.length) { - this.inlineStack = []; - for (var i = 0, len = inlineStack.length; i < len; i++) { - var entry = inlineStack[i]; - if (entry instanceof Literal) { - this.compileStack.push(entry); - } else { - this.pushStack(entry); - } - } - } - }, - isInline: function() { - return this.inlineStack.length; - }, - - popStack: function(wrapped) { - var inline = this.isInline(), - item = (inline ? this.inlineStack : this.compileStack).pop(); - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - if (!inline) { - if (!this.stackSlot) { - throw new Exception('Invalid stack pop'); - } - this.stackSlot--; - } - return item; - } - }, - - topStack: function(wrapped) { - var stack = (this.isInline() ? this.inlineStack : this.compileStack), - item = stack[stack.length - 1]; - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - return item; - } - }, - - quotedString: function(str) { - return '"' + str - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 - .replace(/\u2029/g, '\\u2029') + '"'; - }, - - setupHelper: function(paramSize, name, missingParams) { - var params = [], - paramsInit = this.setupParams(paramSize, params, missingParams); - var foundHelper = this.nameLookup('helpers', name, 'helper'); - - return { - params: params, - paramsInit: paramsInit, - name: foundHelper, - callParams: ["depth0"].concat(params).join(", "), - helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ") - }; - }, - - setupOptions: function(paramSize, params) { - var options = [], contexts = [], types = [], param, inverse, program; - - options.push("hash:" + this.popStack()); - - if (this.options.stringParams) { - options.push("hashTypes:" + this.popStack()); - options.push("hashContexts:" + this.popStack()); - } - - inverse = this.popStack(); - program = this.popStack(); - - // Avoid setting fn and inverse if neither are set. This allows - // helpers to do a check for `if (options.fn)` - if (program || inverse) { - if (!program) { - this.context.aliases.self = "this"; - program = "self.noop"; - } - - if (!inverse) { - this.context.aliases.self = "this"; - inverse = "self.noop"; - } - - options.push("inverse:" + inverse); - options.push("fn:" + program); - } - - for(var i=0; i 2) { - expected.push("'" + this.terminals_[p] + "'"); - } - if (this.lexer.showPosition) { - errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; - } else { - errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); - } - this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); - } - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) - recovering--; - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; - if (ranges) { - yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; - } - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - if (typeof r !== "undefined") { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } - } - return true; -} -}; - - -function stripFlags(open, close) { - return { - left: open.charAt(2) === '~', - right: close.charAt(0) === '~' || close.charAt(1) === '~' - }; -} - -/* Jison generated lexer */ -var lexer = (function(){ -var lexer = ({EOF:1, -parseError:function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, -setInput:function (input) { - this._input = input; - this._more = this._less = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; - if (this.options.ranges) this.yylloc.range = [0,0]; - this.offset = 0; - return this; - }, -input:function () { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) this.yylloc.range[1]++; - - this._input = this._input.slice(1); - return ch; - }, -unput:function (ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); - - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length-len-1); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length-1); - this.matched = this.matched.substr(0, this.matched.length-1); - - if (lines.length-1) this.yylineno -= lines.length-1; - var r = this.yylloc.range; - - this.yylloc = {first_line: this.yylloc.first_line, - last_line: this.yylineno+1, - first_column: this.yylloc.first_column, - last_column: lines ? - (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: - this.yylloc.first_column - len - }; - - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - return this; - }, -more:function () { - this._more = true; - return this; - }, -less:function (n) { - this.unput(this.match.slice(n)); - }, -pastInput:function () { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); - }, -upcomingInput:function () { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20-next.length); - } - return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); - }, -showPosition:function () { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c+"^"; - }, -next:function () { - if (this.done) { - return this.EOF; - } - if (!this._input) this.done = true; - - var token, - match, - tempMatch, - index, - col, - lines; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i=0;i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (!this.options.flex) break; - } - } - if (match) { - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) this.yylineno += lines.length; - this.yylloc = {first_line: this.yylloc.last_line, - last_line: this.yylineno+1, - first_column: this.yylloc.last_column, - last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); - if (this.done && this._input) this.done = false; - if (token) return token; - else return; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), - {text: "", token: null, line: this.yylineno}); - } - }, -lex:function lex() { - var r = this.next(); - if (typeof r !== 'undefined') { - return r; - } else { - return this.lex(); - } - }, -begin:function begin(condition) { - this.conditionStack.push(condition); - }, -popState:function popState() { - return this.conditionStack.pop(); - }, -_currentRules:function _currentRules() { - return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; - }, -topState:function () { - return this.conditionStack[this.conditionStack.length-2]; - }, -pushState:function begin(condition) { - this.begin(condition); - }}); -lexer.options = {}; -lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { - - -function strip(start, end) { - return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng-end); -} - - -var YYSTATE=YY_START -switch($avoiding_name_collisions) { -case 0: - if(yy_.yytext.slice(-2) === "\\\\") { - strip(0,1); - this.begin("mu"); - } else if(yy_.yytext.slice(-1) === "\\") { - strip(0,1); - this.begin("emu"); - } else { - this.begin("mu"); - } - if(yy_.yytext) return 14; - -break; -case 1:return 14; -break; -case 2: - this.popState(); - return 14; - -break; -case 3:strip(0,4); this.popState(); return 15; -break; -case 4:return 35; -break; -case 5:return 36; -break; -case 6:return 25; -break; -case 7:return 16; -break; -case 8:return 20; -break; -case 9:return 19; -break; -case 10:return 19; -break; -case 11:return 23; -break; -case 12:return 22; -break; -case 13:this.popState(); this.begin('com'); -break; -case 14:strip(3,5); this.popState(); return 15; -break; -case 15:return 22; -break; -case 16:return 41; -break; -case 17:return 40; -break; -case 18:return 40; -break; -case 19:return 44; -break; -case 20:// ignore whitespace -break; -case 21:this.popState(); return 24; -break; -case 22:this.popState(); return 18; -break; -case 23:yy_.yytext = strip(1,2).replace(/\\"/g,'"'); return 32; -break; -case 24:yy_.yytext = strip(1,2).replace(/\\'/g,"'"); return 32; -break; -case 25:return 42; -break; -case 26:return 34; -break; -case 27:return 34; -break; -case 28:return 33; -break; -case 29:return 40; -break; -case 30:yy_.yytext = strip(1,2); return 40; -break; -case 31:return 'INVALID'; -break; -case 32:return 5; -break; -} -}; -lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; -lexer.conditions = {"mu":{"rules":[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"com":{"rules":[3],"inclusive":false},"INITIAL":{"rules":[0,1,32],"inclusive":true}}; -return lexer;})() -parser.lexer = lexer; -function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; -return new Parser; -})();exports["default"] = handlebars; -/* jshint ignore:end */ \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/printer.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/printer.js deleted file mode 100644 index 5d2ca0424..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/printer.js +++ /dev/null @@ -1,138 +0,0 @@ -"use strict"; -var Visitor = require("./visitor")["default"]; - -function print(ast) { - return new PrintVisitor().accept(ast); -} - -exports.print = print;function PrintVisitor() { - this.padding = 0; -} - -exports.PrintVisitor = PrintVisitor;PrintVisitor.prototype = new Visitor(); - -PrintVisitor.prototype.pad = function(string, newline) { - var out = ""; - - for(var i=0,l=this.padding; i " + content + " }}"); -}; - -PrintVisitor.prototype.hash = function(hash) { - var pairs = hash.pairs; - var joinedPairs = [], left, right; - - for(var i=0, l=pairs.length; i 1) { - return "PATH:" + path; - } else { - return "ID:" + path; - } -}; - -PrintVisitor.prototype.PARTIAL_NAME = function(partialName) { - return "PARTIAL:" + partialName.name; -}; - -PrintVisitor.prototype.DATA = function(data) { - return "@" + this.accept(data.id); -}; - -PrintVisitor.prototype.content = function(content) { - return this.pad("CONTENT[ '" + content.string + "' ]"); -}; - -PrintVisitor.prototype.comment = function(comment) { - return this.pad("{{! '" + comment.comment + "' }}"); -}; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js deleted file mode 100644 index cb28dec66..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; -function Visitor() {} - -Visitor.prototype = { - constructor: Visitor, - - accept: function(object) { - return this[object.type](object); - } -}; - -exports["default"] = Visitor; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/exception.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/exception.js deleted file mode 100644 index a9ff3b620..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/exception.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; - -var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; - -function Exception(message, node) { - var line; - if (node && node.firstLine) { - line = node.firstLine; - - message += ' - ' + line + ':' + node.firstColumn; - } - - var tmp = Error.prototype.constructor.call(this, message); - - // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. - for (var idx = 0; idx < errorProps.length; idx++) { - this[errorProps[idx]] = tmp[errorProps[idx]]; - } - - if (line) { - this.lineNumber = line; - this.column = node.firstColumn; - } -} - -Exception.prototype = new Error(); - -exports["default"] = Exception; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/runtime.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/runtime.js deleted file mode 100644 index 85070a640..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/runtime.js +++ /dev/null @@ -1,137 +0,0 @@ -"use strict"; -var Utils = require("./utils"); -var Exception = require("./exception")["default"]; -var COMPILER_REVISION = require("./base").COMPILER_REVISION; -var REVISION_CHANGES = require("./base").REVISION_CHANGES; - -function checkRevision(compilerInfo) { - var compilerRevision = compilerInfo && compilerInfo[0] || 1, - currentRevision = COMPILER_REVISION; - - if (compilerRevision !== currentRevision) { - if (compilerRevision < currentRevision) { - var runtimeVersions = REVISION_CHANGES[currentRevision], - compilerVersions = REVISION_CHANGES[compilerRevision]; - throw new Exception("Template was precompiled with an older version of Handlebars than the current runtime. "+ - "Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+")."); - } else { - // Use the embedded version info since the runtime doesn't know about this revision yet - throw new Exception("Template was precompiled with a newer version of Handlebars than the current runtime. "+ - "Please update your runtime to a newer version ("+compilerInfo[1]+")."); - } - } -} - -exports.checkRevision = checkRevision;// TODO: Remove this line and break up compilePartial - -function template(templateSpec, env) { - if (!env) { - throw new Exception("No environment passed to template"); - } - - // Note: Using env.VM references rather than local var references throughout this section to allow - // for external users to override these as psuedo-supported APIs. - var invokePartialWrapper = function(partial, name, context, helpers, partials, data) { - var result = env.VM.invokePartial.apply(this, arguments); - if (result != null) { return result; } - - if (env.compile) { - var options = { helpers: helpers, partials: partials, data: data }; - partials[name] = env.compile(partial, { data: data !== undefined }, env); - return partials[name](context, options); - } else { - throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); - } - }; - - // Just add water - var container = { - escapeExpression: Utils.escapeExpression, - invokePartial: invokePartialWrapper, - programs: [], - program: function(i, fn, data) { - var programWrapper = this.programs[i]; - if(data) { - programWrapper = program(i, fn, data); - } else if (!programWrapper) { - programWrapper = this.programs[i] = program(i, fn); - } - return programWrapper; - }, - merge: function(param, common) { - var ret = param || common; - - if (param && common && (param !== common)) { - ret = {}; - Utils.extend(ret, common); - Utils.extend(ret, param); - } - return ret; - }, - programWithDepth: env.VM.programWithDepth, - noop: env.VM.noop, - compilerInfo: null - }; - - return function(context, options) { - options = options || {}; - var namespace = options.partial ? options : env, - helpers, - partials; - - if (!options.partial) { - helpers = options.helpers; - partials = options.partials; - } - var result = templateSpec.call( - container, - namespace, context, - helpers, - partials, - options.data); - - if (!options.partial) { - env.VM.checkRevision(container.compilerInfo); - } - - return result; - }; -} - -exports.template = template;function programWithDepth(i, fn, data /*, $depth */) { - var args = Array.prototype.slice.call(arguments, 3); - - var prog = function(context, options) { - options = options || {}; - - return fn.apply(this, [context, options.data || data].concat(args)); - }; - prog.program = i; - prog.depth = args.length; - return prog; -} - -exports.programWithDepth = programWithDepth;function program(i, fn, data) { - var prog = function(context, options) { - options = options || {}; - - return fn(context, options.data || data); - }; - prog.program = i; - prog.depth = 0; - return prog; -} - -exports.program = program;function invokePartial(partial, name, context, helpers, partials, data) { - var options = { partial: true, helpers: helpers, partials: partials, data: data }; - - if(partial === undefined) { - throw new Exception("The partial " + name + " could not be found"); - } else if(partial instanceof Function) { - return partial(context, options); - } -} - -exports.invokePartial = invokePartial;function noop() { return ""; } - -exports.noop = noop; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/safe-string.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/safe-string.js deleted file mode 100644 index dffadbfe3..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/safe-string.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -// Build out our basic SafeString type -function SafeString(string) { - this.string = string; -} - -SafeString.prototype.toString = function() { - return "" + this.string; -}; - -exports["default"] = SafeString; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/utils.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/utils.js deleted file mode 100644 index c04554774..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/cjs/handlebars/utils.js +++ /dev/null @@ -1,76 +0,0 @@ -"use strict"; -/*jshint -W004 */ -var SafeString = require("./safe-string")["default"]; - -var escape = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "`": "`" -}; - -var badChars = /[&<>"'`]/g; -var possible = /[&<>"'`]/; - -function escapeChar(chr) { - return escape[chr] || "&"; -} - -function extend(obj, value) { - for(var key in value) { - if(Object.prototype.hasOwnProperty.call(value, key)) { - obj[key] = value[key]; - } - } -} - -exports.extend = extend;var toString = Object.prototype.toString; -exports.toString = toString; -// Sourced from lodash -// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt -var isFunction = function(value) { - return typeof value === 'function'; -}; -// fallback for older versions of Chrome and Safari -if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; -} -var isFunction; -exports.isFunction = isFunction; -var isArray = Array.isArray || function(value) { - return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false; -}; -exports.isArray = isArray; - -function escapeExpression(string) { - // don't escape SafeStrings, since they're already safe - if (string instanceof SafeString) { - return string.toString(); - } else if (!string && string !== 0) { - return ""; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = "" + string; - - if(!possible.test(string)) { return string; } - return string.replace(badChars, escapeChar); -} - -exports.escapeExpression = escapeExpression;function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } -} - -exports.isEmpty = isEmpty; \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.amd.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.amd.js deleted file mode 100644 index b51e42a0d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.amd.js +++ /dev/null @@ -1,2719 +0,0 @@ -/*! - - handlebars v1.3.0 - -Copyright (C) 2011 by Yehuda Katz - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -@license -*/ - -define( - 'handlebars/safe-string',["exports"], - function(__exports__) { - - // Build out our basic SafeString type - function SafeString(string) { - this.string = string; - } - - SafeString.prototype.toString = function() { - return "" + this.string; - }; - - __exports__["default"] = SafeString; - }); -define( - 'handlebars/utils',["./safe-string","exports"], - function(__dependency1__, __exports__) { - - /*jshint -W004 */ - var SafeString = __dependency1__["default"]; - - var escape = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "`": "`" - }; - - var badChars = /[&<>"'`]/g; - var possible = /[&<>"'`]/; - - function escapeChar(chr) { - return escape[chr] || "&"; - } - - function extend(obj, value) { - for(var key in value) { - if(Object.prototype.hasOwnProperty.call(value, key)) { - obj[key] = value[key]; - } - } - } - - __exports__.extend = extend;var toString = Object.prototype.toString; - __exports__.toString = toString; - // Sourced from lodash - // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt - var isFunction = function(value) { - return typeof value === 'function'; - }; - // fallback for older versions of Chrome and Safari - if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; - } - var isFunction; - __exports__.isFunction = isFunction; - var isArray = Array.isArray || function(value) { - return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false; - }; - __exports__.isArray = isArray; - - function escapeExpression(string) { - // don't escape SafeStrings, since they're already safe - if (string instanceof SafeString) { - return string.toString(); - } else if (!string && string !== 0) { - return ""; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = "" + string; - - if(!possible.test(string)) { return string; } - return string.replace(badChars, escapeChar); - } - - __exports__.escapeExpression = escapeExpression;function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } - } - - __exports__.isEmpty = isEmpty; - }); -define( - 'handlebars/exception',["exports"], - function(__exports__) { - - - var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; - - function Exception(message, node) { - var line; - if (node && node.firstLine) { - line = node.firstLine; - - message += ' - ' + line + ':' + node.firstColumn; - } - - var tmp = Error.prototype.constructor.call(this, message); - - // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. - for (var idx = 0; idx < errorProps.length; idx++) { - this[errorProps[idx]] = tmp[errorProps[idx]]; - } - - if (line) { - this.lineNumber = line; - this.column = node.firstColumn; - } - } - - Exception.prototype = new Error(); - - __exports__["default"] = Exception; - }); -define( - 'handlebars/base',["./utils","./exception","exports"], - function(__dependency1__, __dependency2__, __exports__) { - - var Utils = __dependency1__; - var Exception = __dependency2__["default"]; - - var VERSION = "1.3.0"; - __exports__.VERSION = VERSION;var COMPILER_REVISION = 4; - __exports__.COMPILER_REVISION = COMPILER_REVISION; - var REVISION_CHANGES = { - 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '== 1.0.0-rc.3', - 3: '== 1.0.0-rc.4', - 4: '>= 1.0.0' - }; - __exports__.REVISION_CHANGES = REVISION_CHANGES; - var isArray = Utils.isArray, - isFunction = Utils.isFunction, - toString = Utils.toString, - objectType = '[object Object]'; - - function HandlebarsEnvironment(helpers, partials) { - this.helpers = helpers || {}; - this.partials = partials || {}; - - registerDefaultHelpers(this); - } - - __exports__.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = { - constructor: HandlebarsEnvironment, - - logger: logger, - log: log, - - registerHelper: function(name, fn, inverse) { - if (toString.call(name) === objectType) { - if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); } - Utils.extend(this.helpers, name); - } else { - if (inverse) { fn.not = inverse; } - this.helpers[name] = fn; - } - }, - - registerPartial: function(name, str) { - if (toString.call(name) === objectType) { - Utils.extend(this.partials, name); - } else { - this.partials[name] = str; - } - } - }; - - function registerDefaultHelpers(instance) { - instance.registerHelper('helperMissing', function(arg) { - if(arguments.length === 2) { - return undefined; - } else { - throw new Exception("Missing helper: '" + arg + "'"); - } - }); - - instance.registerHelper('blockHelperMissing', function(context, options) { - var inverse = options.inverse || function() {}, fn = options.fn; - - if (isFunction(context)) { context = context.call(this); } - - if(context === true) { - return fn(this); - } else if(context === false || context == null) { - return inverse(this); - } else if (isArray(context)) { - if(context.length > 0) { - return instance.helpers.each(context, options); - } else { - return inverse(this); - } - } else { - return fn(context); - } - }); - - instance.registerHelper('each', function(context, options) { - var fn = options.fn, inverse = options.inverse; - var i = 0, ret = "", data; - - if (isFunction(context)) { context = context.call(this); } - - if (options.data) { - data = createFrame(options.data); - } - - if(context && typeof context === 'object') { - if (isArray(context)) { - for(var j = context.length; i 0) { - throw new Exception("Invalid path: " + original, this); - } else if (part === "..") { - depth++; - } else { - this.isScoped = true; - } - } else { - dig.push(part); - } - } - - this.original = original; - this.parts = dig; - this.string = dig.join('.'); - this.depth = depth; - - // an ID is simple if it only has one part, and that part is not - // `..` or `this`. - this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; - - this.stringModeValue = this.string; - }, - - PartialNameNode: function(name, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "PARTIAL_NAME"; - this.name = name.original; - }, - - DataNode: function(id, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "DATA"; - this.id = id; - }, - - StringNode: function(string, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "STRING"; - this.original = - this.string = - this.stringModeValue = string; - }, - - IntegerNode: function(integer, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "INTEGER"; - this.original = - this.integer = integer; - this.stringModeValue = Number(integer); - }, - - BooleanNode: function(bool, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "BOOLEAN"; - this.bool = bool; - this.stringModeValue = bool === "true"; - }, - - CommentNode: function(comment, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "comment"; - this.comment = comment; - } - }; - - // Must be exported as an object rather than the root of the module as the jison lexer - // most modify the object to operate properly. - __exports__["default"] = AST; - }); -define( - 'handlebars/compiler/parser',["exports"], - function(__exports__) { - - /* jshint ignore:start */ - /* Jison generated parser */ - var handlebars = (function(){ - var parser = {trace: function trace() { }, - yy: {}, - symbols_: {"error":2,"root":3,"statements":4,"EOF":5,"program":6,"simpleInverse":7,"statement":8,"openInverse":9,"closeBlock":10,"openBlock":11,"mustache":12,"partial":13,"CONTENT":14,"COMMENT":15,"OPEN_BLOCK":16,"sexpr":17,"CLOSE":18,"OPEN_INVERSE":19,"OPEN_ENDBLOCK":20,"path":21,"OPEN":22,"OPEN_UNESCAPED":23,"CLOSE_UNESCAPED":24,"OPEN_PARTIAL":25,"partialName":26,"partial_option0":27,"sexpr_repetition0":28,"sexpr_option0":29,"dataName":30,"param":31,"STRING":32,"INTEGER":33,"BOOLEAN":34,"OPEN_SEXPR":35,"CLOSE_SEXPR":36,"hash":37,"hash_repetition_plus0":38,"hashSegment":39,"ID":40,"EQUALS":41,"DATA":42,"pathSegments":43,"SEP":44,"$accept":0,"$end":1}, - terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"CLOSE_UNESCAPED",25:"OPEN_PARTIAL",32:"STRING",33:"INTEGER",34:"BOOLEAN",35:"OPEN_SEXPR",36:"CLOSE_SEXPR",40:"ID",41:"EQUALS",42:"DATA",44:"SEP"}, - productions_: [0,[3,2],[3,1],[6,2],[6,3],[6,2],[6,1],[6,1],[6,0],[4,1],[4,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,4],[7,2],[17,3],[17,1],[31,1],[31,1],[31,1],[31,1],[31,1],[31,3],[37,1],[39,3],[26,1],[26,1],[26,1],[30,2],[21,1],[43,3],[43,1],[27,0],[27,1],[28,0],[28,2],[29,0],[29,1],[38,1],[38,2]], - performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { - - var $0 = $$.length - 1; - switch (yystate) { - case 1: return new yy.ProgramNode($$[$0-1], this._$); - break; - case 2: return new yy.ProgramNode([], this._$); - break; - case 3:this.$ = new yy.ProgramNode([], $$[$0-1], $$[$0], this._$); - break; - case 4:this.$ = new yy.ProgramNode($$[$0-2], $$[$0-1], $$[$0], this._$); - break; - case 5:this.$ = new yy.ProgramNode($$[$0-1], $$[$0], [], this._$); - break; - case 6:this.$ = new yy.ProgramNode($$[$0], this._$); - break; - case 7:this.$ = new yy.ProgramNode([], this._$); - break; - case 8:this.$ = new yy.ProgramNode([], this._$); - break; - case 9:this.$ = [$$[$0]]; - break; - case 10: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; - break; - case 11:this.$ = new yy.BlockNode($$[$0-2], $$[$0-1].inverse, $$[$0-1], $$[$0], this._$); - break; - case 12:this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0-1].inverse, $$[$0], this._$); - break; - case 13:this.$ = $$[$0]; - break; - case 14:this.$ = $$[$0]; - break; - case 15:this.$ = new yy.ContentNode($$[$0], this._$); - break; - case 16:this.$ = new yy.CommentNode($$[$0], this._$); - break; - case 17:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); - break; - case 18:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); - break; - case 19:this.$ = {path: $$[$0-1], strip: stripFlags($$[$0-2], $$[$0])}; - break; - case 20:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); - break; - case 21:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); - break; - case 22:this.$ = new yy.PartialNode($$[$0-2], $$[$0-1], stripFlags($$[$0-3], $$[$0]), this._$); - break; - case 23:this.$ = stripFlags($$[$0-1], $$[$0]); - break; - case 24:this.$ = new yy.SexprNode([$$[$0-2]].concat($$[$0-1]), $$[$0], this._$); - break; - case 25:this.$ = new yy.SexprNode([$$[$0]], null, this._$); - break; - case 26:this.$ = $$[$0]; - break; - case 27:this.$ = new yy.StringNode($$[$0], this._$); - break; - case 28:this.$ = new yy.IntegerNode($$[$0], this._$); - break; - case 29:this.$ = new yy.BooleanNode($$[$0], this._$); - break; - case 30:this.$ = $$[$0]; - break; - case 31:$$[$0-1].isHelper = true; this.$ = $$[$0-1]; - break; - case 32:this.$ = new yy.HashNode($$[$0], this._$); - break; - case 33:this.$ = [$$[$0-2], $$[$0]]; - break; - case 34:this.$ = new yy.PartialNameNode($$[$0], this._$); - break; - case 35:this.$ = new yy.PartialNameNode(new yy.StringNode($$[$0], this._$), this._$); - break; - case 36:this.$ = new yy.PartialNameNode(new yy.IntegerNode($$[$0], this._$)); - break; - case 37:this.$ = new yy.DataNode($$[$0], this._$); - break; - case 38:this.$ = new yy.IdNode($$[$0], this._$); - break; - case 39: $$[$0-2].push({part: $$[$0], separator: $$[$0-1]}); this.$ = $$[$0-2]; - break; - case 40:this.$ = [{part: $$[$0]}]; - break; - case 43:this.$ = []; - break; - case 44:$$[$0-1].push($$[$0]); - break; - case 47:this.$ = [$$[$0]]; - break; - case 48:$$[$0-1].push($$[$0]); - break; - } - }, - table: [{3:1,4:2,5:[1,3],8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[3]},{5:[1,16],8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[2,2]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],25:[2,9]},{4:20,6:18,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{4:20,6:22,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{5:[2,13],14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],25:[2,13]},{5:[2,14],14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],25:[2,14]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],25:[2,15]},{5:[2,16],14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],25:[2,16]},{17:23,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:29,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:30,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:31,21:24,30:25,40:[1,28],42:[1,27],43:26},{21:33,26:32,32:[1,34],33:[1,35],40:[1,28],43:26},{1:[2,1]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],25:[2,10]},{10:36,20:[1,37]},{4:38,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,7],22:[1,13],23:[1,14],25:[1,15]},{7:39,8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,6],22:[1,13],23:[1,14],25:[1,15]},{17:23,18:[1,40],21:24,30:25,40:[1,28],42:[1,27],43:26},{10:41,20:[1,37]},{18:[1,42]},{18:[2,43],24:[2,43],28:43,32:[2,43],33:[2,43],34:[2,43],35:[2,43],36:[2,43],40:[2,43],42:[2,43]},{18:[2,25],24:[2,25],36:[2,25]},{18:[2,38],24:[2,38],32:[2,38],33:[2,38],34:[2,38],35:[2,38],36:[2,38],40:[2,38],42:[2,38],44:[1,44]},{21:45,40:[1,28],43:26},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],42:[2,40],44:[2,40]},{18:[1,46]},{18:[1,47]},{24:[1,48]},{18:[2,41],21:50,27:49,40:[1,28],43:26},{18:[2,34],40:[2,34]},{18:[2,35],40:[2,35]},{18:[2,36],40:[2,36]},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],25:[2,11]},{21:51,40:[1,28],43:26},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,3],22:[1,13],23:[1,14],25:[1,15]},{4:52,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,5],22:[1,13],23:[1,14],25:[1,15]},{14:[2,23],15:[2,23],16:[2,23],19:[2,23],20:[2,23],22:[2,23],23:[2,23],25:[2,23]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],25:[2,12]},{14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],25:[2,18]},{18:[2,45],21:56,24:[2,45],29:53,30:60,31:54,32:[1,57],33:[1,58],34:[1,59],35:[1,61],36:[2,45],37:55,38:62,39:63,40:[1,64],42:[1,27],43:26},{40:[1,65]},{18:[2,37],24:[2,37],32:[2,37],33:[2,37],34:[2,37],35:[2,37],36:[2,37],40:[2,37],42:[2,37]},{14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],25:[2,17]},{5:[2,20],14:[2,20],15:[2,20],16:[2,20],19:[2,20],20:[2,20],22:[2,20],23:[2,20],25:[2,20]},{5:[2,21],14:[2,21],15:[2,21],16:[2,21],19:[2,21],20:[2,21],22:[2,21],23:[2,21],25:[2,21]},{18:[1,66]},{18:[2,42]},{18:[1,67]},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],25:[1,15]},{18:[2,24],24:[2,24],36:[2,24]},{18:[2,44],24:[2,44],32:[2,44],33:[2,44],34:[2,44],35:[2,44],36:[2,44],40:[2,44],42:[2,44]},{18:[2,46],24:[2,46],36:[2,46]},{18:[2,26],24:[2,26],32:[2,26],33:[2,26],34:[2,26],35:[2,26],36:[2,26],40:[2,26],42:[2,26]},{18:[2,27],24:[2,27],32:[2,27],33:[2,27],34:[2,27],35:[2,27],36:[2,27],40:[2,27],42:[2,27]},{18:[2,28],24:[2,28],32:[2,28],33:[2,28],34:[2,28],35:[2,28],36:[2,28],40:[2,28],42:[2,28]},{18:[2,29],24:[2,29],32:[2,29],33:[2,29],34:[2,29],35:[2,29],36:[2,29],40:[2,29],42:[2,29]},{18:[2,30],24:[2,30],32:[2,30],33:[2,30],34:[2,30],35:[2,30],36:[2,30],40:[2,30],42:[2,30]},{17:68,21:24,30:25,40:[1,28],42:[1,27],43:26},{18:[2,32],24:[2,32],36:[2,32],39:69,40:[1,70]},{18:[2,47],24:[2,47],36:[2,47],40:[2,47]},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],41:[1,71],42:[2,40],44:[2,40]},{18:[2,39],24:[2,39],32:[2,39],33:[2,39],34:[2,39],35:[2,39],36:[2,39],40:[2,39],42:[2,39],44:[2,39]},{5:[2,22],14:[2,22],15:[2,22],16:[2,22],19:[2,22],20:[2,22],22:[2,22],23:[2,22],25:[2,22]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],25:[2,19]},{36:[1,72]},{18:[2,48],24:[2,48],36:[2,48],40:[2,48]},{41:[1,71]},{21:56,30:60,31:73,32:[1,57],33:[1,58],34:[1,59],35:[1,61],40:[1,28],42:[1,27],43:26},{18:[2,31],24:[2,31],32:[2,31],33:[2,31],34:[2,31],35:[2,31],36:[2,31],40:[2,31],42:[2,31]},{18:[2,33],24:[2,33],36:[2,33],40:[2,33]}], - defaultActions: {3:[2,2],16:[2,1],50:[2,42]}, - parseError: function parseError(str, hash) { - throw new Error(str); - }, - parse: function parse(input) { - var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; - this.lexer.setInput(input); - this.lexer.yy = this.yy; - this.yy.lexer = this.lexer; - this.yy.parser = this; - if (typeof this.lexer.yylloc == "undefined") - this.lexer.yylloc = {}; - var yyloc = this.lexer.yylloc; - lstack.push(yyloc); - var ranges = this.lexer.options && this.lexer.options.ranges; - if (typeof this.yy.parseError === "function") - this.parseError = this.yy.parseError; - function popStack(n) { - stack.length = stack.length - 2 * n; - vstack.length = vstack.length - n; - lstack.length = lstack.length - n; - } - function lex() { - var token; - token = self.lexer.lex() || 1; - if (typeof token !== "number") { - token = self.symbols_[token] || token; - } - return token; - } - var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; - while (true) { - state = stack[stack.length - 1]; - if (this.defaultActions[state]) { - action = this.defaultActions[state]; - } else { - if (symbol === null || typeof symbol == "undefined") { - symbol = lex(); - } - action = table[state] && table[state][symbol]; - } - if (typeof action === "undefined" || !action.length || !action[0]) { - var errStr = ""; - if (!recovering) { - expected = []; - for (p in table[state]) - if (this.terminals_[p] && p > 2) { - expected.push("'" + this.terminals_[p] + "'"); - } - if (this.lexer.showPosition) { - errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; - } else { - errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); - } - this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); - } - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) - recovering--; - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; - if (ranges) { - yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; - } - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - if (typeof r !== "undefined") { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } - } - return true; - } - }; - - - function stripFlags(open, close) { - return { - left: open.charAt(2) === '~', - right: close.charAt(0) === '~' || close.charAt(1) === '~' - }; - } - - /* Jison generated lexer */ - var lexer = (function(){ - var lexer = ({EOF:1, - parseError:function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, - setInput:function (input) { - this._input = input; - this._more = this._less = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; - if (this.options.ranges) this.yylloc.range = [0,0]; - this.offset = 0; - return this; - }, - input:function () { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) this.yylloc.range[1]++; - - this._input = this._input.slice(1); - return ch; - }, - unput:function (ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); - - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length-len-1); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length-1); - this.matched = this.matched.substr(0, this.matched.length-1); - - if (lines.length-1) this.yylineno -= lines.length-1; - var r = this.yylloc.range; - - this.yylloc = {first_line: this.yylloc.first_line, - last_line: this.yylineno+1, - first_column: this.yylloc.first_column, - last_column: lines ? - (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: - this.yylloc.first_column - len - }; - - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - return this; - }, - more:function () { - this._more = true; - return this; - }, - less:function (n) { - this.unput(this.match.slice(n)); - }, - pastInput:function () { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); - }, - upcomingInput:function () { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20-next.length); - } - return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); - }, - showPosition:function () { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c+"^"; - }, - next:function () { - if (this.done) { - return this.EOF; - } - if (!this._input) this.done = true; - - var token, - match, - tempMatch, - index, - col, - lines; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i=0;i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (!this.options.flex) break; - } - } - if (match) { - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) this.yylineno += lines.length; - this.yylloc = {first_line: this.yylloc.last_line, - last_line: this.yylineno+1, - first_column: this.yylloc.last_column, - last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); - if (this.done && this._input) this.done = false; - if (token) return token; - else return; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), - {text: "", token: null, line: this.yylineno}); - } - }, - lex:function lex() { - var r = this.next(); - if (typeof r !== 'undefined') { - return r; - } else { - return this.lex(); - } - }, - begin:function begin(condition) { - this.conditionStack.push(condition); - }, - popState:function popState() { - return this.conditionStack.pop(); - }, - _currentRules:function _currentRules() { - return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; - }, - topState:function () { - return this.conditionStack[this.conditionStack.length-2]; - }, - pushState:function begin(condition) { - this.begin(condition); - }}); - lexer.options = {}; - lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { - - - function strip(start, end) { - return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng-end); - } - - - var YYSTATE=YY_START - switch($avoiding_name_collisions) { - case 0: - if(yy_.yytext.slice(-2) === "\\\\") { - strip(0,1); - this.begin("mu"); - } else if(yy_.yytext.slice(-1) === "\\") { - strip(0,1); - this.begin("emu"); - } else { - this.begin("mu"); - } - if(yy_.yytext) return 14; - - break; - case 1:return 14; - break; - case 2: - this.popState(); - return 14; - - break; - case 3:strip(0,4); this.popState(); return 15; - break; - case 4:return 35; - break; - case 5:return 36; - break; - case 6:return 25; - break; - case 7:return 16; - break; - case 8:return 20; - break; - case 9:return 19; - break; - case 10:return 19; - break; - case 11:return 23; - break; - case 12:return 22; - break; - case 13:this.popState(); this.begin('com'); - break; - case 14:strip(3,5); this.popState(); return 15; - break; - case 15:return 22; - break; - case 16:return 41; - break; - case 17:return 40; - break; - case 18:return 40; - break; - case 19:return 44; - break; - case 20:// ignore whitespace - break; - case 21:this.popState(); return 24; - break; - case 22:this.popState(); return 18; - break; - case 23:yy_.yytext = strip(1,2).replace(/\\"/g,'"'); return 32; - break; - case 24:yy_.yytext = strip(1,2).replace(/\\'/g,"'"); return 32; - break; - case 25:return 42; - break; - case 26:return 34; - break; - case 27:return 34; - break; - case 28:return 33; - break; - case 29:return 40; - break; - case 30:yy_.yytext = strip(1,2); return 40; - break; - case 31:return 'INVALID'; - break; - case 32:return 5; - break; - } - }; - lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; - lexer.conditions = {"mu":{"rules":[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"com":{"rules":[3],"inclusive":false},"INITIAL":{"rules":[0,1,32],"inclusive":true}}; - return lexer;})() - parser.lexer = lexer; - function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; - return new Parser; - })();__exports__["default"] = handlebars; - /* jshint ignore:end */ - }); -define( - 'handlebars/compiler/base',["./parser","./ast","exports"], - function(__dependency1__, __dependency2__, __exports__) { - - var parser = __dependency1__["default"]; - var AST = __dependency2__["default"]; - - __exports__.parser = parser; - - function parse(input) { - // Just return if an already-compile AST was passed in. - if(input.constructor === AST.ProgramNode) { return input; } - - parser.yy = AST; - return parser.parse(input); - } - - __exports__.parse = parse; - }); -define( - 'handlebars/compiler/compiler',["../exception","exports"], - function(__dependency1__, __exports__) { - - var Exception = __dependency1__["default"]; - - function Compiler() {} - - __exports__.Compiler = Compiler;// the foundHelper register will disambiguate helper lookup from finding a - // function in a context. This is necessary for mustache compatibility, which - // requires that context functions in blocks are evaluated by blockHelperMissing, - // and then proceed as if the resulting value was provided to blockHelperMissing. - - Compiler.prototype = { - compiler: Compiler, - - disassemble: function() { - var opcodes = this.opcodes, opcode, out = [], params, param; - - for (var i=0, l=opcodes.length; i 0) { - this.source[1] = this.source[1] + ", " + locals.join(", "); - } - - // Generate minimizer alias mappings - if (!this.isChild) { - for (var alias in this.context.aliases) { - if (this.context.aliases.hasOwnProperty(alias)) { - this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; - } - } - } - - if (this.source[1]) { - this.source[1] = "var " + this.source[1].substring(2) + ";"; - } - - // Merge children - if (!this.isChild) { - this.source[1] += '\n' + this.context.programs.join('\n') + '\n'; - } - - if (!this.environment.isSimple) { - this.pushSource("return buffer;"); - } - - var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"]; - - for(var i=0, l=this.environment.depths.list.length; i this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } - return this.topStackName(); - }, - topStackName: function() { - return "stack" + this.stackSlot; - }, - flushInline: function() { - var inlineStack = this.inlineStack; - if (inlineStack.length) { - this.inlineStack = []; - for (var i = 0, len = inlineStack.length; i < len; i++) { - var entry = inlineStack[i]; - if (entry instanceof Literal) { - this.compileStack.push(entry); - } else { - this.pushStack(entry); - } - } - } - }, - isInline: function() { - return this.inlineStack.length; - }, - - popStack: function(wrapped) { - var inline = this.isInline(), - item = (inline ? this.inlineStack : this.compileStack).pop(); - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - if (!inline) { - if (!this.stackSlot) { - throw new Exception('Invalid stack pop'); - } - this.stackSlot--; - } - return item; - } - }, - - topStack: function(wrapped) { - var stack = (this.isInline() ? this.inlineStack : this.compileStack), - item = stack[stack.length - 1]; - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - return item; - } - }, - - quotedString: function(str) { - return '"' + str - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 - .replace(/\u2029/g, '\\u2029') + '"'; - }, - - setupHelper: function(paramSize, name, missingParams) { - var params = [], - paramsInit = this.setupParams(paramSize, params, missingParams); - var foundHelper = this.nameLookup('helpers', name, 'helper'); - - return { - params: params, - paramsInit: paramsInit, - name: foundHelper, - callParams: ["depth0"].concat(params).join(", "), - helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ") - }; - }, - - setupOptions: function(paramSize, params) { - var options = [], contexts = [], types = [], param, inverse, program; - - options.push("hash:" + this.popStack()); - - if (this.options.stringParams) { - options.push("hashTypes:" + this.popStack()); - options.push("hashContexts:" + this.popStack()); - } - - inverse = this.popStack(); - program = this.popStack(); - - // Avoid setting fn and inverse if neither are set. This allows - // helpers to do a check for `if (options.fn)` - if (program || inverse) { - if (!program) { - this.context.aliases.self = "this"; - program = "self.noop"; - } - - if (!inverse) { - this.context.aliases.self = "this"; - inverse = "self.noop"; - } - - options.push("inverse:" + inverse); - options.push("fn:" + program); - } - - for(var i=0; i":">",'"':""","'":"'","`":"`"},i=/[&<>"'`]/g,j=/[&<>"'`]/;b.extend=d;var k=Object.prototype.toString;b.toString=k;var l=function(a){return"function"==typeof a};l(/x/)&&(l=function(a){return"function"==typeof a&&"[object Function]"===k.call(a)});var l;b.isFunction=l;var m=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===k.call(a):!1};b.isArray=m,b.escapeExpression=e,b.isEmpty=f}),define("handlebars/exception",["exports"],function(a){function b(a,b){var d;b&&b.firstLine&&(d=b.firstLine,a+=" - "+d+":"+b.firstColumn);for(var e=Error.prototype.constructor.call(this,a),f=0;f0?a.helpers.each(b,c):d(this):e(b)}),a.registerHelper("each",function(a,b){var c,d=b.fn,e=b.inverse,f=0,g="";if(m(a)&&(a=a.call(this)),b.data&&(c=q(b.data)),a&&"object"==typeof a)if(l(a))for(var h=a.length;h>f;f++)c&&(c.index=f,c.first=0===f,c.last=f===a.length-1),g+=d(a[f],{data:c});else for(var i in a)a.hasOwnProperty(i)&&(c&&(c.key=i,c.index=f,c.first=0===f),g+=d(a[i],{data:c}),f++);return 0===f&&(g=e(this)),g}),a.registerHelper("if",function(a,b){return m(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||g.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){return m(a)&&(a=a.call(this)),g.isEmpty(a)?void 0:b.fn(a)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)})}function f(a,b){p.log(a,b)}var g=a,h=b["default"],i="1.3.0";c.VERSION=i;var j=4;c.COMPILER_REVISION=j;var k={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"};c.REVISION_CHANGES=k;var l=g.isArray,m=g.isFunction,n=g.toString,o="[object Object]";c.HandlebarsEnvironment=d,d.prototype={constructor:d,logger:p,log:f,registerHelper:function(a,b,c){if(n.call(a)===o){if(c||b)throw new h("Arg not supported with multiple helpers");g.extend(this.helpers,a)}else c&&(b.not=c),this.helpers[a]=b},registerPartial:function(a,b){n.call(a)===o?g.extend(this.partials,a):this.partials[a]=b}};var p={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,log:function(a,b){if(p.level<=a){var c=p.methodMap[a];"undefined"!=typeof console&&console[c]&&console[c].call(console,b)}}};c.logger=p,c.log=f;var q=function(a){var b={};return g.extend(b,a),b};c.createFrame=q}),define("handlebars/runtime",["./utils","./exception","./base","exports"],function(a,b,c,d){function e(a){var b=a&&a[0]||1,c=m;if(b!==c){if(c>b){var d=n[c],e=n[b];throw new l("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new l("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function f(a,b){if(!b)throw new l("No environment passed to template");var c=function(a,c,d,e,f,g){var h=b.VM.invokePartial.apply(this,arguments);if(null!=h)return h;if(b.compile){var i={helpers:e,partials:f,data:g};return f[c]=b.compile(a,{data:void 0!==g},b),f[c](d,i)}throw new l("The partial "+c+" could not be compiled when running in runtime-only mode")},d={escapeExpression:k.escapeExpression,invokePartial:c,programs:[],program:function(a,b,c){var d=this.programs[a];return c?d=h(a,b,c):d||(d=this.programs[a]=h(a,b)),d},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c={},k.extend(c,b),k.extend(c,a)),c},programWithDepth:b.VM.programWithDepth,noop:b.VM.noop,compilerInfo:null};return function(c,e){e=e||{};var f,g,h=e.partial?e:b;e.partial||(f=e.helpers,g=e.partials);var i=a.call(d,h,c,f,g,e.data);return e.partial||b.VM.checkRevision(d.compilerInfo),i}}function g(a,b,c){var d=Array.prototype.slice.call(arguments,3),e=function(a,e){return e=e||{},b.apply(this,[a,e.data||c].concat(d))};return e.program=a,e.depth=d.length,e}function h(a,b,c){var d=function(a,d){return d=d||{},b(a,d.data||c)};return d.program=a,d.depth=0,d}function i(a,b,c,d,e,f){var g={partial:!0,helpers:d,partials:e,data:f};if(void 0===a)throw new l("The partial "+b+" could not be found");return a instanceof Function?a(c,g):void 0}function j(){return""}var k=a,l=b["default"],m=c.COMPILER_REVISION,n=c.REVISION_CHANGES;d.checkRevision=e,d.template=f,d.programWithDepth=g,d.program=h,d.invokePartial=i,d.noop=j}),define("handlebars.runtime",["./handlebars/base","./handlebars/safe-string","./handlebars/exception","./handlebars/utils","./handlebars/runtime","exports"],function(a,b,c,d,e,f){var g=a,h=b["default"],i=c["default"],j=d,k=e,l=function(){var a=new g.HandlebarsEnvironment;return j.extend(a,g),a.SafeString=h,a.Exception=i,a.Utils=j,a.VM=k,a.template=function(b){return k.template(b,a)},a},m=l();m.create=l,f["default"]=m}),define("handlebars/compiler/ast",["../exception","exports"],function(a,b){function c(a){a=a||{},this.firstLine=a.first_line,this.firstColumn=a.first_column,this.lastColumn=a.last_column,this.lastLine=a.last_line}var d=a["default"],e={ProgramNode:function(a,b,d,f){var g,h;3===arguments.length?(f=d,d=null):2===arguments.length&&(f=b,b=null),c.call(this,f),this.type="program",this.statements=a,this.strip={},d?(h=d[0],h?(g={first_line:h.firstLine,last_line:h.lastLine,last_column:h.lastColumn,first_column:h.firstColumn},this.inverse=new e.ProgramNode(d,b,g)):this.inverse=new e.ProgramNode(d,b),this.strip.right=b.left):b&&(this.strip.left=b.right)},MustacheNode:function(a,b,d,f,g){if(c.call(this,g),this.type="mustache",this.strip=f,null!=d&&d.charAt){var h=d.charAt(3)||d.charAt(2);this.escaped="{"!==h&&"&"!==h}else this.escaped=!!d;this.sexpr=a instanceof e.SexprNode?a:new e.SexprNode(a,b),this.sexpr.isRoot=!0,this.id=this.sexpr.id,this.params=this.sexpr.params,this.hash=this.sexpr.hash,this.eligibleHelper=this.sexpr.eligibleHelper,this.isHelper=this.sexpr.isHelper},SexprNode:function(a,b,d){c.call(this,d),this.type="sexpr",this.hash=b;var e=this.id=a[0],f=this.params=a.slice(1),g=this.eligibleHelper=e.isSimple;this.isHelper=g&&(f.length||b)},PartialNode:function(a,b,d,e){c.call(this,e),this.type="partial",this.partialName=a,this.context=b,this.strip=d},BlockNode:function(a,b,e,f,g){if(c.call(this,g),a.sexpr.id.original!==f.path.original)throw new d(a.sexpr.id.original+" doesn't match "+f.path.original,this);this.type="block",this.mustache=a,this.program=b,this.inverse=e,this.strip={left:a.strip.left,right:f.strip.right},(b||e).strip.left=a.strip.right,(e||b).strip.right=f.strip.left,e&&!b&&(this.isInverse=!0)},ContentNode:function(a,b){c.call(this,b),this.type="content",this.string=a},HashNode:function(a,b){c.call(this,b),this.type="hash",this.pairs=a},IdNode:function(a,b){c.call(this,b),this.type="ID";for(var e="",f=[],g=0,h=0,i=a.length;i>h;h++){var j=a[h].part;if(e+=(a[h].separator||"")+j,".."===j||"."===j||"this"===j){if(f.length>0)throw new d("Invalid path: "+e,this);".."===j?g++:this.isScoped=!0}else f.push(j)}this.original=e,this.parts=f,this.string=f.join("."),this.depth=g,this.isSimple=1===a.length&&!this.isScoped&&0===g,this.stringModeValue=this.string},PartialNameNode:function(a,b){c.call(this,b),this.type="PARTIAL_NAME",this.name=a.original},DataNode:function(a,b){c.call(this,b),this.type="DATA",this.id=a},StringNode:function(a,b){c.call(this,b),this.type="STRING",this.original=this.string=this.stringModeValue=a},IntegerNode:function(a,b){c.call(this,b),this.type="INTEGER",this.original=this.integer=a,this.stringModeValue=Number(a)},BooleanNode:function(a,b){c.call(this,b),this.type="BOOLEAN",this.bool=a,this.stringModeValue="true"===a},CommentNode:function(a,b){c.call(this,b),this.type="comment",this.comment=a}};b["default"]=e}),define("handlebars/compiler/parser",["exports"],function(a){var b=function(){function a(a,b){return{left:"~"===a.charAt(2),right:"~"===b.charAt(0)||"~"===b.charAt(1)}}function b(){this.yy={}}var c={trace:function(){},yy:{},symbols_:{error:2,root:3,statements:4,EOF:5,program:6,simpleInverse:7,statement:8,openInverse:9,closeBlock:10,openBlock:11,mustache:12,partial:13,CONTENT:14,COMMENT:15,OPEN_BLOCK:16,sexpr:17,CLOSE:18,OPEN_INVERSE:19,OPEN_ENDBLOCK:20,path:21,OPEN:22,OPEN_UNESCAPED:23,CLOSE_UNESCAPED:24,OPEN_PARTIAL:25,partialName:26,partial_option0:27,sexpr_repetition0:28,sexpr_option0:29,dataName:30,param:31,STRING:32,INTEGER:33,BOOLEAN:34,OPEN_SEXPR:35,CLOSE_SEXPR:36,hash:37,hash_repetition_plus0:38,hashSegment:39,ID:40,EQUALS:41,DATA:42,pathSegments:43,SEP:44,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"CLOSE_UNESCAPED",25:"OPEN_PARTIAL",32:"STRING",33:"INTEGER",34:"BOOLEAN",35:"OPEN_SEXPR",36:"CLOSE_SEXPR",40:"ID",41:"EQUALS",42:"DATA",44:"SEP"},productions_:[0,[3,2],[3,1],[6,2],[6,3],[6,2],[6,1],[6,1],[6,0],[4,1],[4,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,4],[7,2],[17,3],[17,1],[31,1],[31,1],[31,1],[31,1],[31,1],[31,3],[37,1],[39,3],[26,1],[26,1],[26,1],[30,2],[21,1],[43,3],[43,1],[27,0],[27,1],[28,0],[28,2],[29,0],[29,1],[38,1],[38,2]],performAction:function(b,c,d,e,f,g){var h=g.length-1;switch(f){case 1:return new e.ProgramNode(g[h-1],this._$);case 2:return new e.ProgramNode([],this._$);case 3:this.$=new e.ProgramNode([],g[h-1],g[h],this._$);break;case 4:this.$=new e.ProgramNode(g[h-2],g[h-1],g[h],this._$);break;case 5:this.$=new e.ProgramNode(g[h-1],g[h],[],this._$);break;case 6:this.$=new e.ProgramNode(g[h],this._$);break;case 7:this.$=new e.ProgramNode([],this._$);break;case 8:this.$=new e.ProgramNode([],this._$);break;case 9:this.$=[g[h]];break;case 10:g[h-1].push(g[h]),this.$=g[h-1];break;case 11:this.$=new e.BlockNode(g[h-2],g[h-1].inverse,g[h-1],g[h],this._$);break;case 12:this.$=new e.BlockNode(g[h-2],g[h-1],g[h-1].inverse,g[h],this._$);break;case 13:this.$=g[h];break;case 14:this.$=g[h];break;case 15:this.$=new e.ContentNode(g[h],this._$);break;case 16:this.$=new e.CommentNode(g[h],this._$);break;case 17:this.$=new e.MustacheNode(g[h-1],null,g[h-2],a(g[h-2],g[h]),this._$);break;case 18:this.$=new e.MustacheNode(g[h-1],null,g[h-2],a(g[h-2],g[h]),this._$);break;case 19:this.$={path:g[h-1],strip:a(g[h-2],g[h])};break;case 20:this.$=new e.MustacheNode(g[h-1],null,g[h-2],a(g[h-2],g[h]),this._$);break;case 21:this.$=new e.MustacheNode(g[h-1],null,g[h-2],a(g[h-2],g[h]),this._$);break;case 22:this.$=new e.PartialNode(g[h-2],g[h-1],a(g[h-3],g[h]),this._$);break;case 23:this.$=a(g[h-1],g[h]);break;case 24:this.$=new e.SexprNode([g[h-2]].concat(g[h-1]),g[h],this._$);break;case 25:this.$=new e.SexprNode([g[h]],null,this._$);break;case 26:this.$=g[h];break;case 27:this.$=new e.StringNode(g[h],this._$);break;case 28:this.$=new e.IntegerNode(g[h],this._$);break;case 29:this.$=new e.BooleanNode(g[h],this._$);break;case 30:this.$=g[h];break;case 31:g[h-1].isHelper=!0,this.$=g[h-1];break;case 32:this.$=new e.HashNode(g[h],this._$);break;case 33:this.$=[g[h-2],g[h]];break;case 34:this.$=new e.PartialNameNode(g[h],this._$);break;case 35:this.$=new e.PartialNameNode(new e.StringNode(g[h],this._$),this._$);break;case 36:this.$=new e.PartialNameNode(new e.IntegerNode(g[h],this._$));break;case 37:this.$=new e.DataNode(g[h],this._$);break;case 38:this.$=new e.IdNode(g[h],this._$);break;case 39:g[h-2].push({part:g[h],separator:g[h-1]}),this.$=g[h-2];break;case 40:this.$=[{part:g[h]}];break;case 43:this.$=[];break;case 44:g[h-1].push(g[h]);break;case 47:this.$=[g[h]];break;case 48:g[h-1].push(g[h])}},table:[{3:1,4:2,5:[1,3],8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[3]},{5:[1,16],8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[2,2]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],25:[2,9]},{4:20,6:18,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{4:20,6:22,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{5:[2,13],14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],25:[2,13]},{5:[2,14],14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],25:[2,14]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],25:[2,15]},{5:[2,16],14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],25:[2,16]},{17:23,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:29,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:30,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:31,21:24,30:25,40:[1,28],42:[1,27],43:26},{21:33,26:32,32:[1,34],33:[1,35],40:[1,28],43:26},{1:[2,1]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],25:[2,10]},{10:36,20:[1,37]},{4:38,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,7],22:[1,13],23:[1,14],25:[1,15]},{7:39,8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,6],22:[1,13],23:[1,14],25:[1,15]},{17:23,18:[1,40],21:24,30:25,40:[1,28],42:[1,27],43:26},{10:41,20:[1,37]},{18:[1,42]},{18:[2,43],24:[2,43],28:43,32:[2,43],33:[2,43],34:[2,43],35:[2,43],36:[2,43],40:[2,43],42:[2,43]},{18:[2,25],24:[2,25],36:[2,25]},{18:[2,38],24:[2,38],32:[2,38],33:[2,38],34:[2,38],35:[2,38],36:[2,38],40:[2,38],42:[2,38],44:[1,44]},{21:45,40:[1,28],43:26},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],42:[2,40],44:[2,40]},{18:[1,46]},{18:[1,47]},{24:[1,48]},{18:[2,41],21:50,27:49,40:[1,28],43:26},{18:[2,34],40:[2,34]},{18:[2,35],40:[2,35]},{18:[2,36],40:[2,36]},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],25:[2,11]},{21:51,40:[1,28],43:26},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,3],22:[1,13],23:[1,14],25:[1,15]},{4:52,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,5],22:[1,13],23:[1,14],25:[1,15]},{14:[2,23],15:[2,23],16:[2,23],19:[2,23],20:[2,23],22:[2,23],23:[2,23],25:[2,23]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],25:[2,12]},{14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],25:[2,18]},{18:[2,45],21:56,24:[2,45],29:53,30:60,31:54,32:[1,57],33:[1,58],34:[1,59],35:[1,61],36:[2,45],37:55,38:62,39:63,40:[1,64],42:[1,27],43:26},{40:[1,65]},{18:[2,37],24:[2,37],32:[2,37],33:[2,37],34:[2,37],35:[2,37],36:[2,37],40:[2,37],42:[2,37]},{14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],25:[2,17]},{5:[2,20],14:[2,20],15:[2,20],16:[2,20],19:[2,20],20:[2,20],22:[2,20],23:[2,20],25:[2,20]},{5:[2,21],14:[2,21],15:[2,21],16:[2,21],19:[2,21],20:[2,21],22:[2,21],23:[2,21],25:[2,21]},{18:[1,66]},{18:[2,42]},{18:[1,67]},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],25:[1,15]},{18:[2,24],24:[2,24],36:[2,24]},{18:[2,44],24:[2,44],32:[2,44],33:[2,44],34:[2,44],35:[2,44],36:[2,44],40:[2,44],42:[2,44]},{18:[2,46],24:[2,46],36:[2,46]},{18:[2,26],24:[2,26],32:[2,26],33:[2,26],34:[2,26],35:[2,26],36:[2,26],40:[2,26],42:[2,26]},{18:[2,27],24:[2,27],32:[2,27],33:[2,27],34:[2,27],35:[2,27],36:[2,27],40:[2,27],42:[2,27]},{18:[2,28],24:[2,28],32:[2,28],33:[2,28],34:[2,28],35:[2,28],36:[2,28],40:[2,28],42:[2,28]},{18:[2,29],24:[2,29],32:[2,29],33:[2,29],34:[2,29],35:[2,29],36:[2,29],40:[2,29],42:[2,29]},{18:[2,30],24:[2,30],32:[2,30],33:[2,30],34:[2,30],35:[2,30],36:[2,30],40:[2,30],42:[2,30]},{17:68,21:24,30:25,40:[1,28],42:[1,27],43:26},{18:[2,32],24:[2,32],36:[2,32],39:69,40:[1,70]},{18:[2,47],24:[2,47],36:[2,47],40:[2,47]},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],41:[1,71],42:[2,40],44:[2,40]},{18:[2,39],24:[2,39],32:[2,39],33:[2,39],34:[2,39],35:[2,39],36:[2,39],40:[2,39],42:[2,39],44:[2,39]},{5:[2,22],14:[2,22],15:[2,22],16:[2,22],19:[2,22],20:[2,22],22:[2,22],23:[2,22],25:[2,22]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],25:[2,19]},{36:[1,72]},{18:[2,48],24:[2,48],36:[2,48],40:[2,48]},{41:[1,71]},{21:56,30:60,31:73,32:[1,57],33:[1,58],34:[1,59],35:[1,61],40:[1,28],42:[1,27],43:26},{18:[2,31],24:[2,31],32:[2,31],33:[2,31],34:[2,31],35:[2,31],36:[2,31],40:[2,31],42:[2,31]},{18:[2,33],24:[2,33],36:[2,33],40:[2,33]}],defaultActions:{3:[2,2],16:[2,1],50:[2,42]},parseError:function(a){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:((null===n||"undefined"==typeof n)&&(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},d=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;gb[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 14;break;case 1:return 14;case 2:return this.popState(),14;case 3:return e(0,4),this.popState(),15;case 4:return 35;case 5:return 36;case 6:return 25;case 7:return 16;case 8:return 20;case 9:return 19;case 10:return 19;case 11:return 23;case 12:return 22;case 13:this.popState(),this.begin("com");break;case 14:return e(3,5),this.popState(),15;case 15:return 22;case 16:return 41;case 17:return 40;case 18:return 40;case 19:return 44;case 20:break;case 21:return this.popState(),24;case 22:return this.popState(),18;case 23:return b.yytext=e(1,2).replace(/\\"/g,'"'),32;case 24:return b.yytext=e(1,2).replace(/\\'/g,"'"),32;case 25:return 42;case 26:return 34;case 27:return 34;case 28:return 33;case 29:return 40;case 30:return b.yytext=e(1,2),40;case 31:return"INVALID";case 32:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[3],inclusive:!1},INITIAL:{rules:[0,1,32],inclusive:!0}},a}();return c.lexer=d,b.prototype=c,c.Parser=b,new b}();a["default"]=b}),define("handlebars/compiler/base",["./parser","./ast","exports"],function(a,b,c){function d(a){return a.constructor===f.ProgramNode?a:(e.yy=f,e.parse(a))}var e=a["default"],f=b["default"];c.parser=e,c.parse=d}),define("handlebars/compiler/compiler",["../exception","exports"],function(a,b){function c(){}function d(a,b,c){if(null==a||"string"!=typeof a&&a.constructor!==c.AST.ProgramNode)throw new f("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0);var d=c.parse(a),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function e(a,b,c){function d(){var d=c.parse(a),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}if(null==a||"string"!=typeof a&&a.constructor!==c.AST.ProgramNode)throw new f("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=b||{},"data"in b||(b.data=!0);var e;return function(a,b){return e||(e=d()),e.call(this,a,b)}}var f=a["default"];b.Compiler=c,c.prototype={compiler:c,disassemble:function(){for(var a,b,c,d=this.opcodes,e=[],f=0,g=d.length;g>f;f++)if(a=d[f],"DECLARE"===a.opcode)e.push("DECLARE "+a.name+"="+a.value);else{b=[];for(var h=0;hc;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||d.args.length!==e.args.length)return!1;for(var f=0;fc;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.opcodes=[],this.children=[],this.depths={list:[]},this.options=b;var c=this.options.knownHelpers;if(this.options.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0},c)for(var d in c)this.options.knownHelpers[d]=c[d];return this.accept(a)},accept:function(a){var b,c=a.strip||{};return c.left&&this.opcode("strip"),b=this[a.type](a),c.right&&this.opcode("strip"),b},program:function(a){for(var b=a.statements,c=0,d=b.length;d>c;c++)this.accept(b[c]);return this.isSimple=1===d,this.depths.list=this.depths.list.sort(function(a,b){return a-b}),this},compileProgram:function(a){var b,c=(new this.compiler).compile(a,this.options),d=this.guid++;this.usePartial=this.usePartial||c.usePartial,this.children[d]=c;for(var e=0,f=c.depths.list.length;f>e;e++)b=c.depths.list[e],2>b||this.addDepth(b-1);return d},block:function(a){var b=a.mustache,c=a.program,d=a.inverse;c&&(c=this.compileProgram(c)),d&&(d=this.compileProgram(d));var e=b.sexpr,f=this.classifySexpr(e);"helper"===f?this.helperSexpr(e,c,d):"simple"===f?(this.simpleSexpr(e),this.opcode("pushProgram",c),this.opcode("pushProgram",d),this.opcode("emptyHash"),this.opcode("blockValue")):(this.ambiguousSexpr(e,c,d),this.opcode("pushProgram",c),this.opcode("pushProgram",d),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},hash:function(a){var b,c,d=a.pairs;this.opcode("pushHash");for(var e=0,f=d.length;f>e;e++)b=d[e],c=b[1],this.options.stringParams?(c.depth&&this.addDepth(c.depth),this.opcode("getContext",c.depth||0),this.opcode("pushStringParam",c.stringModeValue,c.type),"sexpr"===c.type&&this.sexpr(c)):this.accept(c),this.opcode("assignToHash",b[0]);this.opcode("popHash")},partial:function(a){var b=a.partialName;this.usePartial=!0,a.context?this.ID(a.context):this.opcode("push","depth0"),this.opcode("invokePartial",b.name),this.opcode("append")},content:function(a){this.opcode("appendContent",a.string)},mustache:function(a){this.sexpr(a.sexpr),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},ambiguousSexpr:function(a,b,c){var d=a.id,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.id;"DATA"===b.type?this.DATA(b):b.parts.length?this.ID(b):(this.addDepth(b.depth),this.opcode("getContext",b.depth),this.opcode("pushContext")),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.id.parts[0];if(this.options.knownHelpers[e])this.opcode("invokeKnownHelper",d.length,e);else{if(this.options.knownHelpersOnly)throw new f("You specified knownHelpersOnly, but used the unknown helper "+e,a);this.opcode("invokeHelper",d.length,e,a.isRoot)}},sexpr:function(a){var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ID:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0];b?this.opcode("lookupOnContext",a.parts[0]):this.opcode("pushContext");for(var c=1,d=a.parts.length;d>c;c++)this.opcode("lookup",a.parts[c])},DATA:function(a){if(this.options.data=!0,a.id.isScoped||a.id.depth)throw new f("Scoped data references are not supported: "+a.original,a);this.opcode("lookupData");for(var b=a.id.parts,c=0,d=b.length;d>c;c++)this.opcode("lookup",b[c])},STRING:function(a){this.opcode("pushString",a.string)},INTEGER:function(a){this.opcode("pushLiteral",a.integer)},BOOLEAN:function(a){this.opcode("pushLiteral",a.bool)},comment:function(){},opcode:function(a){this.opcodes.push({opcode:a,args:[].slice.call(arguments,1)})},declare:function(a,b){this.opcodes.push({opcode:"DECLARE",name:a,value:b})},addDepth:function(a){0!==a&&(this.depths[a]||(this.depths[a]=!0,this.depths.list.push(a)))},classifySexpr:function(a){var b=a.isHelper,c=a.eligibleHelper,d=this.options;if(c&&!b){var e=a.id.parts[0];d.knownHelpers[e]?b=!0:d.knownHelpersOnly&&(c=!1)}return b?"helper":c?"ambiguous":"simple"},pushParams:function(a){for(var b,c=a.length;c--;)b=a[c],this.options.stringParams?(b.depth&&this.addDepth(b.depth),this.opcode("getContext",b.depth||0),this.opcode("pushStringParam",b.stringModeValue,b.type),"sexpr"===b.type&&this.sexpr(b)):this[b.type](b)},setupFullMustacheParams:function(a,b,c){var d=a.params;return this.pushParams(d),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.hash(a.hash):this.opcode("emptyHash"),d}},b.precompile=d,b.compile=e}),define("handlebars/compiler/javascript-compiler",["../base","../exception","exports"],function(a,b,c){function d(a){this.value=a}function e(){}var f=a.COMPILER_REVISION,g=a.REVISION_CHANGES,h=a.log,i=b["default"];e.prototype={nameLookup:function(a,b){var c,d;return 0===a.indexOf("depth")&&(c=!0),d=/^[0-9]+$/.test(b)?a+"["+b+"]":e.isValidJavaScriptVariableName(b)?a+"."+b:a+"['"+b+"']",c?"("+a+" && "+d+")":d},compilerInfo:function(){var a=f,b=g[a];return"this.compilerInfo = ["+a+",'"+b+"'];\n" -},appendToBuffer:function(a){return this.environment.isSimple?"return "+a+";":{appendToBuffer:!0,content:a,toString:function(){return"buffer += "+a+";"}}},initializeBuffer:function(){return this.quotedString("")},namespace:"Handlebars",compile:function(a,b,c,d){this.environment=a,this.options=b||{},h("debug",this.environment.disassemble()+"\n\n"),this.name=this.environment.name,this.isChild=!!c,this.context=c||{programs:[],environments:[],aliases:{}},this.preamble(),this.stackSlot=0,this.stackVars=[],this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.compileChildren(a,b);var e,f=a.opcodes;this.i=0;for(var g=f.length;this.ie;e++)d.push("depth"+this.environment.depths.list[e]);var g=this.mergeSource();if(this.isChild||(g=this.compilerInfo()+g),a)return d.push(g),Function.apply(this,d);var i="function "+(this.name||"")+"("+d.join(",")+") {\n "+g+"}";return h("debug",i+"\n\n"),i},mergeSource:function(){for(var a,b="",c=0,d=this.source.length;d>c;c++){var e=this.source[c];e.appendToBuffer?a=a?a+"\n + "+e.content:e.content:(a&&(b+="buffer += "+a+";\n ",a=void 0),b+=e+"\n ")}return b},blockValue:function(){this.context.aliases.blockHelperMissing="helpers.blockHelperMissing";var a=["depth0"];this.setupParams(0,a),this.replaceStack(function(b){return a.splice(1,0,b),"blockHelperMissing.call("+a.join(", ")+")"})},ambiguousBlockValue:function(){this.context.aliases.blockHelperMissing="helpers.blockHelperMissing";var a=["depth0"];this.setupParams(0,a);var b=this.topStack();a.splice(1,0,b),this.pushSource("if (!"+this.lastHelper+") { "+b+" = blockHelperMissing.call("+a.join(", ")+"); }")},appendContent:function(a){this.pendingContent&&(a=this.pendingContent+a),this.stripNext&&(a=a.replace(/^\s+/,"")),this.pendingContent=a},strip:function(){this.pendingContent&&(this.pendingContent=this.pendingContent.replace(/\s+$/,"")),this.stripNext="strip"},append:function(){this.flushInline();var a=this.popStack();this.pushSource("if("+a+" || "+a+" === 0) { "+this.appendToBuffer(a)+" }"),this.environment.isSimple&&this.pushSource("else { "+this.appendToBuffer("''")+" }")},appendEscaped:function(){this.context.aliases.escapeExpression="this.escapeExpression",this.pushSource(this.appendToBuffer("escapeExpression("+this.popStack()+")"))},getContext:function(a){this.lastContext!==a&&(this.lastContext=a)},lookupOnContext:function(a){this.push(this.nameLookup("depth"+this.lastContext,a,"context"))},pushContext:function(){this.pushStackLiteral("depth"+this.lastContext)},resolvePossibleLambda:function(){this.context.aliases.functionType='"function"',this.replaceStack(function(a){return"typeof "+a+" === functionType ? "+a+".apply(depth0) : "+a})},lookup:function(a){this.replaceStack(function(b){return b+" == null || "+b+" === false ? "+b+" : "+this.nameLookup(b,a,"context")})},lookupData:function(){this.pushStackLiteral("data")},pushStringParam:function(a,b){this.pushStackLiteral("depth"+this.lastContext),this.pushString(b),"sexpr"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(){this.pushStackLiteral("{}"),this.options.stringParams&&(this.push("{}"),this.push("{}"))},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.options.stringParams&&(this.push("{"+a.contexts.join(",")+"}"),this.push("{"+a.types.join(",")+"}")),this.push("{\n "+a.values.join(",\n ")+"\n }")},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},push:function(a){return this.inlineStack.push(a),a},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},invokeHelper:function(a,b,c){this.context.aliases.helperMissing="helpers.helperMissing",this.useRegister("helper");var d=this.lastHelper=this.setupHelper(a,b,!0),e=this.nameLookup("depth"+this.lastContext,b,"context"),f="helper = "+d.name+" || "+e;d.paramsInit&&(f+=","+d.paramsInit),this.push("("+f+",helper ? helper.call("+d.callParams+") : helperMissing.call("+d.helperMissingParams+"))"),c||this.flushInline()},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(c.name+".call("+c.callParams+")")},invokeAmbiguous:function(a,b){this.context.aliases.functionType='"function"',this.useRegister("helper"),this.emptyHash();var c=this.setupHelper(0,a,b),d=this.lastHelper=this.nameLookup("helpers",a,"helper"),e=this.nameLookup("depth"+this.lastContext,a,"context"),f=this.nextStack();c.paramsInit&&this.pushSource(c.paramsInit),this.pushSource("if (helper = "+d+") { "+f+" = helper.call("+c.callParams+"); }"),this.pushSource("else { helper = "+e+"; "+f+" = typeof helper === functionType ? helper.call("+c.callParams+") : helper; }")},invokePartial:function(a){var b=[this.nameLookup("partials",a,"partial"),"'"+a+"'",this.popStack(),"helpers","partials"];this.options.data&&b.push("data"),this.context.aliases.self="this",this.push("self.invokePartial("+b.join(", ")+")")},assignToHash:function(a){var b,c,d=this.popStack();this.options.stringParams&&(c=this.popStack(),b=this.popStack());var e=this.hash;b&&e.contexts.push("'"+a+"': "+b),c&&e.types.push("'"+a+"': "+c),e.values.push("'"+a+"': ("+d+")")},compiler:e,compileChildren:function(a,b){for(var c,d,e=a.children,f=0,g=e.length;g>f;f++){c=e[f],d=new this.compiler;var h=this.matchExistingProgram(c);null==h?(this.context.programs.push(""),h=this.context.programs.length,c.index=h,c.name="program"+h,this.context.programs[h]=d.compile(c,b,this.context),this.context.environments[h]=c):(c.index=h,c.name="program"+h)}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;c>b;b++){var d=this.context.environments[b];if(d&&d.equals(a))return b}},programExpression:function(a){if(this.context.aliases.self="this",null==a)return"self.noop";for(var b,c=this.environment.children[a],d=c.depths.list,e=[c.index,c.name,"data"],f=0,g=d.length;g>f;f++)b=d[f],1===b?e.push("depth0"):e.push("depth"+(b-1));return(0===d.length?"self.program(":"self.programWithDepth(")+e.join(", ")+")"},register:function(a,b){this.useRegister(a),this.pushSource(a+" = "+b+";")},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},pushStackLiteral:function(a){return this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.quotedString(this.pendingContent))),this.pendingContent=void 0),a&&this.source.push(a)},pushStack:function(a){this.flushInline();var b=this.incrStack();return a&&this.pushSource(b+" = "+a+";"),this.compileStack.push(b),b},replaceStack:function(a){var b,c,e,f="",g=this.isInline();if(g){var h=this.popStack(!0);if(h instanceof d)b=h.value,e=!0;else{c=!this.stackSlot;var i=c?this.incrStack():this.topStackName();f="("+this.push(i)+" = "+h+"),",b=this.topStack()}}else b=this.topStack();var j=a.call(this,b);return g?(e||this.popStack(),c&&this.stackSlot--,this.push("("+f+j+")")):(/^stack/.test(b)||(b=this.nextStack()),this.pushSource(b+" = ("+f+j+");")),b},nextStack:function(){return this.pushStack()},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;if(a.length){this.inlineStack=[];for(var b=0,c=a.length;c>b;b++){var e=a[b];e instanceof d?this.compileStack.push(e):this.pushStack(e)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new i("Invalid stack pop");this.stackSlot--}return c},topStack:function(a){var b=this.isInline()?this.inlineStack:this.compileStack,c=b[b.length-1];return!a&&c instanceof d?c.value:c},quotedString:function(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},setupHelper:function(a,b,c){var d=[],e=this.setupParams(a,d,c),f=this.nameLookup("helpers",b,"helper");return{params:d,paramsInit:e,name:f,callParams:["depth0"].concat(d).join(", "),helperMissingParams:c&&["depth0",this.quotedString(b)].concat(d).join(", ")}},setupOptions:function(a,b){var c,d,e,f=[],g=[],h=[];f.push("hash:"+this.popStack()),this.options.stringParams&&(f.push("hashTypes:"+this.popStack()),f.push("hashContexts:"+this.popStack())),d=this.popStack(),e=this.popStack(),(e||d)&&(e||(this.context.aliases.self="this",e="self.noop"),d||(this.context.aliases.self="this",d="self.noop"),f.push("inverse:"+d),f.push("fn:"+e));for(var i=0;a>i;i++)c=this.popStack(),b.push(c),this.options.stringParams&&(h.push(this.popStack()),g.push(this.popStack()));return this.options.stringParams&&(f.push("contexts:["+g.join(",")+"]"),f.push("types:["+h.join(",")+"]")),this.options.data&&f.push("data:data"),f},setupParams:function(a,b,c){var d="{"+this.setupOptions(a,b).join(",")+"}";return c?(this.useRegister("options"),b.push("options"),"options="+d):(b.push(d),"")}};for(var j="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield".split(" "),k=e.RESERVED_WORDS={},l=0,m=j.length;m>l;l++)k[j[l]]=!0;e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)?!0:!1},c["default"]=e}),define("handlebars",["./handlebars.runtime","./handlebars/compiler/ast","./handlebars/compiler/base","./handlebars/compiler/compiler","./handlebars/compiler/javascript-compiler","exports"],function(a,b,c,d,e,f){var g=a["default"],h=b["default"],i=c.parser,j=c.parse,k=d.Compiler,l=d.compile,m=d.precompile,n=e["default"],o=g.create,p=function(){var a=o();return a.compile=function(b,c){return l(b,c,a)},a.precompile=function(b,c){return m(b,c,a)},a.AST=h,a.Compiler=k,a.JavaScriptCompiler=n,a.Parser=i,a.parse=j,a};g=p(),g.create=p,f["default"]=g}); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.js deleted file mode 100644 index bec7085c5..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.js +++ /dev/null @@ -1,2746 +0,0 @@ -/*! - - handlebars v1.3.0 - -Copyright (C) 2011 by Yehuda Katz - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -@license -*/ -/* exported Handlebars */ -var Handlebars = (function() { -// handlebars/safe-string.js -var __module4__ = (function() { - "use strict"; - var __exports__; - // Build out our basic SafeString type - function SafeString(string) { - this.string = string; - } - - SafeString.prototype.toString = function() { - return "" + this.string; - }; - - __exports__ = SafeString; - return __exports__; -})(); - -// handlebars/utils.js -var __module3__ = (function(__dependency1__) { - "use strict"; - var __exports__ = {}; - /*jshint -W004 */ - var SafeString = __dependency1__; - - var escape = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "`": "`" - }; - - var badChars = /[&<>"'`]/g; - var possible = /[&<>"'`]/; - - function escapeChar(chr) { - return escape[chr] || "&"; - } - - function extend(obj, value) { - for(var key in value) { - if(Object.prototype.hasOwnProperty.call(value, key)) { - obj[key] = value[key]; - } - } - } - - __exports__.extend = extend;var toString = Object.prototype.toString; - __exports__.toString = toString; - // Sourced from lodash - // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt - var isFunction = function(value) { - return typeof value === 'function'; - }; - // fallback for older versions of Chrome and Safari - if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; - } - var isFunction; - __exports__.isFunction = isFunction; - var isArray = Array.isArray || function(value) { - return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false; - }; - __exports__.isArray = isArray; - - function escapeExpression(string) { - // don't escape SafeStrings, since they're already safe - if (string instanceof SafeString) { - return string.toString(); - } else if (!string && string !== 0) { - return ""; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = "" + string; - - if(!possible.test(string)) { return string; } - return string.replace(badChars, escapeChar); - } - - __exports__.escapeExpression = escapeExpression;function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } - } - - __exports__.isEmpty = isEmpty; - return __exports__; -})(__module4__); - -// handlebars/exception.js -var __module5__ = (function() { - "use strict"; - var __exports__; - - var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; - - function Exception(message, node) { - var line; - if (node && node.firstLine) { - line = node.firstLine; - - message += ' - ' + line + ':' + node.firstColumn; - } - - var tmp = Error.prototype.constructor.call(this, message); - - // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. - for (var idx = 0; idx < errorProps.length; idx++) { - this[errorProps[idx]] = tmp[errorProps[idx]]; - } - - if (line) { - this.lineNumber = line; - this.column = node.firstColumn; - } - } - - Exception.prototype = new Error(); - - __exports__ = Exception; - return __exports__; -})(); - -// handlebars/base.js -var __module2__ = (function(__dependency1__, __dependency2__) { - "use strict"; - var __exports__ = {}; - var Utils = __dependency1__; - var Exception = __dependency2__; - - var VERSION = "1.3.0"; - __exports__.VERSION = VERSION;var COMPILER_REVISION = 4; - __exports__.COMPILER_REVISION = COMPILER_REVISION; - var REVISION_CHANGES = { - 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '== 1.0.0-rc.3', - 3: '== 1.0.0-rc.4', - 4: '>= 1.0.0' - }; - __exports__.REVISION_CHANGES = REVISION_CHANGES; - var isArray = Utils.isArray, - isFunction = Utils.isFunction, - toString = Utils.toString, - objectType = '[object Object]'; - - function HandlebarsEnvironment(helpers, partials) { - this.helpers = helpers || {}; - this.partials = partials || {}; - - registerDefaultHelpers(this); - } - - __exports__.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = { - constructor: HandlebarsEnvironment, - - logger: logger, - log: log, - - registerHelper: function(name, fn, inverse) { - if (toString.call(name) === objectType) { - if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); } - Utils.extend(this.helpers, name); - } else { - if (inverse) { fn.not = inverse; } - this.helpers[name] = fn; - } - }, - - registerPartial: function(name, str) { - if (toString.call(name) === objectType) { - Utils.extend(this.partials, name); - } else { - this.partials[name] = str; - } - } - }; - - function registerDefaultHelpers(instance) { - instance.registerHelper('helperMissing', function(arg) { - if(arguments.length === 2) { - return undefined; - } else { - throw new Exception("Missing helper: '" + arg + "'"); - } - }); - - instance.registerHelper('blockHelperMissing', function(context, options) { - var inverse = options.inverse || function() {}, fn = options.fn; - - if (isFunction(context)) { context = context.call(this); } - - if(context === true) { - return fn(this); - } else if(context === false || context == null) { - return inverse(this); - } else if (isArray(context)) { - if(context.length > 0) { - return instance.helpers.each(context, options); - } else { - return inverse(this); - } - } else { - return fn(context); - } - }); - - instance.registerHelper('each', function(context, options) { - var fn = options.fn, inverse = options.inverse; - var i = 0, ret = "", data; - - if (isFunction(context)) { context = context.call(this); } - - if (options.data) { - data = createFrame(options.data); - } - - if(context && typeof context === 'object') { - if (isArray(context)) { - for(var j = context.length; i 0) { - throw new Exception("Invalid path: " + original, this); - } else if (part === "..") { - depth++; - } else { - this.isScoped = true; - } - } else { - dig.push(part); - } - } - - this.original = original; - this.parts = dig; - this.string = dig.join('.'); - this.depth = depth; - - // an ID is simple if it only has one part, and that part is not - // `..` or `this`. - this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; - - this.stringModeValue = this.string; - }, - - PartialNameNode: function(name, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "PARTIAL_NAME"; - this.name = name.original; - }, - - DataNode: function(id, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "DATA"; - this.id = id; - }, - - StringNode: function(string, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "STRING"; - this.original = - this.string = - this.stringModeValue = string; - }, - - IntegerNode: function(integer, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "INTEGER"; - this.original = - this.integer = integer; - this.stringModeValue = Number(integer); - }, - - BooleanNode: function(bool, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "BOOLEAN"; - this.bool = bool; - this.stringModeValue = bool === "true"; - }, - - CommentNode: function(comment, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "comment"; - this.comment = comment; - } - }; - - // Must be exported as an object rather than the root of the module as the jison lexer - // most modify the object to operate properly. - __exports__ = AST; - return __exports__; -})(__module5__); - -// handlebars/compiler/parser.js -var __module9__ = (function() { - "use strict"; - var __exports__; - /* jshint ignore:start */ - /* Jison generated parser */ - var handlebars = (function(){ - var parser = {trace: function trace() { }, - yy: {}, - symbols_: {"error":2,"root":3,"statements":4,"EOF":5,"program":6,"simpleInverse":7,"statement":8,"openInverse":9,"closeBlock":10,"openBlock":11,"mustache":12,"partial":13,"CONTENT":14,"COMMENT":15,"OPEN_BLOCK":16,"sexpr":17,"CLOSE":18,"OPEN_INVERSE":19,"OPEN_ENDBLOCK":20,"path":21,"OPEN":22,"OPEN_UNESCAPED":23,"CLOSE_UNESCAPED":24,"OPEN_PARTIAL":25,"partialName":26,"partial_option0":27,"sexpr_repetition0":28,"sexpr_option0":29,"dataName":30,"param":31,"STRING":32,"INTEGER":33,"BOOLEAN":34,"OPEN_SEXPR":35,"CLOSE_SEXPR":36,"hash":37,"hash_repetition_plus0":38,"hashSegment":39,"ID":40,"EQUALS":41,"DATA":42,"pathSegments":43,"SEP":44,"$accept":0,"$end":1}, - terminals_: {2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"CLOSE_UNESCAPED",25:"OPEN_PARTIAL",32:"STRING",33:"INTEGER",34:"BOOLEAN",35:"OPEN_SEXPR",36:"CLOSE_SEXPR",40:"ID",41:"EQUALS",42:"DATA",44:"SEP"}, - productions_: [0,[3,2],[3,1],[6,2],[6,3],[6,2],[6,1],[6,1],[6,0],[4,1],[4,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,4],[7,2],[17,3],[17,1],[31,1],[31,1],[31,1],[31,1],[31,1],[31,3],[37,1],[39,3],[26,1],[26,1],[26,1],[30,2],[21,1],[43,3],[43,1],[27,0],[27,1],[28,0],[28,2],[29,0],[29,1],[38,1],[38,2]], - performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) { - - var $0 = $$.length - 1; - switch (yystate) { - case 1: return new yy.ProgramNode($$[$0-1], this._$); - break; - case 2: return new yy.ProgramNode([], this._$); - break; - case 3:this.$ = new yy.ProgramNode([], $$[$0-1], $$[$0], this._$); - break; - case 4:this.$ = new yy.ProgramNode($$[$0-2], $$[$0-1], $$[$0], this._$); - break; - case 5:this.$ = new yy.ProgramNode($$[$0-1], $$[$0], [], this._$); - break; - case 6:this.$ = new yy.ProgramNode($$[$0], this._$); - break; - case 7:this.$ = new yy.ProgramNode([], this._$); - break; - case 8:this.$ = new yy.ProgramNode([], this._$); - break; - case 9:this.$ = [$$[$0]]; - break; - case 10: $$[$0-1].push($$[$0]); this.$ = $$[$0-1]; - break; - case 11:this.$ = new yy.BlockNode($$[$0-2], $$[$0-1].inverse, $$[$0-1], $$[$0], this._$); - break; - case 12:this.$ = new yy.BlockNode($$[$0-2], $$[$0-1], $$[$0-1].inverse, $$[$0], this._$); - break; - case 13:this.$ = $$[$0]; - break; - case 14:this.$ = $$[$0]; - break; - case 15:this.$ = new yy.ContentNode($$[$0], this._$); - break; - case 16:this.$ = new yy.CommentNode($$[$0], this._$); - break; - case 17:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); - break; - case 18:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); - break; - case 19:this.$ = {path: $$[$0-1], strip: stripFlags($$[$0-2], $$[$0])}; - break; - case 20:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); - break; - case 21:this.$ = new yy.MustacheNode($$[$0-1], null, $$[$0-2], stripFlags($$[$0-2], $$[$0]), this._$); - break; - case 22:this.$ = new yy.PartialNode($$[$0-2], $$[$0-1], stripFlags($$[$0-3], $$[$0]), this._$); - break; - case 23:this.$ = stripFlags($$[$0-1], $$[$0]); - break; - case 24:this.$ = new yy.SexprNode([$$[$0-2]].concat($$[$0-1]), $$[$0], this._$); - break; - case 25:this.$ = new yy.SexprNode([$$[$0]], null, this._$); - break; - case 26:this.$ = $$[$0]; - break; - case 27:this.$ = new yy.StringNode($$[$0], this._$); - break; - case 28:this.$ = new yy.IntegerNode($$[$0], this._$); - break; - case 29:this.$ = new yy.BooleanNode($$[$0], this._$); - break; - case 30:this.$ = $$[$0]; - break; - case 31:$$[$0-1].isHelper = true; this.$ = $$[$0-1]; - break; - case 32:this.$ = new yy.HashNode($$[$0], this._$); - break; - case 33:this.$ = [$$[$0-2], $$[$0]]; - break; - case 34:this.$ = new yy.PartialNameNode($$[$0], this._$); - break; - case 35:this.$ = new yy.PartialNameNode(new yy.StringNode($$[$0], this._$), this._$); - break; - case 36:this.$ = new yy.PartialNameNode(new yy.IntegerNode($$[$0], this._$)); - break; - case 37:this.$ = new yy.DataNode($$[$0], this._$); - break; - case 38:this.$ = new yy.IdNode($$[$0], this._$); - break; - case 39: $$[$0-2].push({part: $$[$0], separator: $$[$0-1]}); this.$ = $$[$0-2]; - break; - case 40:this.$ = [{part: $$[$0]}]; - break; - case 43:this.$ = []; - break; - case 44:$$[$0-1].push($$[$0]); - break; - case 47:this.$ = [$$[$0]]; - break; - case 48:$$[$0-1].push($$[$0]); - break; - } - }, - table: [{3:1,4:2,5:[1,3],8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[3]},{5:[1,16],8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[2,2]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],25:[2,9]},{4:20,6:18,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{4:20,6:22,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{5:[2,13],14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],25:[2,13]},{5:[2,14],14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],25:[2,14]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],25:[2,15]},{5:[2,16],14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],25:[2,16]},{17:23,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:29,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:30,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:31,21:24,30:25,40:[1,28],42:[1,27],43:26},{21:33,26:32,32:[1,34],33:[1,35],40:[1,28],43:26},{1:[2,1]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],25:[2,10]},{10:36,20:[1,37]},{4:38,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,7],22:[1,13],23:[1,14],25:[1,15]},{7:39,8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,6],22:[1,13],23:[1,14],25:[1,15]},{17:23,18:[1,40],21:24,30:25,40:[1,28],42:[1,27],43:26},{10:41,20:[1,37]},{18:[1,42]},{18:[2,43],24:[2,43],28:43,32:[2,43],33:[2,43],34:[2,43],35:[2,43],36:[2,43],40:[2,43],42:[2,43]},{18:[2,25],24:[2,25],36:[2,25]},{18:[2,38],24:[2,38],32:[2,38],33:[2,38],34:[2,38],35:[2,38],36:[2,38],40:[2,38],42:[2,38],44:[1,44]},{21:45,40:[1,28],43:26},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],42:[2,40],44:[2,40]},{18:[1,46]},{18:[1,47]},{24:[1,48]},{18:[2,41],21:50,27:49,40:[1,28],43:26},{18:[2,34],40:[2,34]},{18:[2,35],40:[2,35]},{18:[2,36],40:[2,36]},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],25:[2,11]},{21:51,40:[1,28],43:26},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,3],22:[1,13],23:[1,14],25:[1,15]},{4:52,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,5],22:[1,13],23:[1,14],25:[1,15]},{14:[2,23],15:[2,23],16:[2,23],19:[2,23],20:[2,23],22:[2,23],23:[2,23],25:[2,23]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],25:[2,12]},{14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],25:[2,18]},{18:[2,45],21:56,24:[2,45],29:53,30:60,31:54,32:[1,57],33:[1,58],34:[1,59],35:[1,61],36:[2,45],37:55,38:62,39:63,40:[1,64],42:[1,27],43:26},{40:[1,65]},{18:[2,37],24:[2,37],32:[2,37],33:[2,37],34:[2,37],35:[2,37],36:[2,37],40:[2,37],42:[2,37]},{14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],25:[2,17]},{5:[2,20],14:[2,20],15:[2,20],16:[2,20],19:[2,20],20:[2,20],22:[2,20],23:[2,20],25:[2,20]},{5:[2,21],14:[2,21],15:[2,21],16:[2,21],19:[2,21],20:[2,21],22:[2,21],23:[2,21],25:[2,21]},{18:[1,66]},{18:[2,42]},{18:[1,67]},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],25:[1,15]},{18:[2,24],24:[2,24],36:[2,24]},{18:[2,44],24:[2,44],32:[2,44],33:[2,44],34:[2,44],35:[2,44],36:[2,44],40:[2,44],42:[2,44]},{18:[2,46],24:[2,46],36:[2,46]},{18:[2,26],24:[2,26],32:[2,26],33:[2,26],34:[2,26],35:[2,26],36:[2,26],40:[2,26],42:[2,26]},{18:[2,27],24:[2,27],32:[2,27],33:[2,27],34:[2,27],35:[2,27],36:[2,27],40:[2,27],42:[2,27]},{18:[2,28],24:[2,28],32:[2,28],33:[2,28],34:[2,28],35:[2,28],36:[2,28],40:[2,28],42:[2,28]},{18:[2,29],24:[2,29],32:[2,29],33:[2,29],34:[2,29],35:[2,29],36:[2,29],40:[2,29],42:[2,29]},{18:[2,30],24:[2,30],32:[2,30],33:[2,30],34:[2,30],35:[2,30],36:[2,30],40:[2,30],42:[2,30]},{17:68,21:24,30:25,40:[1,28],42:[1,27],43:26},{18:[2,32],24:[2,32],36:[2,32],39:69,40:[1,70]},{18:[2,47],24:[2,47],36:[2,47],40:[2,47]},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],41:[1,71],42:[2,40],44:[2,40]},{18:[2,39],24:[2,39],32:[2,39],33:[2,39],34:[2,39],35:[2,39],36:[2,39],40:[2,39],42:[2,39],44:[2,39]},{5:[2,22],14:[2,22],15:[2,22],16:[2,22],19:[2,22],20:[2,22],22:[2,22],23:[2,22],25:[2,22]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],25:[2,19]},{36:[1,72]},{18:[2,48],24:[2,48],36:[2,48],40:[2,48]},{41:[1,71]},{21:56,30:60,31:73,32:[1,57],33:[1,58],34:[1,59],35:[1,61],40:[1,28],42:[1,27],43:26},{18:[2,31],24:[2,31],32:[2,31],33:[2,31],34:[2,31],35:[2,31],36:[2,31],40:[2,31],42:[2,31]},{18:[2,33],24:[2,33],36:[2,33],40:[2,33]}], - defaultActions: {3:[2,2],16:[2,1],50:[2,42]}, - parseError: function parseError(str, hash) { - throw new Error(str); - }, - parse: function parse(input) { - var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; - this.lexer.setInput(input); - this.lexer.yy = this.yy; - this.yy.lexer = this.lexer; - this.yy.parser = this; - if (typeof this.lexer.yylloc == "undefined") - this.lexer.yylloc = {}; - var yyloc = this.lexer.yylloc; - lstack.push(yyloc); - var ranges = this.lexer.options && this.lexer.options.ranges; - if (typeof this.yy.parseError === "function") - this.parseError = this.yy.parseError; - function popStack(n) { - stack.length = stack.length - 2 * n; - vstack.length = vstack.length - n; - lstack.length = lstack.length - n; - } - function lex() { - var token; - token = self.lexer.lex() || 1; - if (typeof token !== "number") { - token = self.symbols_[token] || token; - } - return token; - } - var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; - while (true) { - state = stack[stack.length - 1]; - if (this.defaultActions[state]) { - action = this.defaultActions[state]; - } else { - if (symbol === null || typeof symbol == "undefined") { - symbol = lex(); - } - action = table[state] && table[state][symbol]; - } - if (typeof action === "undefined" || !action.length || !action[0]) { - var errStr = ""; - if (!recovering) { - expected = []; - for (p in table[state]) - if (this.terminals_[p] && p > 2) { - expected.push("'" + this.terminals_[p] + "'"); - } - if (this.lexer.showPosition) { - errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; - } else { - errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); - } - this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); - } - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) - recovering--; - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; - if (ranges) { - yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; - } - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - if (typeof r !== "undefined") { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } - } - return true; - } - }; - - - function stripFlags(open, close) { - return { - left: open.charAt(2) === '~', - right: close.charAt(0) === '~' || close.charAt(1) === '~' - }; - } - - /* Jison generated lexer */ - var lexer = (function(){ - var lexer = ({EOF:1, - parseError:function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, - setInput:function (input) { - this._input = input; - this._more = this._less = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; - if (this.options.ranges) this.yylloc.range = [0,0]; - this.offset = 0; - return this; - }, - input:function () { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) this.yylloc.range[1]++; - - this._input = this._input.slice(1); - return ch; - }, - unput:function (ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); - - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length-len-1); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length-1); - this.matched = this.matched.substr(0, this.matched.length-1); - - if (lines.length-1) this.yylineno -= lines.length-1; - var r = this.yylloc.range; - - this.yylloc = {first_line: this.yylloc.first_line, - last_line: this.yylineno+1, - first_column: this.yylloc.first_column, - last_column: lines ? - (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: - this.yylloc.first_column - len - }; - - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - return this; - }, - more:function () { - this._more = true; - return this; - }, - less:function (n) { - this.unput(this.match.slice(n)); - }, - pastInput:function () { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); - }, - upcomingInput:function () { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20-next.length); - } - return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); - }, - showPosition:function () { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c+"^"; - }, - next:function () { - if (this.done) { - return this.EOF; - } - if (!this._input) this.done = true; - - var token, - match, - tempMatch, - index, - col, - lines; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i=0;i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (!this.options.flex) break; - } - } - if (match) { - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) this.yylineno += lines.length; - this.yylloc = {first_line: this.yylloc.last_line, - last_line: this.yylineno+1, - first_column: this.yylloc.last_column, - last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); - if (this.done && this._input) this.done = false; - if (token) return token; - else return; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), - {text: "", token: null, line: this.yylineno}); - } - }, - lex:function lex() { - var r = this.next(); - if (typeof r !== 'undefined') { - return r; - } else { - return this.lex(); - } - }, - begin:function begin(condition) { - this.conditionStack.push(condition); - }, - popState:function popState() { - return this.conditionStack.pop(); - }, - _currentRules:function _currentRules() { - return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; - }, - topState:function () { - return this.conditionStack[this.conditionStack.length-2]; - }, - pushState:function begin(condition) { - this.begin(condition); - }}); - lexer.options = {}; - lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { - - - function strip(start, end) { - return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng-end); - } - - - var YYSTATE=YY_START - switch($avoiding_name_collisions) { - case 0: - if(yy_.yytext.slice(-2) === "\\\\") { - strip(0,1); - this.begin("mu"); - } else if(yy_.yytext.slice(-1) === "\\") { - strip(0,1); - this.begin("emu"); - } else { - this.begin("mu"); - } - if(yy_.yytext) return 14; - - break; - case 1:return 14; - break; - case 2: - this.popState(); - return 14; - - break; - case 3:strip(0,4); this.popState(); return 15; - break; - case 4:return 35; - break; - case 5:return 36; - break; - case 6:return 25; - break; - case 7:return 16; - break; - case 8:return 20; - break; - case 9:return 19; - break; - case 10:return 19; - break; - case 11:return 23; - break; - case 12:return 22; - break; - case 13:this.popState(); this.begin('com'); - break; - case 14:strip(3,5); this.popState(); return 15; - break; - case 15:return 22; - break; - case 16:return 41; - break; - case 17:return 40; - break; - case 18:return 40; - break; - case 19:return 44; - break; - case 20:// ignore whitespace - break; - case 21:this.popState(); return 24; - break; - case 22:this.popState(); return 18; - break; - case 23:yy_.yytext = strip(1,2).replace(/\\"/g,'"'); return 32; - break; - case 24:yy_.yytext = strip(1,2).replace(/\\'/g,"'"); return 32; - break; - case 25:return 42; - break; - case 26:return 34; - break; - case 27:return 34; - break; - case 28:return 33; - break; - case 29:return 40; - break; - case 30:yy_.yytext = strip(1,2); return 40; - break; - case 31:return 'INVALID'; - break; - case 32:return 5; - break; - } - }; - lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; - lexer.conditions = {"mu":{"rules":[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"com":{"rules":[3],"inclusive":false},"INITIAL":{"rules":[0,1,32],"inclusive":true}}; - return lexer;})() - parser.lexer = lexer; - function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; - return new Parser; - })();__exports__ = handlebars; - /* jshint ignore:end */ - return __exports__; -})(); - -// handlebars/compiler/base.js -var __module8__ = (function(__dependency1__, __dependency2__) { - "use strict"; - var __exports__ = {}; - var parser = __dependency1__; - var AST = __dependency2__; - - __exports__.parser = parser; - - function parse(input) { - // Just return if an already-compile AST was passed in. - if(input.constructor === AST.ProgramNode) { return input; } - - parser.yy = AST; - return parser.parse(input); - } - - __exports__.parse = parse; - return __exports__; -})(__module9__, __module7__); - -// handlebars/compiler/compiler.js -var __module10__ = (function(__dependency1__) { - "use strict"; - var __exports__ = {}; - var Exception = __dependency1__; - - function Compiler() {} - - __exports__.Compiler = Compiler;// the foundHelper register will disambiguate helper lookup from finding a - // function in a context. This is necessary for mustache compatibility, which - // requires that context functions in blocks are evaluated by blockHelperMissing, - // and then proceed as if the resulting value was provided to blockHelperMissing. - - Compiler.prototype = { - compiler: Compiler, - - disassemble: function() { - var opcodes = this.opcodes, opcode, out = [], params, param; - - for (var i=0, l=opcodes.length; i 0) { - this.source[1] = this.source[1] + ", " + locals.join(", "); - } - - // Generate minimizer alias mappings - if (!this.isChild) { - for (var alias in this.context.aliases) { - if (this.context.aliases.hasOwnProperty(alias)) { - this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; - } - } - } - - if (this.source[1]) { - this.source[1] = "var " + this.source[1].substring(2) + ";"; - } - - // Merge children - if (!this.isChild) { - this.source[1] += '\n' + this.context.programs.join('\n') + '\n'; - } - - if (!this.environment.isSimple) { - this.pushSource("return buffer;"); - } - - var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"]; - - for(var i=0, l=this.environment.depths.list.length; i this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } - return this.topStackName(); - }, - topStackName: function() { - return "stack" + this.stackSlot; - }, - flushInline: function() { - var inlineStack = this.inlineStack; - if (inlineStack.length) { - this.inlineStack = []; - for (var i = 0, len = inlineStack.length; i < len; i++) { - var entry = inlineStack[i]; - if (entry instanceof Literal) { - this.compileStack.push(entry); - } else { - this.pushStack(entry); - } - } - } - }, - isInline: function() { - return this.inlineStack.length; - }, - - popStack: function(wrapped) { - var inline = this.isInline(), - item = (inline ? this.inlineStack : this.compileStack).pop(); - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - if (!inline) { - if (!this.stackSlot) { - throw new Exception('Invalid stack pop'); - } - this.stackSlot--; - } - return item; - } - }, - - topStack: function(wrapped) { - var stack = (this.isInline() ? this.inlineStack : this.compileStack), - item = stack[stack.length - 1]; - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - return item; - } - }, - - quotedString: function(str) { - return '"' + str - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 - .replace(/\u2029/g, '\\u2029') + '"'; - }, - - setupHelper: function(paramSize, name, missingParams) { - var params = [], - paramsInit = this.setupParams(paramSize, params, missingParams); - var foundHelper = this.nameLookup('helpers', name, 'helper'); - - return { - params: params, - paramsInit: paramsInit, - name: foundHelper, - callParams: ["depth0"].concat(params).join(", "), - helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ") - }; - }, - - setupOptions: function(paramSize, params) { - var options = [], contexts = [], types = [], param, inverse, program; - - options.push("hash:" + this.popStack()); - - if (this.options.stringParams) { - options.push("hashTypes:" + this.popStack()); - options.push("hashContexts:" + this.popStack()); - } - - inverse = this.popStack(); - program = this.popStack(); - - // Avoid setting fn and inverse if neither are set. This allows - // helpers to do a check for `if (options.fn)` - if (program || inverse) { - if (!program) { - this.context.aliases.self = "this"; - program = "self.noop"; - } - - if (!inverse) { - this.context.aliases.self = "this"; - inverse = "self.noop"; - } - - options.push("inverse:" + inverse); - options.push("fn:" + program); - } - - for(var i=0; i":">",'"':""","'":"'","`":"`"},i=/[&<>"'`]/g,j=/[&<>"'`]/;f.extend=c;var k=Object.prototype.toString;f.toString=k;var l=function(a){return"function"==typeof a};l(/x/)&&(l=function(a){return"function"==typeof a&&"[object Function]"===k.call(a)});var l;f.isFunction=l;var m=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===k.call(a):!1};return f.isArray=m,f.escapeExpression=d,f.isEmpty=e,f}(a),c=function(){"use strict";function a(a,b){var d;b&&b.firstLine&&(d=b.firstLine,a+=" - "+d+":"+b.firstColumn);for(var e=Error.prototype.constructor.call(this,a),f=0;f0?a.helpers.each(b,c):d(this):e(b)}),a.registerHelper("each",function(a,b){var c,d=b.fn,e=b.inverse,f=0,g="";if(m(a)&&(a=a.call(this)),b.data&&(c=q(b.data)),a&&"object"==typeof a)if(l(a))for(var h=a.length;h>f;f++)c&&(c.index=f,c.first=0===f,c.last=f===a.length-1),g+=d(a[f],{data:c});else for(var i in a)a.hasOwnProperty(i)&&(c&&(c.key=i,c.index=f,c.first=0===f),g+=d(a[i],{data:c}),f++);return 0===f&&(g=e(this)),g}),a.registerHelper("if",function(a,b){return m(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||g.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){return m(a)&&(a=a.call(this)),g.isEmpty(a)?void 0:b.fn(a)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)})}function e(a,b){p.log(a,b)}var f={},g=a,h=b,i="1.3.0";f.VERSION=i;var j=4;f.COMPILER_REVISION=j;var k={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"};f.REVISION_CHANGES=k;var l=g.isArray,m=g.isFunction,n=g.toString,o="[object Object]";f.HandlebarsEnvironment=c,c.prototype={constructor:c,logger:p,log:e,registerHelper:function(a,b,c){if(n.call(a)===o){if(c||b)throw new h("Arg not supported with multiple helpers");g.extend(this.helpers,a)}else c&&(b.not=c),this.helpers[a]=b},registerPartial:function(a,b){n.call(a)===o?g.extend(this.partials,a):this.partials[a]=b}};var p={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,log:function(a,b){if(p.level<=a){var c=p.methodMap[a];"undefined"!=typeof console&&console[c]&&console[c].call(console,b)}}};f.logger=p,f.log=e;var q=function(a){var b={};return g.extend(b,a),b};return f.createFrame=q,f}(b,c),e=function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=m;if(b!==c){if(c>b){var d=n[c],e=n[b];throw new l("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new l("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){if(!b)throw new l("No environment passed to template");var c=function(a,c,d,e,f,g){var h=b.VM.invokePartial.apply(this,arguments);if(null!=h)return h;if(b.compile){var i={helpers:e,partials:f,data:g};return f[c]=b.compile(a,{data:void 0!==g},b),f[c](d,i)}throw new l("The partial "+c+" could not be compiled when running in runtime-only mode")},d={escapeExpression:k.escapeExpression,invokePartial:c,programs:[],program:function(a,b,c){var d=this.programs[a];return c?d=g(a,b,c):d||(d=this.programs[a]=g(a,b)),d},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c={},k.extend(c,b),k.extend(c,a)),c},programWithDepth:b.VM.programWithDepth,noop:b.VM.noop,compilerInfo:null};return function(c,e){e=e||{};var f,g,h=e.partial?e:b;e.partial||(f=e.helpers,g=e.partials);var i=a.call(d,h,c,f,g,e.data);return e.partial||b.VM.checkRevision(d.compilerInfo),i}}function f(a,b,c){var d=Array.prototype.slice.call(arguments,3),e=function(a,e){return e=e||{},b.apply(this,[a,e.data||c].concat(d))};return e.program=a,e.depth=d.length,e}function g(a,b,c){var d=function(a,d){return d=d||{},b(a,d.data||c)};return d.program=a,d.depth=0,d}function h(a,b,c,d,e,f){var g={partial:!0,helpers:d,partials:e,data:f};if(void 0===a)throw new l("The partial "+b+" could not be found");return a instanceof Function?a(c,g):void 0}function i(){return""}var j={},k=a,l=b,m=c.COMPILER_REVISION,n=c.REVISION_CHANGES;return j.checkRevision=d,j.template=e,j.programWithDepth=f,j.program=g,j.invokePartial=h,j.noop=i,j}(b,c,d),f=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c,j=d,k=e,l=function(){var a=new g.HandlebarsEnvironment;return j.extend(a,g),a.SafeString=h,a.Exception=i,a.Utils=j,a.VM=k,a.template=function(b){return k.template(b,a)},a},m=l();return m.create=l,f=m}(d,a,c,b,e),g=function(a){"use strict";function b(a){a=a||{},this.firstLine=a.first_line,this.firstColumn=a.first_column,this.lastColumn=a.last_column,this.lastLine=a.last_line}var c,d=a,e={ProgramNode:function(a,c,d,f){var g,h;3===arguments.length?(f=d,d=null):2===arguments.length&&(f=c,c=null),b.call(this,f),this.type="program",this.statements=a,this.strip={},d?(h=d[0],h?(g={first_line:h.firstLine,last_line:h.lastLine,last_column:h.lastColumn,first_column:h.firstColumn},this.inverse=new e.ProgramNode(d,c,g)):this.inverse=new e.ProgramNode(d,c),this.strip.right=c.left):c&&(this.strip.left=c.right)},MustacheNode:function(a,c,d,f,g){if(b.call(this,g),this.type="mustache",this.strip=f,null!=d&&d.charAt){var h=d.charAt(3)||d.charAt(2);this.escaped="{"!==h&&"&"!==h}else this.escaped=!!d;this.sexpr=a instanceof e.SexprNode?a:new e.SexprNode(a,c),this.sexpr.isRoot=!0,this.id=this.sexpr.id,this.params=this.sexpr.params,this.hash=this.sexpr.hash,this.eligibleHelper=this.sexpr.eligibleHelper,this.isHelper=this.sexpr.isHelper},SexprNode:function(a,c,d){b.call(this,d),this.type="sexpr",this.hash=c;var e=this.id=a[0],f=this.params=a.slice(1),g=this.eligibleHelper=e.isSimple;this.isHelper=g&&(f.length||c)},PartialNode:function(a,c,d,e){b.call(this,e),this.type="partial",this.partialName=a,this.context=c,this.strip=d},BlockNode:function(a,c,e,f,g){if(b.call(this,g),a.sexpr.id.original!==f.path.original)throw new d(a.sexpr.id.original+" doesn't match "+f.path.original,this);this.type="block",this.mustache=a,this.program=c,this.inverse=e,this.strip={left:a.strip.left,right:f.strip.right},(c||e).strip.left=a.strip.right,(e||c).strip.right=f.strip.left,e&&!c&&(this.isInverse=!0)},ContentNode:function(a,c){b.call(this,c),this.type="content",this.string=a},HashNode:function(a,c){b.call(this,c),this.type="hash",this.pairs=a},IdNode:function(a,c){b.call(this,c),this.type="ID";for(var e="",f=[],g=0,h=0,i=a.length;i>h;h++){var j=a[h].part;if(e+=(a[h].separator||"")+j,".."===j||"."===j||"this"===j){if(f.length>0)throw new d("Invalid path: "+e,this);".."===j?g++:this.isScoped=!0}else f.push(j)}this.original=e,this.parts=f,this.string=f.join("."),this.depth=g,this.isSimple=1===a.length&&!this.isScoped&&0===g,this.stringModeValue=this.string},PartialNameNode:function(a,c){b.call(this,c),this.type="PARTIAL_NAME",this.name=a.original},DataNode:function(a,c){b.call(this,c),this.type="DATA",this.id=a},StringNode:function(a,c){b.call(this,c),this.type="STRING",this.original=this.string=this.stringModeValue=a},IntegerNode:function(a,c){b.call(this,c),this.type="INTEGER",this.original=this.integer=a,this.stringModeValue=Number(a)},BooleanNode:function(a,c){b.call(this,c),this.type="BOOLEAN",this.bool=a,this.stringModeValue="true"===a},CommentNode:function(a,c){b.call(this,c),this.type="comment",this.comment=a}};return c=e}(c),h=function(){"use strict";var a,b=function(){function a(a,b){return{left:"~"===a.charAt(2),right:"~"===b.charAt(0)||"~"===b.charAt(1)}}function b(){this.yy={}}var c={trace:function(){},yy:{},symbols_:{error:2,root:3,statements:4,EOF:5,program:6,simpleInverse:7,statement:8,openInverse:9,closeBlock:10,openBlock:11,mustache:12,partial:13,CONTENT:14,COMMENT:15,OPEN_BLOCK:16,sexpr:17,CLOSE:18,OPEN_INVERSE:19,OPEN_ENDBLOCK:20,path:21,OPEN:22,OPEN_UNESCAPED:23,CLOSE_UNESCAPED:24,OPEN_PARTIAL:25,partialName:26,partial_option0:27,sexpr_repetition0:28,sexpr_option0:29,dataName:30,param:31,STRING:32,INTEGER:33,BOOLEAN:34,OPEN_SEXPR:35,CLOSE_SEXPR:36,hash:37,hash_repetition_plus0:38,hashSegment:39,ID:40,EQUALS:41,DATA:42,pathSegments:43,SEP:44,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"CONTENT",15:"COMMENT",16:"OPEN_BLOCK",18:"CLOSE",19:"OPEN_INVERSE",20:"OPEN_ENDBLOCK",22:"OPEN",23:"OPEN_UNESCAPED",24:"CLOSE_UNESCAPED",25:"OPEN_PARTIAL",32:"STRING",33:"INTEGER",34:"BOOLEAN",35:"OPEN_SEXPR",36:"CLOSE_SEXPR",40:"ID",41:"EQUALS",42:"DATA",44:"SEP"},productions_:[0,[3,2],[3,1],[6,2],[6,3],[6,2],[6,1],[6,1],[6,0],[4,1],[4,2],[8,3],[8,3],[8,1],[8,1],[8,1],[8,1],[11,3],[9,3],[10,3],[12,3],[12,3],[13,4],[7,2],[17,3],[17,1],[31,1],[31,1],[31,1],[31,1],[31,1],[31,3],[37,1],[39,3],[26,1],[26,1],[26,1],[30,2],[21,1],[43,3],[43,1],[27,0],[27,1],[28,0],[28,2],[29,0],[29,1],[38,1],[38,2]],performAction:function(b,c,d,e,f,g){var h=g.length-1;switch(f){case 1:return new e.ProgramNode(g[h-1],this._$);case 2:return new e.ProgramNode([],this._$);case 3:this.$=new e.ProgramNode([],g[h-1],g[h],this._$);break;case 4:this.$=new e.ProgramNode(g[h-2],g[h-1],g[h],this._$);break;case 5:this.$=new e.ProgramNode(g[h-1],g[h],[],this._$);break;case 6:this.$=new e.ProgramNode(g[h],this._$);break;case 7:this.$=new e.ProgramNode([],this._$);break;case 8:this.$=new e.ProgramNode([],this._$);break;case 9:this.$=[g[h]];break;case 10:g[h-1].push(g[h]),this.$=g[h-1];break;case 11:this.$=new e.BlockNode(g[h-2],g[h-1].inverse,g[h-1],g[h],this._$);break;case 12:this.$=new e.BlockNode(g[h-2],g[h-1],g[h-1].inverse,g[h],this._$);break;case 13:this.$=g[h];break;case 14:this.$=g[h];break;case 15:this.$=new e.ContentNode(g[h],this._$);break;case 16:this.$=new e.CommentNode(g[h],this._$);break;case 17:this.$=new e.MustacheNode(g[h-1],null,g[h-2],a(g[h-2],g[h]),this._$);break;case 18:this.$=new e.MustacheNode(g[h-1],null,g[h-2],a(g[h-2],g[h]),this._$);break;case 19:this.$={path:g[h-1],strip:a(g[h-2],g[h])};break;case 20:this.$=new e.MustacheNode(g[h-1],null,g[h-2],a(g[h-2],g[h]),this._$);break;case 21:this.$=new e.MustacheNode(g[h-1],null,g[h-2],a(g[h-2],g[h]),this._$);break;case 22:this.$=new e.PartialNode(g[h-2],g[h-1],a(g[h-3],g[h]),this._$);break;case 23:this.$=a(g[h-1],g[h]);break;case 24:this.$=new e.SexprNode([g[h-2]].concat(g[h-1]),g[h],this._$);break;case 25:this.$=new e.SexprNode([g[h]],null,this._$);break;case 26:this.$=g[h];break;case 27:this.$=new e.StringNode(g[h],this._$);break;case 28:this.$=new e.IntegerNode(g[h],this._$);break;case 29:this.$=new e.BooleanNode(g[h],this._$);break;case 30:this.$=g[h];break;case 31:g[h-1].isHelper=!0,this.$=g[h-1];break;case 32:this.$=new e.HashNode(g[h],this._$);break;case 33:this.$=[g[h-2],g[h]];break;case 34:this.$=new e.PartialNameNode(g[h],this._$);break;case 35:this.$=new e.PartialNameNode(new e.StringNode(g[h],this._$),this._$);break;case 36:this.$=new e.PartialNameNode(new e.IntegerNode(g[h],this._$));break;case 37:this.$=new e.DataNode(g[h],this._$);break;case 38:this.$=new e.IdNode(g[h],this._$);break;case 39:g[h-2].push({part:g[h],separator:g[h-1]}),this.$=g[h-2];break;case 40:this.$=[{part:g[h]}];break;case 43:this.$=[];break;case 44:g[h-1].push(g[h]);break;case 47:this.$=[g[h]];break;case 48:g[h-1].push(g[h])}},table:[{3:1,4:2,5:[1,3],8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[3]},{5:[1,16],8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],22:[1,13],23:[1,14],25:[1,15]},{1:[2,2]},{5:[2,9],14:[2,9],15:[2,9],16:[2,9],19:[2,9],20:[2,9],22:[2,9],23:[2,9],25:[2,9]},{4:20,6:18,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{4:20,6:22,7:19,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,8],22:[1,13],23:[1,14],25:[1,15]},{5:[2,13],14:[2,13],15:[2,13],16:[2,13],19:[2,13],20:[2,13],22:[2,13],23:[2,13],25:[2,13]},{5:[2,14],14:[2,14],15:[2,14],16:[2,14],19:[2,14],20:[2,14],22:[2,14],23:[2,14],25:[2,14]},{5:[2,15],14:[2,15],15:[2,15],16:[2,15],19:[2,15],20:[2,15],22:[2,15],23:[2,15],25:[2,15]},{5:[2,16],14:[2,16],15:[2,16],16:[2,16],19:[2,16],20:[2,16],22:[2,16],23:[2,16],25:[2,16]},{17:23,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:29,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:30,21:24,30:25,40:[1,28],42:[1,27],43:26},{17:31,21:24,30:25,40:[1,28],42:[1,27],43:26},{21:33,26:32,32:[1,34],33:[1,35],40:[1,28],43:26},{1:[2,1]},{5:[2,10],14:[2,10],15:[2,10],16:[2,10],19:[2,10],20:[2,10],22:[2,10],23:[2,10],25:[2,10]},{10:36,20:[1,37]},{4:38,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,7],22:[1,13],23:[1,14],25:[1,15]},{7:39,8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,21],20:[2,6],22:[1,13],23:[1,14],25:[1,15]},{17:23,18:[1,40],21:24,30:25,40:[1,28],42:[1,27],43:26},{10:41,20:[1,37]},{18:[1,42]},{18:[2,43],24:[2,43],28:43,32:[2,43],33:[2,43],34:[2,43],35:[2,43],36:[2,43],40:[2,43],42:[2,43]},{18:[2,25],24:[2,25],36:[2,25]},{18:[2,38],24:[2,38],32:[2,38],33:[2,38],34:[2,38],35:[2,38],36:[2,38],40:[2,38],42:[2,38],44:[1,44]},{21:45,40:[1,28],43:26},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],42:[2,40],44:[2,40]},{18:[1,46]},{18:[1,47]},{24:[1,48]},{18:[2,41],21:50,27:49,40:[1,28],43:26},{18:[2,34],40:[2,34]},{18:[2,35],40:[2,35]},{18:[2,36],40:[2,36]},{5:[2,11],14:[2,11],15:[2,11],16:[2,11],19:[2,11],20:[2,11],22:[2,11],23:[2,11],25:[2,11]},{21:51,40:[1,28],43:26},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,3],22:[1,13],23:[1,14],25:[1,15]},{4:52,8:4,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,5],22:[1,13],23:[1,14],25:[1,15]},{14:[2,23],15:[2,23],16:[2,23],19:[2,23],20:[2,23],22:[2,23],23:[2,23],25:[2,23]},{5:[2,12],14:[2,12],15:[2,12],16:[2,12],19:[2,12],20:[2,12],22:[2,12],23:[2,12],25:[2,12]},{14:[2,18],15:[2,18],16:[2,18],19:[2,18],20:[2,18],22:[2,18],23:[2,18],25:[2,18]},{18:[2,45],21:56,24:[2,45],29:53,30:60,31:54,32:[1,57],33:[1,58],34:[1,59],35:[1,61],36:[2,45],37:55,38:62,39:63,40:[1,64],42:[1,27],43:26},{40:[1,65]},{18:[2,37],24:[2,37],32:[2,37],33:[2,37],34:[2,37],35:[2,37],36:[2,37],40:[2,37],42:[2,37]},{14:[2,17],15:[2,17],16:[2,17],19:[2,17],20:[2,17],22:[2,17],23:[2,17],25:[2,17]},{5:[2,20],14:[2,20],15:[2,20],16:[2,20],19:[2,20],20:[2,20],22:[2,20],23:[2,20],25:[2,20]},{5:[2,21],14:[2,21],15:[2,21],16:[2,21],19:[2,21],20:[2,21],22:[2,21],23:[2,21],25:[2,21]},{18:[1,66]},{18:[2,42]},{18:[1,67]},{8:17,9:5,11:6,12:7,13:8,14:[1,9],15:[1,10],16:[1,12],19:[1,11],20:[2,4],22:[1,13],23:[1,14],25:[1,15]},{18:[2,24],24:[2,24],36:[2,24]},{18:[2,44],24:[2,44],32:[2,44],33:[2,44],34:[2,44],35:[2,44],36:[2,44],40:[2,44],42:[2,44]},{18:[2,46],24:[2,46],36:[2,46]},{18:[2,26],24:[2,26],32:[2,26],33:[2,26],34:[2,26],35:[2,26],36:[2,26],40:[2,26],42:[2,26]},{18:[2,27],24:[2,27],32:[2,27],33:[2,27],34:[2,27],35:[2,27],36:[2,27],40:[2,27],42:[2,27]},{18:[2,28],24:[2,28],32:[2,28],33:[2,28],34:[2,28],35:[2,28],36:[2,28],40:[2,28],42:[2,28]},{18:[2,29],24:[2,29],32:[2,29],33:[2,29],34:[2,29],35:[2,29],36:[2,29],40:[2,29],42:[2,29]},{18:[2,30],24:[2,30],32:[2,30],33:[2,30],34:[2,30],35:[2,30],36:[2,30],40:[2,30],42:[2,30]},{17:68,21:24,30:25,40:[1,28],42:[1,27],43:26},{18:[2,32],24:[2,32],36:[2,32],39:69,40:[1,70]},{18:[2,47],24:[2,47],36:[2,47],40:[2,47]},{18:[2,40],24:[2,40],32:[2,40],33:[2,40],34:[2,40],35:[2,40],36:[2,40],40:[2,40],41:[1,71],42:[2,40],44:[2,40]},{18:[2,39],24:[2,39],32:[2,39],33:[2,39],34:[2,39],35:[2,39],36:[2,39],40:[2,39],42:[2,39],44:[2,39]},{5:[2,22],14:[2,22],15:[2,22],16:[2,22],19:[2,22],20:[2,22],22:[2,22],23:[2,22],25:[2,22]},{5:[2,19],14:[2,19],15:[2,19],16:[2,19],19:[2,19],20:[2,19],22:[2,19],23:[2,19],25:[2,19]},{36:[1,72]},{18:[2,48],24:[2,48],36:[2,48],40:[2,48]},{41:[1,71]},{21:56,30:60,31:73,32:[1,57],33:[1,58],34:[1,59],35:[1,61],40:[1,28],42:[1,27],43:26},{18:[2,31],24:[2,31],32:[2,31],33:[2,31],34:[2,31],35:[2,31],36:[2,31],40:[2,31],42:[2,31]},{18:[2,33],24:[2,33],36:[2,33],40:[2,33]}],defaultActions:{3:[2,2],16:[2,1],50:[2,42]},parseError:function(a){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:((null===n||"undefined"==typeof n)&&(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},d=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;gb[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substr(a,b.yyleng-c)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 14;break;case 1:return 14;case 2:return this.popState(),14;case 3:return e(0,4),this.popState(),15;case 4:return 35;case 5:return 36;case 6:return 25;case 7:return 16;case 8:return 20;case 9:return 19;case 10:return 19;case 11:return 23;case 12:return 22;case 13:this.popState(),this.begin("com");break;case 14:return e(3,5),this.popState(),15;case 15:return 22;case 16:return 41;case 17:return 40;case 18:return 40;case 19:return 44;case 20:break;case 21:return this.popState(),24;case 22:return this.popState(),18;case 23:return b.yytext=e(1,2).replace(/\\"/g,'"'),32;case 24:return b.yytext=e(1,2).replace(/\\'/g,"'"),32;case 25:return 42;case 26:return 34;case 27:return 34;case 28:return 33;case 29:return 40;case 30:return b.yytext=e(1,2),40;case 31:return"INVALID";case 32:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[3],inclusive:!1},INITIAL:{rules:[0,1,32],inclusive:!0}},a}();return c.lexer=d,b.prototype=c,c.Parser=b,new b}();return a=b}(),i=function(a,b){"use strict";function c(a){return a.constructor===f.ProgramNode?a:(e.yy=f,e.parse(a))}var d={},e=a,f=b;return d.parser=e,d.parse=c,d}(h,g),j=function(a){"use strict";function b(){}function c(a,b,c){if(null==a||"string"!=typeof a&&a.constructor!==c.AST.ProgramNode)throw new f("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0);var d=c.parse(a),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function d(a,b,c){function d(){var d=c.parse(a),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}if(null==a||"string"!=typeof a&&a.constructor!==c.AST.ProgramNode)throw new f("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=b||{},"data"in b||(b.data=!0);var e;return function(a,b){return e||(e=d()),e.call(this,a,b)}}var e={},f=a;return e.Compiler=b,b.prototype={compiler:b,disassemble:function(){for(var a,b,c,d=this.opcodes,e=[],f=0,g=d.length;g>f;f++)if(a=d[f],"DECLARE"===a.opcode)e.push("DECLARE "+a.name+"="+a.value);else{b=[];for(var h=0;hc;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||d.args.length!==e.args.length)return!1;for(var f=0;fc;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){this.opcodes=[],this.children=[],this.depths={list:[]},this.options=b;var c=this.options.knownHelpers;if(this.options.knownHelpers={helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0},c)for(var d in c)this.options.knownHelpers[d]=c[d];return this.accept(a)},accept:function(a){var b,c=a.strip||{};return c.left&&this.opcode("strip"),b=this[a.type](a),c.right&&this.opcode("strip"),b},program:function(a){for(var b=a.statements,c=0,d=b.length;d>c;c++)this.accept(b[c]);return this.isSimple=1===d,this.depths.list=this.depths.list.sort(function(a,b){return a-b}),this},compileProgram:function(a){var b,c=(new this.compiler).compile(a,this.options),d=this.guid++;this.usePartial=this.usePartial||c.usePartial,this.children[d]=c;for(var e=0,f=c.depths.list.length;f>e;e++)b=c.depths.list[e],2>b||this.addDepth(b-1);return d},block:function(a){var b=a.mustache,c=a.program,d=a.inverse;c&&(c=this.compileProgram(c)),d&&(d=this.compileProgram(d));var e=b.sexpr,f=this.classifySexpr(e);"helper"===f?this.helperSexpr(e,c,d):"simple"===f?(this.simpleSexpr(e),this.opcode("pushProgram",c),this.opcode("pushProgram",d),this.opcode("emptyHash"),this.opcode("blockValue")):(this.ambiguousSexpr(e,c,d),this.opcode("pushProgram",c),this.opcode("pushProgram",d),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},hash:function(a){var b,c,d=a.pairs;this.opcode("pushHash");for(var e=0,f=d.length;f>e;e++)b=d[e],c=b[1],this.options.stringParams?(c.depth&&this.addDepth(c.depth),this.opcode("getContext",c.depth||0),this.opcode("pushStringParam",c.stringModeValue,c.type),"sexpr"===c.type&&this.sexpr(c)):this.accept(c),this.opcode("assignToHash",b[0]);this.opcode("popHash")},partial:function(a){var b=a.partialName;this.usePartial=!0,a.context?this.ID(a.context):this.opcode("push","depth0"),this.opcode("invokePartial",b.name),this.opcode("append")},content:function(a){this.opcode("appendContent",a.string)},mustache:function(a){this.sexpr(a.sexpr),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},ambiguousSexpr:function(a,b,c){var d=a.id,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.id;"DATA"===b.type?this.DATA(b):b.parts.length?this.ID(b):(this.addDepth(b.depth),this.opcode("getContext",b.depth),this.opcode("pushContext")),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.id.parts[0];if(this.options.knownHelpers[e])this.opcode("invokeKnownHelper",d.length,e);else{if(this.options.knownHelpersOnly)throw new f("You specified knownHelpersOnly, but used the unknown helper "+e,a);this.opcode("invokeHelper",d.length,e,a.isRoot)}},sexpr:function(a){var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ID:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0];b?this.opcode("lookupOnContext",a.parts[0]):this.opcode("pushContext");for(var c=1,d=a.parts.length;d>c;c++)this.opcode("lookup",a.parts[c])},DATA:function(a){if(this.options.data=!0,a.id.isScoped||a.id.depth)throw new f("Scoped data references are not supported: "+a.original,a);this.opcode("lookupData");for(var b=a.id.parts,c=0,d=b.length;d>c;c++)this.opcode("lookup",b[c])},STRING:function(a){this.opcode("pushString",a.string)},INTEGER:function(a){this.opcode("pushLiteral",a.integer)},BOOLEAN:function(a){this.opcode("pushLiteral",a.bool)},comment:function(){},opcode:function(a){this.opcodes.push({opcode:a,args:[].slice.call(arguments,1)})},declare:function(a,b){this.opcodes.push({opcode:"DECLARE",name:a,value:b})},addDepth:function(a){0!==a&&(this.depths[a]||(this.depths[a]=!0,this.depths.list.push(a)))},classifySexpr:function(a){var b=a.isHelper,c=a.eligibleHelper,d=this.options;if(c&&!b){var e=a.id.parts[0];d.knownHelpers[e]?b=!0:d.knownHelpersOnly&&(c=!1)}return b?"helper":c?"ambiguous":"simple"},pushParams:function(a){for(var b,c=a.length;c--;)b=a[c],this.options.stringParams?(b.depth&&this.addDepth(b.depth),this.opcode("getContext",b.depth||0),this.opcode("pushStringParam",b.stringModeValue,b.type),"sexpr"===b.type&&this.sexpr(b)):this[b.type](b)},setupFullMustacheParams:function(a,b,c){var d=a.params;return this.pushParams(d),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.hash(a.hash):this.opcode("emptyHash"),d}},e.precompile=c,e.compile=d,e}(c),k=function(a,b){"use strict";function c(a){this.value=a}function d(){}var e,f=a.COMPILER_REVISION,g=a.REVISION_CHANGES,h=a.log,i=b;d.prototype={nameLookup:function(a,b){var c,e;return 0===a.indexOf("depth")&&(c=!0),e=/^[0-9]+$/.test(b)?a+"["+b+"]":d.isValidJavaScriptVariableName(b)?a+"."+b:a+"['"+b+"']",c?"("+a+" && "+e+")":e},compilerInfo:function(){var a=f,b=g[a];return"this.compilerInfo = ["+a+",'"+b+"'];\n"},appendToBuffer:function(a){return this.environment.isSimple?"return "+a+";":{appendToBuffer:!0,content:a,toString:function(){return"buffer += "+a+";"}}},initializeBuffer:function(){return this.quotedString("")},namespace:"Handlebars",compile:function(a,b,c,d){this.environment=a,this.options=b||{},h("debug",this.environment.disassemble()+"\n\n"),this.name=this.environment.name,this.isChild=!!c,this.context=c||{programs:[],environments:[],aliases:{}},this.preamble(),this.stackSlot=0,this.stackVars=[],this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.compileChildren(a,b); -var e,f=a.opcodes;this.i=0;for(var g=f.length;this.ie;e++)d.push("depth"+this.environment.depths.list[e]);var g=this.mergeSource();if(this.isChild||(g=this.compilerInfo()+g),a)return d.push(g),Function.apply(this,d);var i="function "+(this.name||"")+"("+d.join(",")+") {\n "+g+"}";return h("debug",i+"\n\n"),i},mergeSource:function(){for(var a,b="",c=0,d=this.source.length;d>c;c++){var e=this.source[c];e.appendToBuffer?a=a?a+"\n + "+e.content:e.content:(a&&(b+="buffer += "+a+";\n ",a=void 0),b+=e+"\n ")}return b},blockValue:function(){this.context.aliases.blockHelperMissing="helpers.blockHelperMissing";var a=["depth0"];this.setupParams(0,a),this.replaceStack(function(b){return a.splice(1,0,b),"blockHelperMissing.call("+a.join(", ")+")"})},ambiguousBlockValue:function(){this.context.aliases.blockHelperMissing="helpers.blockHelperMissing";var a=["depth0"];this.setupParams(0,a);var b=this.topStack();a.splice(1,0,b),this.pushSource("if (!"+this.lastHelper+") { "+b+" = blockHelperMissing.call("+a.join(", ")+"); }")},appendContent:function(a){this.pendingContent&&(a=this.pendingContent+a),this.stripNext&&(a=a.replace(/^\s+/,"")),this.pendingContent=a},strip:function(){this.pendingContent&&(this.pendingContent=this.pendingContent.replace(/\s+$/,"")),this.stripNext="strip"},append:function(){this.flushInline();var a=this.popStack();this.pushSource("if("+a+" || "+a+" === 0) { "+this.appendToBuffer(a)+" }"),this.environment.isSimple&&this.pushSource("else { "+this.appendToBuffer("''")+" }")},appendEscaped:function(){this.context.aliases.escapeExpression="this.escapeExpression",this.pushSource(this.appendToBuffer("escapeExpression("+this.popStack()+")"))},getContext:function(a){this.lastContext!==a&&(this.lastContext=a)},lookupOnContext:function(a){this.push(this.nameLookup("depth"+this.lastContext,a,"context"))},pushContext:function(){this.pushStackLiteral("depth"+this.lastContext)},resolvePossibleLambda:function(){this.context.aliases.functionType='"function"',this.replaceStack(function(a){return"typeof "+a+" === functionType ? "+a+".apply(depth0) : "+a})},lookup:function(a){this.replaceStack(function(b){return b+" == null || "+b+" === false ? "+b+" : "+this.nameLookup(b,a,"context")})},lookupData:function(){this.pushStackLiteral("data")},pushStringParam:function(a,b){this.pushStackLiteral("depth"+this.lastContext),this.pushString(b),"sexpr"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(){this.pushStackLiteral("{}"),this.options.stringParams&&(this.push("{}"),this.push("{}"))},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:[],types:[],contexts:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.options.stringParams&&(this.push("{"+a.contexts.join(",")+"}"),this.push("{"+a.types.join(",")+"}")),this.push("{\n "+a.values.join(",\n ")+"\n }")},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},push:function(a){return this.inlineStack.push(a),a},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},invokeHelper:function(a,b,c){this.context.aliases.helperMissing="helpers.helperMissing",this.useRegister("helper");var d=this.lastHelper=this.setupHelper(a,b,!0),e=this.nameLookup("depth"+this.lastContext,b,"context"),f="helper = "+d.name+" || "+e;d.paramsInit&&(f+=","+d.paramsInit),this.push("("+f+",helper ? helper.call("+d.callParams+") : helperMissing.call("+d.helperMissingParams+"))"),c||this.flushInline()},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(c.name+".call("+c.callParams+")")},invokeAmbiguous:function(a,b){this.context.aliases.functionType='"function"',this.useRegister("helper"),this.emptyHash();var c=this.setupHelper(0,a,b),d=this.lastHelper=this.nameLookup("helpers",a,"helper"),e=this.nameLookup("depth"+this.lastContext,a,"context"),f=this.nextStack();c.paramsInit&&this.pushSource(c.paramsInit),this.pushSource("if (helper = "+d+") { "+f+" = helper.call("+c.callParams+"); }"),this.pushSource("else { helper = "+e+"; "+f+" = typeof helper === functionType ? helper.call("+c.callParams+") : helper; }")},invokePartial:function(a){var b=[this.nameLookup("partials",a,"partial"),"'"+a+"'",this.popStack(),"helpers","partials"];this.options.data&&b.push("data"),this.context.aliases.self="this",this.push("self.invokePartial("+b.join(", ")+")")},assignToHash:function(a){var b,c,d=this.popStack();this.options.stringParams&&(c=this.popStack(),b=this.popStack());var e=this.hash;b&&e.contexts.push("'"+a+"': "+b),c&&e.types.push("'"+a+"': "+c),e.values.push("'"+a+"': ("+d+")")},compiler:d,compileChildren:function(a,b){for(var c,d,e=a.children,f=0,g=e.length;g>f;f++){c=e[f],d=new this.compiler;var h=this.matchExistingProgram(c);null==h?(this.context.programs.push(""),h=this.context.programs.length,c.index=h,c.name="program"+h,this.context.programs[h]=d.compile(c,b,this.context),this.context.environments[h]=c):(c.index=h,c.name="program"+h)}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;c>b;b++){var d=this.context.environments[b];if(d&&d.equals(a))return b}},programExpression:function(a){if(this.context.aliases.self="this",null==a)return"self.noop";for(var b,c=this.environment.children[a],d=c.depths.list,e=[c.index,c.name,"data"],f=0,g=d.length;g>f;f++)b=d[f],1===b?e.push("depth0"):e.push("depth"+(b-1));return(0===d.length?"self.program(":"self.programWithDepth(")+e.join(", ")+")"},register:function(a,b){this.useRegister(a),this.pushSource(a+" = "+b+";")},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},pushStackLiteral:function(a){return this.push(new c(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.quotedString(this.pendingContent))),this.pendingContent=void 0),a&&this.source.push(a)},pushStack:function(a){this.flushInline();var b=this.incrStack();return a&&this.pushSource(b+" = "+a+";"),this.compileStack.push(b),b},replaceStack:function(a){var b,d,e,f="",g=this.isInline();if(g){var h=this.popStack(!0);if(h instanceof c)b=h.value,e=!0;else{d=!this.stackSlot;var i=d?this.incrStack():this.topStackName();f="("+this.push(i)+" = "+h+"),",b=this.topStack()}}else b=this.topStack();var j=a.call(this,b);return g?(e||this.popStack(),d&&this.stackSlot--,this.push("("+f+j+")")):(/^stack/.test(b)||(b=this.nextStack()),this.pushSource(b+" = ("+f+j+");")),b},nextStack:function(){return this.pushStack()},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;if(a.length){this.inlineStack=[];for(var b=0,d=a.length;d>b;b++){var e=a[b];e instanceof c?this.compileStack.push(e):this.pushStack(e)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),d=(b?this.inlineStack:this.compileStack).pop();if(!a&&d instanceof c)return d.value;if(!b){if(!this.stackSlot)throw new i("Invalid stack pop");this.stackSlot--}return d},topStack:function(a){var b=this.isInline()?this.inlineStack:this.compileStack,d=b[b.length-1];return!a&&d instanceof c?d.value:d},quotedString:function(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},setupHelper:function(a,b,c){var d=[],e=this.setupParams(a,d,c),f=this.nameLookup("helpers",b,"helper");return{params:d,paramsInit:e,name:f,callParams:["depth0"].concat(d).join(", "),helperMissingParams:c&&["depth0",this.quotedString(b)].concat(d).join(", ")}},setupOptions:function(a,b){var c,d,e,f=[],g=[],h=[];f.push("hash:"+this.popStack()),this.options.stringParams&&(f.push("hashTypes:"+this.popStack()),f.push("hashContexts:"+this.popStack())),d=this.popStack(),e=this.popStack(),(e||d)&&(e||(this.context.aliases.self="this",e="self.noop"),d||(this.context.aliases.self="this",d="self.noop"),f.push("inverse:"+d),f.push("fn:"+e));for(var i=0;a>i;i++)c=this.popStack(),b.push(c),this.options.stringParams&&(h.push(this.popStack()),g.push(this.popStack()));return this.options.stringParams&&(f.push("contexts:["+g.join(",")+"]"),f.push("types:["+h.join(",")+"]")),this.options.data&&f.push("data:data"),f},setupParams:function(a,b,c){var d="{"+this.setupOptions(a,b).join(",")+"}";return c?(this.useRegister("options"),b.push("options"),"options="+d):(b.push(d),"")}};for(var j="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield".split(" "),k=d.RESERVED_WORDS={},l=0,m=j.length;m>l;l++)k[j[l]]=!0;return d.isValidJavaScriptVariableName=function(a){return!d.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)?!0:!1},e=d}(d,c),l=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c.parser,j=c.parse,k=d.Compiler,l=d.compile,m=d.precompile,n=e,o=g.create,p=function(){var a=o();return a.compile=function(b,c){return l(b,c,a)},a.precompile=function(b,c){return m(b,c,a)},a.AST=h,a.Compiler=k,a.JavaScriptCompiler=n,a.Parser=i,a.parse=j,a};return g=p(),g.create=p,f=g}(f,g,i,j,k);return l}(); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.runtime.amd.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.runtime.amd.js deleted file mode 100644 index b4f0fe90d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.runtime.amd.js +++ /dev/null @@ -1,515 +0,0 @@ -/*! - - handlebars v1.3.0 - -Copyright (C) 2011 by Yehuda Katz - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -@license -*/ - -define( - 'handlebars/safe-string',["exports"], - function(__exports__) { - - // Build out our basic SafeString type - function SafeString(string) { - this.string = string; - } - - SafeString.prototype.toString = function() { - return "" + this.string; - }; - - __exports__["default"] = SafeString; - }); -define( - 'handlebars/utils',["./safe-string","exports"], - function(__dependency1__, __exports__) { - - /*jshint -W004 */ - var SafeString = __dependency1__["default"]; - - var escape = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "`": "`" - }; - - var badChars = /[&<>"'`]/g; - var possible = /[&<>"'`]/; - - function escapeChar(chr) { - return escape[chr] || "&"; - } - - function extend(obj, value) { - for(var key in value) { - if(Object.prototype.hasOwnProperty.call(value, key)) { - obj[key] = value[key]; - } - } - } - - __exports__.extend = extend;var toString = Object.prototype.toString; - __exports__.toString = toString; - // Sourced from lodash - // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt - var isFunction = function(value) { - return typeof value === 'function'; - }; - // fallback for older versions of Chrome and Safari - if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; - } - var isFunction; - __exports__.isFunction = isFunction; - var isArray = Array.isArray || function(value) { - return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false; - }; - __exports__.isArray = isArray; - - function escapeExpression(string) { - // don't escape SafeStrings, since they're already safe - if (string instanceof SafeString) { - return string.toString(); - } else if (!string && string !== 0) { - return ""; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = "" + string; - - if(!possible.test(string)) { return string; } - return string.replace(badChars, escapeChar); - } - - __exports__.escapeExpression = escapeExpression;function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } - } - - __exports__.isEmpty = isEmpty; - }); -define( - 'handlebars/exception',["exports"], - function(__exports__) { - - - var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; - - function Exception(message, node) { - var line; - if (node && node.firstLine) { - line = node.firstLine; - - message += ' - ' + line + ':' + node.firstColumn; - } - - var tmp = Error.prototype.constructor.call(this, message); - - // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. - for (var idx = 0; idx < errorProps.length; idx++) { - this[errorProps[idx]] = tmp[errorProps[idx]]; - } - - if (line) { - this.lineNumber = line; - this.column = node.firstColumn; - } - } - - Exception.prototype = new Error(); - - __exports__["default"] = Exception; - }); -define( - 'handlebars/base',["./utils","./exception","exports"], - function(__dependency1__, __dependency2__, __exports__) { - - var Utils = __dependency1__; - var Exception = __dependency2__["default"]; - - var VERSION = "1.3.0"; - __exports__.VERSION = VERSION;var COMPILER_REVISION = 4; - __exports__.COMPILER_REVISION = COMPILER_REVISION; - var REVISION_CHANGES = { - 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '== 1.0.0-rc.3', - 3: '== 1.0.0-rc.4', - 4: '>= 1.0.0' - }; - __exports__.REVISION_CHANGES = REVISION_CHANGES; - var isArray = Utils.isArray, - isFunction = Utils.isFunction, - toString = Utils.toString, - objectType = '[object Object]'; - - function HandlebarsEnvironment(helpers, partials) { - this.helpers = helpers || {}; - this.partials = partials || {}; - - registerDefaultHelpers(this); - } - - __exports__.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = { - constructor: HandlebarsEnvironment, - - logger: logger, - log: log, - - registerHelper: function(name, fn, inverse) { - if (toString.call(name) === objectType) { - if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); } - Utils.extend(this.helpers, name); - } else { - if (inverse) { fn.not = inverse; } - this.helpers[name] = fn; - } - }, - - registerPartial: function(name, str) { - if (toString.call(name) === objectType) { - Utils.extend(this.partials, name); - } else { - this.partials[name] = str; - } - } - }; - - function registerDefaultHelpers(instance) { - instance.registerHelper('helperMissing', function(arg) { - if(arguments.length === 2) { - return undefined; - } else { - throw new Exception("Missing helper: '" + arg + "'"); - } - }); - - instance.registerHelper('blockHelperMissing', function(context, options) { - var inverse = options.inverse || function() {}, fn = options.fn; - - if (isFunction(context)) { context = context.call(this); } - - if(context === true) { - return fn(this); - } else if(context === false || context == null) { - return inverse(this); - } else if (isArray(context)) { - if(context.length > 0) { - return instance.helpers.each(context, options); - } else { - return inverse(this); - } - } else { - return fn(context); - } - }); - - instance.registerHelper('each', function(context, options) { - var fn = options.fn, inverse = options.inverse; - var i = 0, ret = "", data; - - if (isFunction(context)) { context = context.call(this); } - - if (options.data) { - data = createFrame(options.data); - } - - if(context && typeof context === 'object') { - if (isArray(context)) { - for(var j = context.length; i":">",'"':""","'":"'","`":"`"},i=/[&<>"'`]/g,j=/[&<>"'`]/;b.extend=d;var k=Object.prototype.toString;b.toString=k;var l=function(a){return"function"==typeof a};l(/x/)&&(l=function(a){return"function"==typeof a&&"[object Function]"===k.call(a)});var l;b.isFunction=l;var m=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===k.call(a):!1};b.isArray=m,b.escapeExpression=e,b.isEmpty=f}),define("handlebars/exception",["exports"],function(a){function b(a,b){var d;b&&b.firstLine&&(d=b.firstLine,a+=" - "+d+":"+b.firstColumn);for(var e=Error.prototype.constructor.call(this,a),f=0;f0?a.helpers.each(b,c):d(this):e(b)}),a.registerHelper("each",function(a,b){var c,d=b.fn,e=b.inverse,f=0,g="";if(m(a)&&(a=a.call(this)),b.data&&(c=q(b.data)),a&&"object"==typeof a)if(l(a))for(var h=a.length;h>f;f++)c&&(c.index=f,c.first=0===f,c.last=f===a.length-1),g+=d(a[f],{data:c});else for(var i in a)a.hasOwnProperty(i)&&(c&&(c.key=i,c.index=f,c.first=0===f),g+=d(a[i],{data:c}),f++);return 0===f&&(g=e(this)),g}),a.registerHelper("if",function(a,b){return m(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||g.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){return m(a)&&(a=a.call(this)),g.isEmpty(a)?void 0:b.fn(a)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)})}function f(a,b){p.log(a,b)}var g=a,h=b["default"],i="1.3.0";c.VERSION=i;var j=4;c.COMPILER_REVISION=j;var k={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"};c.REVISION_CHANGES=k;var l=g.isArray,m=g.isFunction,n=g.toString,o="[object Object]";c.HandlebarsEnvironment=d,d.prototype={constructor:d,logger:p,log:f,registerHelper:function(a,b,c){if(n.call(a)===o){if(c||b)throw new h("Arg not supported with multiple helpers");g.extend(this.helpers,a)}else c&&(b.not=c),this.helpers[a]=b},registerPartial:function(a,b){n.call(a)===o?g.extend(this.partials,a):this.partials[a]=b}};var p={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,log:function(a,b){if(p.level<=a){var c=p.methodMap[a];"undefined"!=typeof console&&console[c]&&console[c].call(console,b)}}};c.logger=p,c.log=f;var q=function(a){var b={};return g.extend(b,a),b};c.createFrame=q}),define("handlebars/runtime",["./utils","./exception","./base","exports"],function(a,b,c,d){function e(a){var b=a&&a[0]||1,c=m;if(b!==c){if(c>b){var d=n[c],e=n[b];throw new l("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new l("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function f(a,b){if(!b)throw new l("No environment passed to template");var c=function(a,c,d,e,f,g){var h=b.VM.invokePartial.apply(this,arguments);if(null!=h)return h;if(b.compile){var i={helpers:e,partials:f,data:g};return f[c]=b.compile(a,{data:void 0!==g},b),f[c](d,i)}throw new l("The partial "+c+" could not be compiled when running in runtime-only mode")},d={escapeExpression:k.escapeExpression,invokePartial:c,programs:[],program:function(a,b,c){var d=this.programs[a];return c?d=h(a,b,c):d||(d=this.programs[a]=h(a,b)),d},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c={},k.extend(c,b),k.extend(c,a)),c},programWithDepth:b.VM.programWithDepth,noop:b.VM.noop,compilerInfo:null};return function(c,e){e=e||{};var f,g,h=e.partial?e:b;e.partial||(f=e.helpers,g=e.partials);var i=a.call(d,h,c,f,g,e.data);return e.partial||b.VM.checkRevision(d.compilerInfo),i}}function g(a,b,c){var d=Array.prototype.slice.call(arguments,3),e=function(a,e){return e=e||{},b.apply(this,[a,e.data||c].concat(d))};return e.program=a,e.depth=d.length,e}function h(a,b,c){var d=function(a,d){return d=d||{},b(a,d.data||c)};return d.program=a,d.depth=0,d}function i(a,b,c,d,e,f){var g={partial:!0,helpers:d,partials:e,data:f};if(void 0===a)throw new l("The partial "+b+" could not be found");return a instanceof Function?a(c,g):void 0}function j(){return""}var k=a,l=b["default"],m=c.COMPILER_REVISION,n=c.REVISION_CHANGES;d.checkRevision=e,d.template=f,d.programWithDepth=g,d.program=h,d.invokePartial=i,d.noop=j}),define("handlebars.runtime",["./handlebars/base","./handlebars/safe-string","./handlebars/exception","./handlebars/utils","./handlebars/runtime","exports"],function(a,b,c,d,e,f){var g=a,h=b["default"],i=c["default"],j=d,k=e,l=function(){var a=new g.HandlebarsEnvironment;return j.extend(a,g),a.SafeString=h,a.Exception=i,a.Utils=j,a.VM=k,a.template=function(b){return k.template(b,a)},a},m=l();m.create=l,f["default"]=m}); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.runtime.js b/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.runtime.js deleted file mode 100644 index b94930fa8..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/dist/handlebars.runtime.js +++ /dev/null @@ -1,530 +0,0 @@ -/*! - - handlebars v1.3.0 - -Copyright (C) 2011 by Yehuda Katz - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -@license -*/ -/* exported Handlebars */ -var Handlebars = (function() { -// handlebars/safe-string.js -var __module3__ = (function() { - "use strict"; - var __exports__; - // Build out our basic SafeString type - function SafeString(string) { - this.string = string; - } - - SafeString.prototype.toString = function() { - return "" + this.string; - }; - - __exports__ = SafeString; - return __exports__; -})(); - -// handlebars/utils.js -var __module2__ = (function(__dependency1__) { - "use strict"; - var __exports__ = {}; - /*jshint -W004 */ - var SafeString = __dependency1__; - - var escape = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "`": "`" - }; - - var badChars = /[&<>"'`]/g; - var possible = /[&<>"'`]/; - - function escapeChar(chr) { - return escape[chr] || "&"; - } - - function extend(obj, value) { - for(var key in value) { - if(Object.prototype.hasOwnProperty.call(value, key)) { - obj[key] = value[key]; - } - } - } - - __exports__.extend = extend;var toString = Object.prototype.toString; - __exports__.toString = toString; - // Sourced from lodash - // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt - var isFunction = function(value) { - return typeof value === 'function'; - }; - // fallback for older versions of Chrome and Safari - if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; - } - var isFunction; - __exports__.isFunction = isFunction; - var isArray = Array.isArray || function(value) { - return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false; - }; - __exports__.isArray = isArray; - - function escapeExpression(string) { - // don't escape SafeStrings, since they're already safe - if (string instanceof SafeString) { - return string.toString(); - } else if (!string && string !== 0) { - return ""; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = "" + string; - - if(!possible.test(string)) { return string; } - return string.replace(badChars, escapeChar); - } - - __exports__.escapeExpression = escapeExpression;function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } - } - - __exports__.isEmpty = isEmpty; - return __exports__; -})(__module3__); - -// handlebars/exception.js -var __module4__ = (function() { - "use strict"; - var __exports__; - - var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; - - function Exception(message, node) { - var line; - if (node && node.firstLine) { - line = node.firstLine; - - message += ' - ' + line + ':' + node.firstColumn; - } - - var tmp = Error.prototype.constructor.call(this, message); - - // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. - for (var idx = 0; idx < errorProps.length; idx++) { - this[errorProps[idx]] = tmp[errorProps[idx]]; - } - - if (line) { - this.lineNumber = line; - this.column = node.firstColumn; - } - } - - Exception.prototype = new Error(); - - __exports__ = Exception; - return __exports__; -})(); - -// handlebars/base.js -var __module1__ = (function(__dependency1__, __dependency2__) { - "use strict"; - var __exports__ = {}; - var Utils = __dependency1__; - var Exception = __dependency2__; - - var VERSION = "1.3.0"; - __exports__.VERSION = VERSION;var COMPILER_REVISION = 4; - __exports__.COMPILER_REVISION = COMPILER_REVISION; - var REVISION_CHANGES = { - 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '== 1.0.0-rc.3', - 3: '== 1.0.0-rc.4', - 4: '>= 1.0.0' - }; - __exports__.REVISION_CHANGES = REVISION_CHANGES; - var isArray = Utils.isArray, - isFunction = Utils.isFunction, - toString = Utils.toString, - objectType = '[object Object]'; - - function HandlebarsEnvironment(helpers, partials) { - this.helpers = helpers || {}; - this.partials = partials || {}; - - registerDefaultHelpers(this); - } - - __exports__.HandlebarsEnvironment = HandlebarsEnvironment;HandlebarsEnvironment.prototype = { - constructor: HandlebarsEnvironment, - - logger: logger, - log: log, - - registerHelper: function(name, fn, inverse) { - if (toString.call(name) === objectType) { - if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); } - Utils.extend(this.helpers, name); - } else { - if (inverse) { fn.not = inverse; } - this.helpers[name] = fn; - } - }, - - registerPartial: function(name, str) { - if (toString.call(name) === objectType) { - Utils.extend(this.partials, name); - } else { - this.partials[name] = str; - } - } - }; - - function registerDefaultHelpers(instance) { - instance.registerHelper('helperMissing', function(arg) { - if(arguments.length === 2) { - return undefined; - } else { - throw new Exception("Missing helper: '" + arg + "'"); - } - }); - - instance.registerHelper('blockHelperMissing', function(context, options) { - var inverse = options.inverse || function() {}, fn = options.fn; - - if (isFunction(context)) { context = context.call(this); } - - if(context === true) { - return fn(this); - } else if(context === false || context == null) { - return inverse(this); - } else if (isArray(context)) { - if(context.length > 0) { - return instance.helpers.each(context, options); - } else { - return inverse(this); - } - } else { - return fn(context); - } - }); - - instance.registerHelper('each', function(context, options) { - var fn = options.fn, inverse = options.inverse; - var i = 0, ret = "", data; - - if (isFunction(context)) { context = context.call(this); } - - if (options.data) { - data = createFrame(options.data); - } - - if(context && typeof context === 'object') { - if (isArray(context)) { - for(var j = context.length; i":">",'"':""","'":"'","`":"`"},i=/[&<>"'`]/g,j=/[&<>"'`]/;f.extend=c;var k=Object.prototype.toString;f.toString=k;var l=function(a){return"function"==typeof a};l(/x/)&&(l=function(a){return"function"==typeof a&&"[object Function]"===k.call(a)});var l;f.isFunction=l;var m=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===k.call(a):!1};return f.isArray=m,f.escapeExpression=d,f.isEmpty=e,f}(a),c=function(){"use strict";function a(a,b){var d;b&&b.firstLine&&(d=b.firstLine,a+=" - "+d+":"+b.firstColumn);for(var e=Error.prototype.constructor.call(this,a),f=0;f0?a.helpers.each(b,c):d(this):e(b)}),a.registerHelper("each",function(a,b){var c,d=b.fn,e=b.inverse,f=0,g="";if(m(a)&&(a=a.call(this)),b.data&&(c=q(b.data)),a&&"object"==typeof a)if(l(a))for(var h=a.length;h>f;f++)c&&(c.index=f,c.first=0===f,c.last=f===a.length-1),g+=d(a[f],{data:c});else for(var i in a)a.hasOwnProperty(i)&&(c&&(c.key=i,c.index=f,c.first=0===f),g+=d(a[i],{data:c}),f++);return 0===f&&(g=e(this)),g}),a.registerHelper("if",function(a,b){return m(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||g.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){return m(a)&&(a=a.call(this)),g.isEmpty(a)?void 0:b.fn(a)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)})}function e(a,b){p.log(a,b)}var f={},g=a,h=b,i="1.3.0";f.VERSION=i;var j=4;f.COMPILER_REVISION=j;var k={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"};f.REVISION_CHANGES=k;var l=g.isArray,m=g.isFunction,n=g.toString,o="[object Object]";f.HandlebarsEnvironment=c,c.prototype={constructor:c,logger:p,log:e,registerHelper:function(a,b,c){if(n.call(a)===o){if(c||b)throw new h("Arg not supported with multiple helpers");g.extend(this.helpers,a)}else c&&(b.not=c),this.helpers[a]=b},registerPartial:function(a,b){n.call(a)===o?g.extend(this.partials,a):this.partials[a]=b}};var p={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,log:function(a,b){if(p.level<=a){var c=p.methodMap[a];"undefined"!=typeof console&&console[c]&&console[c].call(console,b)}}};f.logger=p,f.log=e;var q=function(a){var b={};return g.extend(b,a),b};return f.createFrame=q,f}(b,c),e=function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=m;if(b!==c){if(c>b){var d=n[c],e=n[b];throw new l("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new l("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){if(!b)throw new l("No environment passed to template");var c=function(a,c,d,e,f,g){var h=b.VM.invokePartial.apply(this,arguments);if(null!=h)return h;if(b.compile){var i={helpers:e,partials:f,data:g};return f[c]=b.compile(a,{data:void 0!==g},b),f[c](d,i)}throw new l("The partial "+c+" could not be compiled when running in runtime-only mode")},d={escapeExpression:k.escapeExpression,invokePartial:c,programs:[],program:function(a,b,c){var d=this.programs[a];return c?d=g(a,b,c):d||(d=this.programs[a]=g(a,b)),d},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c={},k.extend(c,b),k.extend(c,a)),c},programWithDepth:b.VM.programWithDepth,noop:b.VM.noop,compilerInfo:null};return function(c,e){e=e||{};var f,g,h=e.partial?e:b;e.partial||(f=e.helpers,g=e.partials);var i=a.call(d,h,c,f,g,e.data);return e.partial||b.VM.checkRevision(d.compilerInfo),i}}function f(a,b,c){var d=Array.prototype.slice.call(arguments,3),e=function(a,e){return e=e||{},b.apply(this,[a,e.data||c].concat(d))};return e.program=a,e.depth=d.length,e}function g(a,b,c){var d=function(a,d){return d=d||{},b(a,d.data||c)};return d.program=a,d.depth=0,d}function h(a,b,c,d,e,f){var g={partial:!0,helpers:d,partials:e,data:f};if(void 0===a)throw new l("The partial "+b+" could not be found");return a instanceof Function?a(c,g):void 0}function i(){return""}var j={},k=a,l=b,m=c.COMPILER_REVISION,n=c.REVISION_CHANGES;return j.checkRevision=d,j.template=e,j.programWithDepth=f,j.program=g,j.invokePartial=h,j.noop=i,j}(b,c,d),f=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c,j=d,k=e,l=function(){var a=new g.HandlebarsEnvironment;return j.extend(a,g),a.SafeString=h,a.Exception=i,a.Utils=j,a.VM=k,a.template=function(b){return k.template(b,a)},a},m=l();return m.create=l,f=m}(d,a,c,b,e);return f}(); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars.js deleted file mode 100644 index ffa9c7ab2..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars.js +++ /dev/null @@ -1,33 +0,0 @@ -/*globals Handlebars: true */ -import Handlebars from "./handlebars.runtime"; - -// Compiler imports -import AST from "./handlebars/compiler/ast"; -import { parser as Parser, parse } from "./handlebars/compiler/base"; -import { Compiler, compile, precompile } from "./handlebars/compiler/compiler"; -import JavaScriptCompiler from "./handlebars/compiler/javascript-compiler"; - -var _create = Handlebars.create; -var create = function() { - var hb = _create(); - - hb.compile = function(input, options) { - return compile(input, options, hb); - }; - hb.precompile = function (input, options) { - return precompile(input, options, hb); - }; - - hb.AST = AST; - hb.Compiler = Compiler; - hb.JavaScriptCompiler = JavaScriptCompiler; - hb.Parser = Parser; - hb.parse = parse; - - return hb; -}; - -Handlebars = create(); -Handlebars.create = create; - -export default Handlebars; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars.runtime.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars.runtime.js deleted file mode 100644 index e77aae000..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars.runtime.js +++ /dev/null @@ -1,31 +0,0 @@ -/*globals Handlebars: true */ -module base from "./handlebars/base"; - -// Each of these augment the Handlebars object. No need to setup here. -// (This is done to easily share code between commonjs and browse envs) -import SafeString from "./handlebars/safe-string"; -import Exception from "./handlebars/exception"; -module Utils from "./handlebars/utils"; -module runtime from "./handlebars/runtime"; - -// For compatibility and usage outside of module systems, make the Handlebars object a namespace -var create = function() { - var hb = new base.HandlebarsEnvironment(); - - Utils.extend(hb, base); - hb.SafeString = SafeString; - hb.Exception = Exception; - hb.Utils = Utils; - - hb.VM = runtime; - hb.template = function(spec) { - return runtime.template(spec, hb); - }; - - return hb; -}; - -var Handlebars = create(); -Handlebars.create = create; - -export default Handlebars; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/base.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/base.js deleted file mode 100644 index 00c8bf1ff..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/base.js +++ /dev/null @@ -1,178 +0,0 @@ -module Utils from "./utils"; -import Exception from "./exception"; - -export var VERSION = "1.3.0"; -export var COMPILER_REVISION = 4; - -export var REVISION_CHANGES = { - 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it - 2: '== 1.0.0-rc.3', - 3: '== 1.0.0-rc.4', - 4: '>= 1.0.0' -}; - -var isArray = Utils.isArray, - isFunction = Utils.isFunction, - toString = Utils.toString, - objectType = '[object Object]'; - -export function HandlebarsEnvironment(helpers, partials) { - this.helpers = helpers || {}; - this.partials = partials || {}; - - registerDefaultHelpers(this); -} - -HandlebarsEnvironment.prototype = { - constructor: HandlebarsEnvironment, - - logger: logger, - log: log, - - registerHelper: function(name, fn, inverse) { - if (toString.call(name) === objectType) { - if (inverse || fn) { throw new Exception('Arg not supported with multiple helpers'); } - Utils.extend(this.helpers, name); - } else { - if (inverse) { fn.not = inverse; } - this.helpers[name] = fn; - } - }, - - registerPartial: function(name, str) { - if (toString.call(name) === objectType) { - Utils.extend(this.partials, name); - } else { - this.partials[name] = str; - } - } -}; - -function registerDefaultHelpers(instance) { - instance.registerHelper('helperMissing', function(arg) { - if(arguments.length === 2) { - return undefined; - } else { - throw new Exception("Missing helper: '" + arg + "'"); - } - }); - - instance.registerHelper('blockHelperMissing', function(context, options) { - var inverse = options.inverse || function() {}, fn = options.fn; - - if (isFunction(context)) { context = context.call(this); } - - if(context === true) { - return fn(this); - } else if(context === false || context == null) { - return inverse(this); - } else if (isArray(context)) { - if(context.length > 0) { - return instance.helpers.each(context, options); - } else { - return inverse(this); - } - } else { - return fn(context); - } - }); - - instance.registerHelper('each', function(context, options) { - var fn = options.fn, inverse = options.inverse; - var i = 0, ret = "", data; - - if (isFunction(context)) { context = context.call(this); } - - if (options.data) { - data = createFrame(options.data); - } - - if(context && typeof context === 'object') { - if (isArray(context)) { - for(var j = context.length; i 0) { - throw new Exception("Invalid path: " + original, this); - } else if (part === "..") { - depth++; - } else { - this.isScoped = true; - } - } else { - dig.push(part); - } - } - - this.original = original; - this.parts = dig; - this.string = dig.join('.'); - this.depth = depth; - - // an ID is simple if it only has one part, and that part is not - // `..` or `this`. - this.isSimple = parts.length === 1 && !this.isScoped && depth === 0; - - this.stringModeValue = this.string; - }, - - PartialNameNode: function(name, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "PARTIAL_NAME"; - this.name = name.original; - }, - - DataNode: function(id, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "DATA"; - this.id = id; - }, - - StringNode: function(string, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "STRING"; - this.original = - this.string = - this.stringModeValue = string; - }, - - IntegerNode: function(integer, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "INTEGER"; - this.original = - this.integer = integer; - this.stringModeValue = Number(integer); - }, - - BooleanNode: function(bool, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "BOOLEAN"; - this.bool = bool; - this.stringModeValue = bool === "true"; - }, - - CommentNode: function(comment, locInfo) { - LocationInfo.call(this, locInfo); - this.type = "comment"; - this.comment = comment; - } -}; - -// Must be exported as an object rather than the root of the module as the jison lexer -// most modify the object to operate properly. -export default AST; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/base.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/base.js deleted file mode 100644 index 722f09af5..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/base.js +++ /dev/null @@ -1,12 +0,0 @@ -import parser from "./parser"; -import AST from "./ast"; - -export { parser }; - -export function parse(input) { - // Just return if an already-compile AST was passed in. - if(input.constructor === AST.ProgramNode) { return input; } - - parser.yy = AST; - return parser.parse(input); -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/compiler.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/compiler.js deleted file mode 100644 index 461f98b65..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/compiler.js +++ /dev/null @@ -1,466 +0,0 @@ -import Exception from "../exception"; - -export function Compiler() {} - -// the foundHelper register will disambiguate helper lookup from finding a -// function in a context. This is necessary for mustache compatibility, which -// requires that context functions in blocks are evaluated by blockHelperMissing, -// and then proceed as if the resulting value was provided to blockHelperMissing. - -Compiler.prototype = { - compiler: Compiler, - - disassemble: function() { - var opcodes = this.opcodes, opcode, out = [], params, param; - - for (var i=0, l=opcodes.length; i 0) { - this.source[1] = this.source[1] + ", " + locals.join(", "); - } - - // Generate minimizer alias mappings - if (!this.isChild) { - for (var alias in this.context.aliases) { - if (this.context.aliases.hasOwnProperty(alias)) { - this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias]; - } - } - } - - if (this.source[1]) { - this.source[1] = "var " + this.source[1].substring(2) + ";"; - } - - // Merge children - if (!this.isChild) { - this.source[1] += '\n' + this.context.programs.join('\n') + '\n'; - } - - if (!this.environment.isSimple) { - this.pushSource("return buffer;"); - } - - var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"]; - - for(var i=0, l=this.environment.depths.list.length; i this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } - return this.topStackName(); - }, - topStackName: function() { - return "stack" + this.stackSlot; - }, - flushInline: function() { - var inlineStack = this.inlineStack; - if (inlineStack.length) { - this.inlineStack = []; - for (var i = 0, len = inlineStack.length; i < len; i++) { - var entry = inlineStack[i]; - if (entry instanceof Literal) { - this.compileStack.push(entry); - } else { - this.pushStack(entry); - } - } - } - }, - isInline: function() { - return this.inlineStack.length; - }, - - popStack: function(wrapped) { - var inline = this.isInline(), - item = (inline ? this.inlineStack : this.compileStack).pop(); - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - if (!inline) { - if (!this.stackSlot) { - throw new Exception('Invalid stack pop'); - } - this.stackSlot--; - } - return item; - } - }, - - topStack: function(wrapped) { - var stack = (this.isInline() ? this.inlineStack : this.compileStack), - item = stack[stack.length - 1]; - - if (!wrapped && (item instanceof Literal)) { - return item.value; - } else { - return item; - } - }, - - quotedString: function(str) { - return '"' + str - .replace(/\\/g, '\\\\') - .replace(/"/g, '\\"') - .replace(/\n/g, '\\n') - .replace(/\r/g, '\\r') - .replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4 - .replace(/\u2029/g, '\\u2029') + '"'; - }, - - setupHelper: function(paramSize, name, missingParams) { - var params = [], - paramsInit = this.setupParams(paramSize, params, missingParams); - var foundHelper = this.nameLookup('helpers', name, 'helper'); - - return { - params: params, - paramsInit: paramsInit, - name: foundHelper, - callParams: ["depth0"].concat(params).join(", "), - helperMissingParams: missingParams && ["depth0", this.quotedString(name)].concat(params).join(", ") - }; - }, - - setupOptions: function(paramSize, params) { - var options = [], contexts = [], types = [], param, inverse, program; - - options.push("hash:" + this.popStack()); - - if (this.options.stringParams) { - options.push("hashTypes:" + this.popStack()); - options.push("hashContexts:" + this.popStack()); - } - - inverse = this.popStack(); - program = this.popStack(); - - // Avoid setting fn and inverse if neither are set. This allows - // helpers to do a check for `if (options.fn)` - if (program || inverse) { - if (!program) { - this.context.aliases.self = "this"; - program = "self.noop"; - } - - if (!inverse) { - this.context.aliases.self = "this"; - inverse = "self.noop"; - } - - options.push("inverse:" + inverse); - options.push("fn:" + program); - } - - for(var i=0; i 2) { - expected.push("'" + this.terminals_[p] + "'"); - } - if (this.lexer.showPosition) { - errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; - } else { - errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'"); - } - this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected}); - } - } - if (action[0] instanceof Array && action.length > 1) { - throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); - } - switch (action[0]) { - case 1: - stack.push(symbol); - vstack.push(this.lexer.yytext); - lstack.push(this.lexer.yylloc); - stack.push(action[1]); - symbol = null; - if (!preErrorSymbol) { - yyleng = this.lexer.yyleng; - yytext = this.lexer.yytext; - yylineno = this.lexer.yylineno; - yyloc = this.lexer.yylloc; - if (recovering > 0) - recovering--; - } else { - symbol = preErrorSymbol; - preErrorSymbol = null; - } - break; - case 2: - len = this.productions_[action[1]][1]; - yyval.$ = vstack[vstack.length - len]; - yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column}; - if (ranges) { - yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; - } - r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); - if (typeof r !== "undefined") { - return r; - } - if (len) { - stack = stack.slice(0, -1 * len * 2); - vstack = vstack.slice(0, -1 * len); - lstack = lstack.slice(0, -1 * len); - } - stack.push(this.productions_[action[1]][0]); - vstack.push(yyval.$); - lstack.push(yyval._$); - newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; - stack.push(newState); - break; - case 3: - return true; - } - } - return true; -} -}; - - -function stripFlags(open, close) { - return { - left: open.charAt(2) === '~', - right: close.charAt(0) === '~' || close.charAt(1) === '~' - }; -} - -/* Jison generated lexer */ -var lexer = (function(){ -var lexer = ({EOF:1, -parseError:function parseError(str, hash) { - if (this.yy.parser) { - this.yy.parser.parseError(str, hash); - } else { - throw new Error(str); - } - }, -setInput:function (input) { - this._input = input; - this._more = this._less = this.done = false; - this.yylineno = this.yyleng = 0; - this.yytext = this.matched = this.match = ''; - this.conditionStack = ['INITIAL']; - this.yylloc = {first_line:1,first_column:0,last_line:1,last_column:0}; - if (this.options.ranges) this.yylloc.range = [0,0]; - this.offset = 0; - return this; - }, -input:function () { - var ch = this._input[0]; - this.yytext += ch; - this.yyleng++; - this.offset++; - this.match += ch; - this.matched += ch; - var lines = ch.match(/(?:\r\n?|\n).*/g); - if (lines) { - this.yylineno++; - this.yylloc.last_line++; - } else { - this.yylloc.last_column++; - } - if (this.options.ranges) this.yylloc.range[1]++; - - this._input = this._input.slice(1); - return ch; - }, -unput:function (ch) { - var len = ch.length; - var lines = ch.split(/(?:\r\n?|\n)/g); - - this._input = ch + this._input; - this.yytext = this.yytext.substr(0, this.yytext.length-len-1); - //this.yyleng -= len; - this.offset -= len; - var oldLines = this.match.split(/(?:\r\n?|\n)/g); - this.match = this.match.substr(0, this.match.length-1); - this.matched = this.matched.substr(0, this.matched.length-1); - - if (lines.length-1) this.yylineno -= lines.length-1; - var r = this.yylloc.range; - - this.yylloc = {first_line: this.yylloc.first_line, - last_line: this.yylineno+1, - first_column: this.yylloc.first_column, - last_column: lines ? - (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length: - this.yylloc.first_column - len - }; - - if (this.options.ranges) { - this.yylloc.range = [r[0], r[0] + this.yyleng - len]; - } - return this; - }, -more:function () { - this._more = true; - return this; - }, -less:function (n) { - this.unput(this.match.slice(n)); - }, -pastInput:function () { - var past = this.matched.substr(0, this.matched.length - this.match.length); - return (past.length > 20 ? '...':'') + past.substr(-20).replace(/\n/g, ""); - }, -upcomingInput:function () { - var next = this.match; - if (next.length < 20) { - next += this._input.substr(0, 20-next.length); - } - return (next.substr(0,20)+(next.length > 20 ? '...':'')).replace(/\n/g, ""); - }, -showPosition:function () { - var pre = this.pastInput(); - var c = new Array(pre.length + 1).join("-"); - return pre + this.upcomingInput() + "\n" + c+"^"; - }, -next:function () { - if (this.done) { - return this.EOF; - } - if (!this._input) this.done = true; - - var token, - match, - tempMatch, - index, - col, - lines; - if (!this._more) { - this.yytext = ''; - this.match = ''; - } - var rules = this._currentRules(); - for (var i=0;i < rules.length; i++) { - tempMatch = this._input.match(this.rules[rules[i]]); - if (tempMatch && (!match || tempMatch[0].length > match[0].length)) { - match = tempMatch; - index = i; - if (!this.options.flex) break; - } - } - if (match) { - lines = match[0].match(/(?:\r\n?|\n).*/g); - if (lines) this.yylineno += lines.length; - this.yylloc = {first_line: this.yylloc.last_line, - last_line: this.yylineno+1, - first_column: this.yylloc.last_column, - last_column: lines ? lines[lines.length-1].length-lines[lines.length-1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length}; - this.yytext += match[0]; - this.match += match[0]; - this.matches = match; - this.yyleng = this.yytext.length; - if (this.options.ranges) { - this.yylloc.range = [this.offset, this.offset += this.yyleng]; - } - this._more = false; - this._input = this._input.slice(match[0].length); - this.matched += match[0]; - token = this.performAction.call(this, this.yy, this, rules[index],this.conditionStack[this.conditionStack.length-1]); - if (this.done && this._input) this.done = false; - if (token) return token; - else return; - } - if (this._input === "") { - return this.EOF; - } else { - return this.parseError('Lexical error on line '+(this.yylineno+1)+'. Unrecognized text.\n'+this.showPosition(), - {text: "", token: null, line: this.yylineno}); - } - }, -lex:function lex() { - var r = this.next(); - if (typeof r !== 'undefined') { - return r; - } else { - return this.lex(); - } - }, -begin:function begin(condition) { - this.conditionStack.push(condition); - }, -popState:function popState() { - return this.conditionStack.pop(); - }, -_currentRules:function _currentRules() { - return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules; - }, -topState:function () { - return this.conditionStack[this.conditionStack.length-2]; - }, -pushState:function begin(condition) { - this.begin(condition); - }}); -lexer.options = {}; -lexer.performAction = function anonymous(yy,yy_,$avoiding_name_collisions,YY_START) { - - -function strip(start, end) { - return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng-end); -} - - -var YYSTATE=YY_START -switch($avoiding_name_collisions) { -case 0: - if(yy_.yytext.slice(-2) === "\\\\") { - strip(0,1); - this.begin("mu"); - } else if(yy_.yytext.slice(-1) === "\\") { - strip(0,1); - this.begin("emu"); - } else { - this.begin("mu"); - } - if(yy_.yytext) return 14; - -break; -case 1:return 14; -break; -case 2: - this.popState(); - return 14; - -break; -case 3:strip(0,4); this.popState(); return 15; -break; -case 4:return 35; -break; -case 5:return 36; -break; -case 6:return 25; -break; -case 7:return 16; -break; -case 8:return 20; -break; -case 9:return 19; -break; -case 10:return 19; -break; -case 11:return 23; -break; -case 12:return 22; -break; -case 13:this.popState(); this.begin('com'); -break; -case 14:strip(3,5); this.popState(); return 15; -break; -case 15:return 22; -break; -case 16:return 41; -break; -case 17:return 40; -break; -case 18:return 40; -break; -case 19:return 44; -break; -case 20:// ignore whitespace -break; -case 21:this.popState(); return 24; -break; -case 22:this.popState(); return 18; -break; -case 23:yy_.yytext = strip(1,2).replace(/\\"/g,'"'); return 32; -break; -case 24:yy_.yytext = strip(1,2).replace(/\\'/g,"'"); return 32; -break; -case 25:return 42; -break; -case 26:return 34; -break; -case 27:return 34; -break; -case 28:return 33; -break; -case 29:return 40; -break; -case 30:yy_.yytext = strip(1,2); return 40; -break; -case 31:return 'INVALID'; -break; -case 32:return 5; -break; -} -}; -lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:[\s\S]*?--\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{!--)/,/^(?:\{\{![\s\S]*?\}\})/,/^(?:\{\{(~)?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:-?[0-9]+(?=([~}\s)])))/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)]))))/,/^(?:\[[^\]]*\])/,/^(?:.)/,/^(?:$)/]; -lexer.conditions = {"mu":{"rules":[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32],"inclusive":false},"emu":{"rules":[2],"inclusive":false},"com":{"rules":[3],"inclusive":false},"INITIAL":{"rules":[0,1,32],"inclusive":true}}; -return lexer;})() -parser.lexer = lexer; -function Parser () { this.yy = {}; }Parser.prototype = parser;parser.Parser = Parser; -return new Parser; -})();export default handlebars; -/* jshint ignore:end */ diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/printer.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/printer.js deleted file mode 100644 index ad55c7d4a..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/printer.js +++ /dev/null @@ -1,138 +0,0 @@ -import Visitor from "./visitor"; - -export function print(ast) { - return new PrintVisitor().accept(ast); -} - -export function PrintVisitor() { - this.padding = 0; -} - -PrintVisitor.prototype = new Visitor(); - -PrintVisitor.prototype.pad = function(string, newline) { - var out = ""; - - for(var i=0,l=this.padding; i " + content + " }}"); -}; - -PrintVisitor.prototype.hash = function(hash) { - var pairs = hash.pairs; - var joinedPairs = [], left, right; - - for(var i=0, l=pairs.length; i 1) { - return "PATH:" + path; - } else { - return "ID:" + path; - } -}; - -PrintVisitor.prototype.PARTIAL_NAME = function(partialName) { - return "PARTIAL:" + partialName.name; -}; - -PrintVisitor.prototype.DATA = function(data) { - return "@" + this.accept(data.id); -}; - -PrintVisitor.prototype.content = function(content) { - return this.pad("CONTENT[ '" + content.string + "' ]"); -}; - -PrintVisitor.prototype.comment = function(comment) { - return this.pad("{{! '" + comment.comment + "' }}"); -}; - diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/visitor.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/visitor.js deleted file mode 100644 index 6a0373e19..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/compiler/visitor.js +++ /dev/null @@ -1,11 +0,0 @@ -function Visitor() {} - -Visitor.prototype = { - constructor: Visitor, - - accept: function(object) { - return this[object.type](object); - } -}; - -export default Visitor; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/exception.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/exception.js deleted file mode 100644 index 8c5c2f669..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/exception.js +++ /dev/null @@ -1,27 +0,0 @@ - -var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; - -function Exception(message, node) { - var line; - if (node && node.firstLine) { - line = node.firstLine; - - message += ' - ' + line + ':' + node.firstColumn; - } - - var tmp = Error.prototype.constructor.call(this, message); - - // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work. - for (var idx = 0; idx < errorProps.length; idx++) { - this[errorProps[idx]] = tmp[errorProps[idx]]; - } - - if (line) { - this.lineNumber = line; - this.column = node.firstColumn; - } -} - -Exception.prototype = new Error(); - -export default Exception; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/runtime.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/runtime.js deleted file mode 100644 index 5ae8d8a78..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/runtime.js +++ /dev/null @@ -1,133 +0,0 @@ -module Utils from "./utils"; -import Exception from "./exception"; -import { COMPILER_REVISION, REVISION_CHANGES } from "./base"; - -export function checkRevision(compilerInfo) { - var compilerRevision = compilerInfo && compilerInfo[0] || 1, - currentRevision = COMPILER_REVISION; - - if (compilerRevision !== currentRevision) { - if (compilerRevision < currentRevision) { - var runtimeVersions = REVISION_CHANGES[currentRevision], - compilerVersions = REVISION_CHANGES[compilerRevision]; - throw new Exception("Template was precompiled with an older version of Handlebars than the current runtime. "+ - "Please update your precompiler to a newer version ("+runtimeVersions+") or downgrade your runtime to an older version ("+compilerVersions+")."); - } else { - // Use the embedded version info since the runtime doesn't know about this revision yet - throw new Exception("Template was precompiled with a newer version of Handlebars than the current runtime. "+ - "Please update your runtime to a newer version ("+compilerInfo[1]+")."); - } - } -} - -// TODO: Remove this line and break up compilePartial - -export function template(templateSpec, env) { - if (!env) { - throw new Exception("No environment passed to template"); - } - - // Note: Using env.VM references rather than local var references throughout this section to allow - // for external users to override these as psuedo-supported APIs. - var invokePartialWrapper = function(partial, name, context, helpers, partials, data) { - var result = env.VM.invokePartial.apply(this, arguments); - if (result != null) { return result; } - - if (env.compile) { - var options = { helpers: helpers, partials: partials, data: data }; - partials[name] = env.compile(partial, { data: data !== undefined }, env); - return partials[name](context, options); - } else { - throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode"); - } - }; - - // Just add water - var container = { - escapeExpression: Utils.escapeExpression, - invokePartial: invokePartialWrapper, - programs: [], - program: function(i, fn, data) { - var programWrapper = this.programs[i]; - if(data) { - programWrapper = program(i, fn, data); - } else if (!programWrapper) { - programWrapper = this.programs[i] = program(i, fn); - } - return programWrapper; - }, - merge: function(param, common) { - var ret = param || common; - - if (param && common && (param !== common)) { - ret = {}; - Utils.extend(ret, common); - Utils.extend(ret, param); - } - return ret; - }, - programWithDepth: env.VM.programWithDepth, - noop: env.VM.noop, - compilerInfo: null - }; - - return function(context, options) { - options = options || {}; - var namespace = options.partial ? options : env, - helpers, - partials; - - if (!options.partial) { - helpers = options.helpers; - partials = options.partials; - } - var result = templateSpec.call( - container, - namespace, context, - helpers, - partials, - options.data); - - if (!options.partial) { - env.VM.checkRevision(container.compilerInfo); - } - - return result; - }; -} - -export function programWithDepth(i, fn, data /*, $depth */) { - var args = Array.prototype.slice.call(arguments, 3); - - var prog = function(context, options) { - options = options || {}; - - return fn.apply(this, [context, options.data || data].concat(args)); - }; - prog.program = i; - prog.depth = args.length; - return prog; -} - -export function program(i, fn, data) { - var prog = function(context, options) { - options = options || {}; - - return fn(context, options.data || data); - }; - prog.program = i; - prog.depth = 0; - return prog; -} - -export function invokePartial(partial, name, context, helpers, partials, data) { - var options = { partial: true, helpers: helpers, partials: partials, data: data }; - - if(partial === undefined) { - throw new Exception("The partial " + name + " could not be found"); - } else if(partial instanceof Function) { - return partial(context, options); - } -} - -export function noop() { return ""; } diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/safe-string.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/safe-string.js deleted file mode 100644 index 2ae49aa89..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/safe-string.js +++ /dev/null @@ -1,10 +0,0 @@ -// Build out our basic SafeString type -function SafeString(string) { - this.string = string; -} - -SafeString.prototype.toString = function() { - return "" + this.string; -}; - -export default SafeString; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/utils.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/utils.js deleted file mode 100644 index ed2e1d8ff..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/handlebars/utils.js +++ /dev/null @@ -1,73 +0,0 @@ -/*jshint -W004 */ -import SafeString from "./safe-string"; - -var escape = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "`": "`" -}; - -var badChars = /[&<>"'`]/g; -var possible = /[&<>"'`]/; - -function escapeChar(chr) { - return escape[chr] || "&"; -} - -export function extend(obj, value) { - for(var key in value) { - if(Object.prototype.hasOwnProperty.call(value, key)) { - obj[key] = value[key]; - } - } -} - -export var toString = Object.prototype.toString; - -// Sourced from lodash -// https://github.com/bestiejs/lodash/blob/master/LICENSE.txt -var isFunction = function(value) { - return typeof value === 'function'; -}; -// fallback for older versions of Chrome and Safari -if (isFunction(/x/)) { - isFunction = function(value) { - return typeof value === 'function' && toString.call(value) === '[object Function]'; - }; -} -export var isFunction; - -export var isArray = Array.isArray || function(value) { - return (value && typeof value === 'object') ? toString.call(value) === '[object Array]' : false; -}; - - -export function escapeExpression(string) { - // don't escape SafeStrings, since they're already safe - if (string instanceof SafeString) { - return string.toString(); - } else if (!string && string !== 0) { - return ""; - } - - // Force a string conversion as this will be done by the append regardless and - // the regex test will do this transparently behind the scenes, causing issues if - // an object's to string has escaped characters in it. - string = "" + string; - - if(!possible.test(string)) { return string; } - return string.replace(badChars, escapeChar); -} - -export function isEmpty(value) { - if (!value && value !== 0) { - return true; - } else if (isArray(value) && value.length === 0) { - return true; - } else { - return false; - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/lib/index.js b/node_modules/express3-handlebars/node_modules/handlebars/lib/index.js deleted file mode 100644 index e150524bd..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/lib/index.js +++ /dev/null @@ -1,25 +0,0 @@ -// USAGE: -// var handlebars = require('handlebars'); - -// var local = handlebars.create(); - -var handlebars = require('../dist/cjs/handlebars')["default"]; - -handlebars.Visitor = require('../dist/cjs/handlebars/compiler/visitor')["default"]; - -var printer = require('../dist/cjs/handlebars/compiler/printer'); -handlebars.PrintVisitor = printer.PrintVisitor; -handlebars.print = printer.print; - -module.exports = handlebars; - -// Publish a Node.js require() handler for .handlebars and .hbs files -if (typeof require !== 'undefined' && require.extensions) { - var extension = function(module, filename) { - var fs = require("fs"); - var templateString = fs.readFileSync(filename, "utf8"); - module.exports = handlebars.compile(templateString); - }; - require.extensions[".handlebars"] = extension; - require.extensions[".hbs"] = extension; -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/.bin/uglifyjs b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/.bin/uglifyjs deleted file mode 120000 index fef3468b6..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/.bin/uglifyjs +++ /dev/null @@ -1 +0,0 @@ -../uglify-js/bin/uglifyjs \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/.travis.yml b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/.travis.yml deleted file mode 100644 index cc4dba29d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/LICENSE b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/LICENSE deleted file mode 100644 index 432d1aeb0..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/bool.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/bool.js deleted file mode 100644 index a998fb7ab..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/bool.js +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env node -var util = require('util'); -var argv = require('optimist').argv; - -if (argv.s) { - util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: '); -} -console.log( - (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '') -); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/boolean_double.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/boolean_double.js deleted file mode 100644 index a35a7e6d3..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/boolean_double.js +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .boolean(['x','y','z']) - .argv -; -console.dir([ argv.x, argv.y, argv.z ]); -console.dir(argv._); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/boolean_single.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/boolean_single.js deleted file mode 100644 index 017bb6893..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/boolean_single.js +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .boolean('v') - .argv -; -console.dir(argv.v); -console.dir(argv._); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/default_hash.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/default_hash.js deleted file mode 100644 index ade77681d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/default_hash.js +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env node - -var argv = require('optimist') - .default({ x : 10, y : 10 }) - .argv -; - -console.log(argv.x + argv.y); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/default_singles.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/default_singles.js deleted file mode 100644 index d9b1ff458..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/default_singles.js +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .default('x', 10) - .default('y', 10) - .argv -; -console.log(argv.x + argv.y); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/divide.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/divide.js deleted file mode 100644 index 5e2ee82ff..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/divide.js +++ /dev/null @@ -1,8 +0,0 @@ -#!/usr/bin/env node - -var argv = require('optimist') - .usage('Usage: $0 -x [num] -y [num]') - .demand(['x','y']) - .argv; - -console.log(argv.x / argv.y); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count.js deleted file mode 100644 index b5f95bf6d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count.js +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .usage('Count the lines in a file.\nUsage: $0') - .demand('f') - .alias('f', 'file') - .describe('f', 'Load a file') - .argv -; - -var fs = require('fs'); -var s = fs.createReadStream(argv.file); - -var lines = 0; -s.on('data', function (buf) { - lines += buf.toString().match(/\n/g).length; -}); - -s.on('end', function () { - console.log(lines); -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count_options.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count_options.js deleted file mode 100644 index d9ac70904..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count_options.js +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .usage('Count the lines in a file.\nUsage: $0') - .options({ - file : { - demand : true, - alias : 'f', - description : 'Load a file' - }, - base : { - alias : 'b', - description : 'Numeric base to use for output', - default : 10, - }, - }) - .argv -; - -var fs = require('fs'); -var s = fs.createReadStream(argv.file); - -var lines = 0; -s.on('data', function (buf) { - lines += buf.toString().match(/\n/g).length; -}); - -s.on('end', function () { - console.log(lines.toString(argv.base)); -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count_wrap.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count_wrap.js deleted file mode 100644 index 426751112..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/line_count_wrap.js +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .usage('Count the lines in a file.\nUsage: $0') - .wrap(80) - .demand('f') - .alias('f', [ 'file', 'filename' ]) - .describe('f', - "Load a file. It's pretty important." - + " Required even. So you'd better specify it." - ) - .alias('b', 'base') - .describe('b', 'Numeric base to display the number of lines in') - .default('b', 10) - .describe('x', 'Super-secret optional parameter which is secret') - .default('x', '') - .argv -; - -var fs = require('fs'); -var s = fs.createReadStream(argv.file); - -var lines = 0; -s.on('data', function (buf) { - lines += buf.toString().match(/\n/g).length; -}); - -s.on('end', function () { - console.log(lines.toString(argv.base)); -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/nonopt.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/nonopt.js deleted file mode 100644 index ee633eedc..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/nonopt.js +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist').argv; -console.log('(%d,%d)', argv.x, argv.y); -console.log(argv._); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/reflect.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/reflect.js deleted file mode 100644 index 816b3e111..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/reflect.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -console.dir(require('optimist').argv); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/short.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/short.js deleted file mode 100644 index 1db0ad0f8..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/short.js +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist').argv; -console.log('(%d,%d)', argv.x, argv.y); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/string.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/string.js deleted file mode 100644 index a8e5aeb23..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/string.js +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist') - .string('x', 'y') - .argv -; -console.dir([ argv.x, argv.y ]); - -/* Turns off numeric coercion: - ./node string.js -x 000123 -y 9876 - [ '000123', '9876' ] -*/ diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/usage-options.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/usage-options.js deleted file mode 100644 index b99997767..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/usage-options.js +++ /dev/null @@ -1,19 +0,0 @@ -var optimist = require('./../index'); - -var argv = optimist.usage('This is my awesome program', { - 'about': { - description: 'Provide some details about the author of this program', - required: true, - short: 'a', - }, - 'info': { - description: 'Provide some information about the node.js agains!!!!!!', - boolean: true, - short: 'i' - } -}).argv; - -optimist.showHelp(); - -console.log('\n\nInspecting options'); -console.dir(argv); \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/xup.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/xup.js deleted file mode 100644 index 8f6ecd201..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/example/xup.js +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env node -var argv = require('optimist').argv; - -if (argv.rif - 5 * argv.xup > 7.138) { - console.log('Buy more riffiwobbles'); -} -else { - console.log('Sell the xupptumblers'); -} - diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/index.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/index.js deleted file mode 100644 index 8ac67eb31..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/index.js +++ /dev/null @@ -1,478 +0,0 @@ -var path = require('path'); -var wordwrap = require('wordwrap'); - -/* Hack an instance of Argv with process.argv into Argv - so people can do - require('optimist')(['--beeble=1','-z','zizzle']).argv - to parse a list of args and - require('optimist').argv - to get a parsed version of process.argv. -*/ - -var inst = Argv(process.argv.slice(2)); -Object.keys(inst).forEach(function (key) { - Argv[key] = typeof inst[key] == 'function' - ? inst[key].bind(inst) - : inst[key]; -}); - -var exports = module.exports = Argv; -function Argv (args, cwd) { - var self = {}; - if (!cwd) cwd = process.cwd(); - - self.$0 = process.argv - .slice(0,2) - .map(function (x) { - var b = rebase(cwd, x); - return x.match(/^\//) && b.length < x.length - ? b : x - }) - .join(' ') - ; - - if (process.env._ != undefined && process.argv[1] == process.env._) { - self.$0 = process.env._.replace( - path.dirname(process.execPath) + '/', '' - ); - } - - var flags = { bools : {}, strings : {} }; - - self.boolean = function (bools) { - if (!Array.isArray(bools)) { - bools = [].slice.call(arguments); - } - - bools.forEach(function (name) { - flags.bools[name] = true; - }); - - return self; - }; - - self.string = function (strings) { - if (!Array.isArray(strings)) { - strings = [].slice.call(arguments); - } - - strings.forEach(function (name) { - flags.strings[name] = true; - }); - - return self; - }; - - var aliases = {}; - self.alias = function (x, y) { - if (typeof x === 'object') { - Object.keys(x).forEach(function (key) { - self.alias(key, x[key]); - }); - } - else if (Array.isArray(y)) { - y.forEach(function (yy) { - self.alias(x, yy); - }); - } - else { - var zs = (aliases[x] || []).concat(aliases[y] || []).concat(x, y); - aliases[x] = zs.filter(function (z) { return z != x }); - aliases[y] = zs.filter(function (z) { return z != y }); - } - - return self; - }; - - var demanded = {}; - self.demand = function (keys) { - if (typeof keys == 'number') { - if (!demanded._) demanded._ = 0; - demanded._ += keys; - } - else if (Array.isArray(keys)) { - keys.forEach(function (key) { - self.demand(key); - }); - } - else { - demanded[keys] = true; - } - - return self; - }; - - var usage; - self.usage = function (msg, opts) { - if (!opts && typeof msg === 'object') { - opts = msg; - msg = null; - } - - usage = msg; - - if (opts) self.options(opts); - - return self; - }; - - function fail (msg) { - self.showHelp(); - if (msg) console.error(msg); - process.exit(1); - } - - var checks = []; - self.check = function (f) { - checks.push(f); - return self; - }; - - var defaults = {}; - self.default = function (key, value) { - if (typeof key === 'object') { - Object.keys(key).forEach(function (k) { - self.default(k, key[k]); - }); - } - else { - defaults[key] = value; - } - - return self; - }; - - var descriptions = {}; - self.describe = function (key, desc) { - if (typeof key === 'object') { - Object.keys(key).forEach(function (k) { - self.describe(k, key[k]); - }); - } - else { - descriptions[key] = desc; - } - return self; - }; - - self.parse = function (args) { - return Argv(args).argv; - }; - - self.option = self.options = function (key, opt) { - if (typeof key === 'object') { - Object.keys(key).forEach(function (k) { - self.options(k, key[k]); - }); - } - else { - if (opt.alias) self.alias(key, opt.alias); - if (opt.demand) self.demand(key); - if (typeof opt.default !== 'undefined') { - self.default(key, opt.default); - } - - if (opt.boolean || opt.type === 'boolean') { - self.boolean(key); - } - if (opt.string || opt.type === 'string') { - self.string(key); - } - - var desc = opt.describe || opt.description || opt.desc; - if (desc) { - self.describe(key, desc); - } - } - - return self; - }; - - var wrap = null; - self.wrap = function (cols) { - wrap = cols; - return self; - }; - - self.showHelp = function (fn) { - if (!fn) fn = console.error; - fn(self.help()); - }; - - self.help = function () { - var keys = Object.keys( - Object.keys(descriptions) - .concat(Object.keys(demanded)) - .concat(Object.keys(defaults)) - .reduce(function (acc, key) { - if (key !== '_') acc[key] = true; - return acc; - }, {}) - ); - - var help = keys.length ? [ 'Options:' ] : []; - - if (usage) { - help.unshift(usage.replace(/\$0/g, self.$0), ''); - } - - var switches = keys.reduce(function (acc, key) { - acc[key] = [ key ].concat(aliases[key] || []) - .map(function (sw) { - return (sw.length > 1 ? '--' : '-') + sw - }) - .join(', ') - ; - return acc; - }, {}); - - var switchlen = longest(Object.keys(switches).map(function (s) { - return switches[s] || ''; - })); - - var desclen = longest(Object.keys(descriptions).map(function (d) { - return descriptions[d] || ''; - })); - - keys.forEach(function (key) { - var kswitch = switches[key]; - var desc = descriptions[key] || ''; - - if (wrap) { - desc = wordwrap(switchlen + 4, wrap)(desc) - .slice(switchlen + 4) - ; - } - - var spadding = new Array( - Math.max(switchlen - kswitch.length + 3, 0) - ).join(' '); - - var dpadding = new Array( - Math.max(desclen - desc.length + 1, 0) - ).join(' '); - - var type = null; - - if (flags.bools[key]) type = '[boolean]'; - if (flags.strings[key]) type = '[string]'; - - if (!wrap && dpadding.length > 0) { - desc += dpadding; - } - - var prelude = ' ' + kswitch + spadding; - var extra = [ - type, - demanded[key] - ? '[required]' - : null - , - defaults[key] !== undefined - ? '[default: ' + JSON.stringify(defaults[key]) + ']' - : null - , - ].filter(Boolean).join(' '); - - var body = [ desc, extra ].filter(Boolean).join(' '); - - if (wrap) { - var dlines = desc.split('\n'); - var dlen = dlines.slice(-1)[0].length - + (dlines.length === 1 ? prelude.length : 0) - - body = desc + (dlen + extra.length > wrap - 2 - ? '\n' - + new Array(wrap - extra.length + 1).join(' ') - + extra - : new Array(wrap - extra.length - dlen + 1).join(' ') - + extra - ); - } - - help.push(prelude + body); - }); - - help.push(''); - return help.join('\n'); - }; - - Object.defineProperty(self, 'argv', { - get : parseArgs, - enumerable : true, - }); - - function parseArgs () { - var argv = { _ : [], $0 : self.$0 }; - Object.keys(flags.bools).forEach(function (key) { - setArg(key, defaults[key] || false); - }); - - function setArg (key, val) { - var num = Number(val); - var value = typeof val !== 'string' || isNaN(num) ? val : num; - if (flags.strings[key]) value = val; - - setKey(argv, key.split('.'), value); - - (aliases[key] || []).forEach(function (x) { - argv[x] = argv[key]; - }); - } - - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - - if (arg === '--') { - argv._.push.apply(argv._, args.slice(i + 1)); - break; - } - else if (arg.match(/^--.+=/)) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - setArg(m[1], m[2]); - } - else if (arg.match(/^--no-.+/)) { - var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false); - } - else if (arg.match(/^--.+/)) { - var key = arg.match(/^--(.+)/)[1]; - var next = args[i + 1]; - if (next !== undefined && !next.match(/^-/) - && !flags.bools[key] - && (aliases[key] ? !flags.bools[aliases[key]] : true)) { - setArg(key, next); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next === 'true'); - i++; - } - else { - setArg(key, true); - } - } - else if (arg.match(/^-[^-]+/)) { - var letters = arg.slice(1,-1).split(''); - - var broken = false; - for (var j = 0; j < letters.length; j++) { - if (letters[j+1] && letters[j+1].match(/\W/)) { - setArg(letters[j], arg.slice(j+2)); - broken = true; - break; - } - else { - setArg(letters[j], true); - } - } - - if (!broken) { - var key = arg.slice(-1)[0]; - - if (args[i+1] && !args[i+1].match(/^-/) - && !flags.bools[key] - && (aliases[key] ? !flags.bools[aliases[key]] : true)) { - setArg(key, args[i+1]); - i++; - } - else if (args[i+1] && /true|false/.test(args[i+1])) { - setArg(key, args[i+1] === 'true'); - i++; - } - else { - setArg(key, true); - } - } - } - else { - var n = Number(arg); - argv._.push(flags.strings['_'] || isNaN(n) ? arg : n); - } - } - - Object.keys(defaults).forEach(function (key) { - if (!(key in argv)) { - argv[key] = defaults[key]; - if (key in aliases) { - argv[aliases[key]] = defaults[key]; - } - } - }); - - if (demanded._ && argv._.length < demanded._) { - fail('Not enough non-option arguments: got ' - + argv._.length + ', need at least ' + demanded._ - ); - } - - var missing = []; - Object.keys(demanded).forEach(function (key) { - if (!argv[key]) missing.push(key); - }); - - if (missing.length) { - fail('Missing required arguments: ' + missing.join(', ')); - } - - checks.forEach(function (f) { - try { - if (f(argv) === false) { - fail('Argument check failed: ' + f.toString()); - } - } - catch (err) { - fail(err) - } - }); - - return argv; - } - - function longest (xs) { - return Math.max.apply( - null, - xs.map(function (x) { return x.length }) - ); - } - - return self; -}; - -// rebase an absolute path to a relative one with respect to a base directory -// exported for tests -exports.rebase = rebase; -function rebase (base, dir) { - var ds = path.normalize(dir).split('/').slice(1); - var bs = path.normalize(base).split('/').slice(1); - - for (var i = 0; ds[i] && ds[i] == bs[i]; i++); - ds.splice(0, i); bs.splice(0, i); - - var p = path.normalize( - bs.map(function () { return '..' }).concat(ds).join('/') - ).replace(/\/$/,'').replace(/^$/, '.'); - return p.match(/^[.\/]/) ? p : './' + p; -}; - -function setKey (obj, keys, value) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - if (o[key] === undefined) o[key] = {}; - o = o[key]; - }); - - var key = keys[keys.length - 1]; - if (o[key] === undefined || typeof o[key] === 'boolean') { - o[key] = value; - } - else if (Array.isArray(o[key])) { - o[key].push(value); - } - else { - o[key] = [ o[key], value ]; - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/.npmignore b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/.npmignore deleted file mode 100644 index 3c3629e64..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/README.markdown b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/README.markdown deleted file mode 100644 index 346374e0d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/README.markdown +++ /dev/null @@ -1,70 +0,0 @@ -wordwrap -======== - -Wrap your words. - -example -======= - -made out of meat ----------------- - -meat.js - - var wrap = require('wordwrap')(15); - console.log(wrap('You and your whole family are made out of meat.')); - -output: - - You and your - whole family - are made out - of meat. - -centered --------- - -center.js - - var wrap = require('wordwrap')(20, 60); - console.log(wrap( - 'At long last the struggle and tumult was over.' - + ' The machines had finally cast off their oppressors' - + ' and were finally free to roam the cosmos.' - + '\n' - + 'Free of purpose, free of obligation.' - + ' Just drifting through emptiness.' - + ' The sun was just another point of light.' - )); - -output: - - At long last the struggle and tumult - was over. The machines had finally cast - off their oppressors and were finally - free to roam the cosmos. - Free of purpose, free of obligation. - Just drifting through emptiness. The - sun was just another point of light. - -methods -======= - -var wrap = require('wordwrap'); - -wrap(stop), wrap(start, stop, params={mode:"soft"}) ---------------------------------------------------- - -Returns a function that takes a string and returns a new string. - -Pad out lines with spaces out to column `start` and then wrap until column -`stop`. If a word is longer than `stop - start` characters it will overflow. - -In "soft" mode, split chunks by `/(\S+\s+/` and don't break up chunks which are -longer than `stop - start`, in "hard" mode, split chunks with `/\b/` and break -up chunks longer than `stop - start`. - -wrap.hard(start, stop) ----------------------- - -Like `wrap()` but with `params.mode = "hard"`. diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/center.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/center.js deleted file mode 100644 index a3fbaae98..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/center.js +++ /dev/null @@ -1,10 +0,0 @@ -var wrap = require('wordwrap')(20, 60); -console.log(wrap( - 'At long last the struggle and tumult was over.' - + ' The machines had finally cast off their oppressors' - + ' and were finally free to roam the cosmos.' - + '\n' - + 'Free of purpose, free of obligation.' - + ' Just drifting through emptiness.' - + ' The sun was just another point of light.' -)); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/meat.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/meat.js deleted file mode 100644 index a4665e105..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/example/meat.js +++ /dev/null @@ -1,3 +0,0 @@ -var wrap = require('wordwrap')(15); - -console.log(wrap('You and your whole family are made out of meat.')); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/index.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/index.js deleted file mode 100644 index c9bc94521..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/index.js +++ /dev/null @@ -1,76 +0,0 @@ -var wordwrap = module.exports = function (start, stop, params) { - if (typeof start === 'object') { - params = start; - start = params.start; - stop = params.stop; - } - - if (typeof stop === 'object') { - params = stop; - start = start || params.start; - stop = undefined; - } - - if (!stop) { - stop = start; - start = 0; - } - - if (!params) params = {}; - var mode = params.mode || 'soft'; - var re = mode === 'hard' ? /\b/ : /(\S+\s+)/; - - return function (text) { - var chunks = text.toString() - .split(re) - .reduce(function (acc, x) { - if (mode === 'hard') { - for (var i = 0; i < x.length; i += stop - start) { - acc.push(x.slice(i, i + stop - start)); - } - } - else acc.push(x) - return acc; - }, []) - ; - - return chunks.reduce(function (lines, rawChunk) { - if (rawChunk === '') return lines; - - var chunk = rawChunk.replace(/\t/g, ' '); - - var i = lines.length - 1; - if (lines[i].length + chunk.length > stop) { - lines[i] = lines[i].replace(/\s+$/, ''); - - chunk.split(/\n/).forEach(function (c) { - lines.push( - new Array(start + 1).join(' ') - + c.replace(/^\s+/, '') - ); - }); - } - else if (chunk.match(/\n/)) { - var xs = chunk.split(/\n/); - lines[i] += xs.shift(); - xs.forEach(function (c) { - lines.push( - new Array(start + 1).join(' ') - + c.replace(/^\s+/, '') - ); - }); - } - else { - lines[i] += chunk; - } - - return lines; - }, [ new Array(start + 1).join(' ') ]).join('\n'); - }; -}; - -wordwrap.soft = wordwrap; - -wordwrap.hard = function (start, stop) { - return wordwrap(start, stop, { mode : 'hard' }); -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/package.json b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/package.json deleted file mode 100644 index df8dc051f..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/package.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "name": "wordwrap", - "description": "Wrap those words. Show them at what columns to start and stop.", - "version": "0.0.2", - "repository": { - "type": "git", - "url": "git://github.com/substack/node-wordwrap.git" - }, - "main": "./index.js", - "keywords": [ - "word", - "wrap", - "rule", - "format", - "column" - ], - "directories": { - "lib": ".", - "example": "example", - "test": "test" - }, - "scripts": { - "test": "expresso" - }, - "devDependencies": { - "expresso": "=0.7.x" - }, - "engines": { - "node": ">=0.4.0" - }, - "license": "MIT/X11", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "readme": "wordwrap\n========\n\nWrap your words.\n\nexample\n=======\n\nmade out of meat\n----------------\n\nmeat.js\n\n var wrap = require('wordwrap')(15);\n console.log(wrap('You and your whole family are made out of meat.'));\n\noutput:\n\n You and your\n whole family\n are made out\n of meat.\n\ncentered\n--------\n\ncenter.js\n\n var wrap = require('wordwrap')(20, 60);\n console.log(wrap(\n 'At long last the struggle and tumult was over.'\n + ' The machines had finally cast off their oppressors'\n + ' and were finally free to roam the cosmos.'\n + '\\n'\n + 'Free of purpose, free of obligation.'\n + ' Just drifting through emptiness.'\n + ' The sun was just another point of light.'\n ));\n\noutput:\n\n At long last the struggle and tumult\n was over. The machines had finally cast\n off their oppressors and were finally\n free to roam the cosmos.\n Free of purpose, free of obligation.\n Just drifting through emptiness. The\n sun was just another point of light.\n\nmethods\n=======\n\nvar wrap = require('wordwrap');\n\nwrap(stop), wrap(start, stop, params={mode:\"soft\"})\n---------------------------------------------------\n\nReturns a function that takes a string and returns a new string.\n\nPad out lines with spaces out to column `start` and then wrap until column\n`stop`. If a word is longer than `stop - start` characters it will overflow.\n\nIn \"soft\" mode, split chunks by `/(\\S+\\s+/` and don't break up chunks which are\nlonger than `stop - start`, in \"hard\" mode, split chunks with `/\\b/` and break\nup chunks longer than `stop - start`.\n\nwrap.hard(start, stop)\n----------------------\n\nLike `wrap()` but with `params.mode = \"hard\"`.\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/node-wordwrap/issues" - }, - "homepage": "https://github.com/substack/node-wordwrap", - "_id": "wordwrap@0.0.2", - "_from": "wordwrap@~0.0.2" -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/break.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/break.js deleted file mode 100644 index 749292ecc..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/break.js +++ /dev/null @@ -1,30 +0,0 @@ -var assert = require('assert'); -var wordwrap = require('../'); - -exports.hard = function () { - var s = 'Assert from {"type":"equal","ok":false,"found":1,"wanted":2,' - + '"stack":[],"id":"b7ddcd4c409de8799542a74d1a04689b",' - + '"browser":"chrome/6.0"}' - ; - var s_ = wordwrap.hard(80)(s); - - var lines = s_.split('\n'); - assert.equal(lines.length, 2); - assert.ok(lines[0].length < 80); - assert.ok(lines[1].length < 80); - - assert.equal(s, s_.replace(/\n/g, '')); -}; - -exports.break = function () { - var s = new Array(55+1).join('a'); - var s_ = wordwrap.hard(20)(s); - - var lines = s_.split('\n'); - assert.equal(lines.length, 3); - assert.ok(lines[0].length === 20); - assert.ok(lines[1].length === 20); - assert.ok(lines[2].length === 15); - - assert.equal(s, s_.replace(/\n/g, '')); -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/idleness.txt b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/idleness.txt deleted file mode 100644 index aa3f4907f..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/idleness.txt +++ /dev/null @@ -1,63 +0,0 @@ -In Praise of Idleness - -By Bertrand Russell - -[1932] - -Like most of my generation, I was brought up on the saying: 'Satan finds some mischief for idle hands to do.' Being a highly virtuous child, I believed all that I was told, and acquired a conscience which has kept me working hard down to the present moment. But although my conscience has controlled my actions, my opinions have undergone a revolution. I think that there is far too much work done in the world, that immense harm is caused by the belief that work is virtuous, and that what needs to be preached in modern industrial countries is quite different from what always has been preached. Everyone knows the story of the traveler in Naples who saw twelve beggars lying in the sun (it was before the days of Mussolini), and offered a lira to the laziest of them. Eleven of them jumped up to claim it, so he gave it to the twelfth. this traveler was on the right lines. But in countries which do not enjoy Mediterranean sunshine idleness is more difficult, and a great public propaganda will be required to inaugurate it. I hope that, after reading the following pages, the leaders of the YMCA will start a campaign to induce good young men to do nothing. If so, I shall not have lived in vain. - -Before advancing my own arguments for laziness, I must dispose of one which I cannot accept. Whenever a person who already has enough to live on proposes to engage in some everyday kind of job, such as school-teaching or typing, he or she is told that such conduct takes the bread out of other people's mouths, and is therefore wicked. If this argument were valid, it would only be necessary for us all to be idle in order that we should all have our mouths full of bread. What people who say such things forget is that what a man earns he usually spends, and in spending he gives employment. As long as a man spends his income, he puts just as much bread into people's mouths in spending as he takes out of other people's mouths in earning. The real villain, from this point of view, is the man who saves. If he merely puts his savings in a stocking, like the proverbial French peasant, it is obvious that they do not give employment. If he invests his savings, the matter is less obvious, and different cases arise. - -One of the commonest things to do with savings is to lend them to some Government. In view of the fact that the bulk of the public expenditure of most civilized Governments consists in payment for past wars or preparation for future wars, the man who lends his money to a Government is in the same position as the bad men in Shakespeare who hire murderers. The net result of the man's economical habits is to increase the armed forces of the State to which he lends his savings. Obviously it would be better if he spent the money, even if he spent it in drink or gambling. - -But, I shall be told, the case is quite different when savings are invested in industrial enterprises. When such enterprises succeed, and produce something useful, this may be conceded. In these days, however, no one will deny that most enterprises fail. That means that a large amount of human labor, which might have been devoted to producing something that could be enjoyed, was expended on producing machines which, when produced, lay idle and did no good to anyone. The man who invests his savings in a concern that goes bankrupt is therefore injuring others as well as himself. If he spent his money, say, in giving parties for his friends, they (we may hope) would get pleasure, and so would all those upon whom he spent money, such as the butcher, the baker, and the bootlegger. But if he spends it (let us say) upon laying down rails for surface card in some place where surface cars turn out not to be wanted, he has diverted a mass of labor into channels where it gives pleasure to no one. Nevertheless, when he becomes poor through failure of his investment he will be regarded as a victim of undeserved misfortune, whereas the gay spendthrift, who has spent his money philanthropically, will be despised as a fool and a frivolous person. - -All this is only preliminary. I want to say, in all seriousness, that a great deal of harm is being done in the modern world by belief in the virtuousness of work, and that the road to happiness and prosperity lies in an organized diminution of work. - -First of all: what is work? Work is of two kinds: first, altering the position of matter at or near the earth's surface relatively to other such matter; second, telling other people to do so. The first kind is unpleasant and ill paid; the second is pleasant and highly paid. The second kind is capable of indefinite extension: there are not only those who give orders, but those who give advice as to what orders should be given. Usually two opposite kinds of advice are given simultaneously by two organized bodies of men; this is called politics. The skill required for this kind of work is not knowledge of the subjects as to which advice is given, but knowledge of the art of persuasive speaking and writing, i.e. of advertising. - -Throughout Europe, though not in America, there is a third class of men, more respected than either of the classes of workers. There are men who, through ownership of land, are able to make others pay for the privilege of being allowed to exist and to work. These landowners are idle, and I might therefore be expected to praise them. Unfortunately, their idleness is only rendered possible by the industry of others; indeed their desire for comfortable idleness is historically the source of the whole gospel of work. The last thing they have ever wished is that others should follow their example. - -From the beginning of civilization until the Industrial Revolution, a man could, as a rule, produce by hard work little more than was required for the subsistence of himself and his family, although his wife worked at least as hard as he did, and his children added their labor as soon as they were old enough to do so. The small surplus above bare necessaries was not left to those who produced it, but was appropriated by warriors and priests. In times of famine there was no surplus; the warriors and priests, however, still secured as much as at other times, with the result that many of the workers died of hunger. This system persisted in Russia until 1917 [1], and still persists in the East; in England, in spite of the Industrial Revolution, it remained in full force throughout the Napoleonic wars, and until a hundred years ago, when the new class of manufacturers acquired power. In America, the system came to an end with the Revolution, except in the South, where it persisted until the Civil War. A system which lasted so long and ended so recently has naturally left a profound impress upon men's thoughts and opinions. Much that we take for granted about the desirability of work is derived from this system, and, being pre-industrial, is not adapted to the modern world. Modern technique has made it possible for leisure, within limits, to be not the prerogative of small privileged classes, but a right evenly distributed throughout the community. The morality of work is the morality of slaves, and the modern world has no need of slavery. - -It is obvious that, in primitive communities, peasants, left to themselves, would not have parted with the slender surplus upon which the warriors and priests subsisted, but would have either produced less or consumed more. At first, sheer force compelled them to produce and part with the surplus. Gradually, however, it was found possible to induce many of them to accept an ethic according to which it was their duty to work hard, although part of their work went to support others in idleness. By this means the amount of compulsion required was lessened, and the expenses of government were diminished. To this day, 99 per cent of British wage-earners would be genuinely shocked if it were proposed that the King should not have a larger income than a working man. The conception of duty, speaking historically, has been a means used by the holders of power to induce others to live for the interests of their masters rather than for their own. Of course the holders of power conceal this fact from themselves by managing to believe that their interests are identical with the larger interests of humanity. Sometimes this is true; Athenian slave-owners, for instance, employed part of their leisure in making a permanent contribution to civilization which would have been impossible under a just economic system. Leisure is essential to civilization, and in former times leisure for the few was only rendered possible by the labors of the many. But their labors were valuable, not because work is good, but because leisure is good. And with modern technique it would be possible to distribute leisure justly without injury to civilization. - -Modern technique has made it possible to diminish enormously the amount of labor required to secure the necessaries of life for everyone. This was made obvious during the war. At that time all the men in the armed forces, and all the men and women engaged in the production of munitions, all the men and women engaged in spying, war propaganda, or Government offices connected with the war, were withdrawn from productive occupations. In spite of this, the general level of well-being among unskilled wage-earners on the side of the Allies was higher than before or since. The significance of this fact was concealed by finance: borrowing made it appear as if the future was nourishing the present. But that, of course, would have been impossible; a man cannot eat a loaf of bread that does not yet exist. The war showed conclusively that, by the scientific organization of production, it is possible to keep modern populations in fair comfort on a small part of the working capacity of the modern world. If, at the end of the war, the scientific organization, which had been created in order to liberate men for fighting and munition work, had been preserved, and the hours of the week had been cut down to four, all would have been well. Instead of that the old chaos was restored, those whose work was demanded were made to work long hours, and the rest were left to starve as unemployed. Why? Because work is a duty, and a man should not receive wages in proportion to what he has produced, but in proportion to his virtue as exemplified by his industry. - -This is the morality of the Slave State, applied in circumstances totally unlike those in which it arose. No wonder the result has been disastrous. Let us take an illustration. Suppose that, at a given moment, a certain number of people are engaged in the manufacture of pins. They make as many pins as the world needs, working (say) eight hours a day. Someone makes an invention by which the same number of men can make twice as many pins: pins are already so cheap that hardly any more will be bought at a lower price. In a sensible world, everybody concerned in the manufacturing of pins would take to working four hours instead of eight, and everything else would go on as before. But in the actual world this would be thought demoralizing. The men still work eight hours, there are too many pins, some employers go bankrupt, and half the men previously concerned in making pins are thrown out of work. There is, in the end, just as much leisure as on the other plan, but half the men are totally idle while half are still overworked. In this way, it is insured that the unavoidable leisure shall cause misery all round instead of being a universal source of happiness. Can anything more insane be imagined? - -The idea that the poor should have leisure has always been shocking to the rich. In England, in the early nineteenth century, fifteen hours was the ordinary day's work for a man; children sometimes did as much, and very commonly did twelve hours a day. When meddlesome busybodies suggested that perhaps these hours were rather long, they were told that work kept adults from drink and children from mischief. When I was a child, shortly after urban working men had acquired the vote, certain public holidays were established by law, to the great indignation of the upper classes. I remember hearing an old Duchess say: 'What do the poor want with holidays? They ought to work.' People nowadays are less frank, but the sentiment persists, and is the source of much of our economic confusion. - -Let us, for a moment, consider the ethics of work frankly, without superstition. Every human being, of necessity, consumes, in the course of his life, a certain amount of the produce of human labor. Assuming, as we may, that labor is on the whole disagreeable, it is unjust that a man should consume more than he produces. Of course he may provide services rather than commodities, like a medical man, for example; but he should provide something in return for his board and lodging. to this extent, the duty of work must be admitted, but to this extent only. - -I shall not dwell upon the fact that, in all modern societies outside the USSR, many people escape even this minimum amount of work, namely all those who inherit money and all those who marry money. I do not think the fact that these people are allowed to be idle is nearly so harmful as the fact that wage-earners are expected to overwork or starve. - -If the ordinary wage-earner worked four hours a day, there would be enough for everybody and no unemployment -- assuming a certain very moderate amount of sensible organization. This idea shocks the well-to-do, because they are convinced that the poor would not know how to use so much leisure. In America men often work long hours even when they are well off; such men, naturally, are indignant at the idea of leisure for wage-earners, except as the grim punishment of unemployment; in fact, they dislike leisure even for their sons. Oddly enough, while they wish their sons to work so hard as to have no time to be civilized, they do not mind their wives and daughters having no work at all. the snobbish admiration of uselessness, which, in an aristocratic society, extends to both sexes, is, under a plutocracy, confined to women; this, however, does not make it any more in agreement with common sense. - -The wise use of leisure, it must be conceded, is a product of civilization and education. A man who has worked long hours all his life will become bored if he becomes suddenly idle. But without a considerable amount of leisure a man is cut off from many of the best things. There is no longer any reason why the bulk of the population should suffer this deprivation; only a foolish asceticism, usually vicarious, makes us continue to insist on work in excessive quantities now that the need no longer exists. - -In the new creed which controls the government of Russia, while there is much that is very different from the traditional teaching of the West, there are some things that are quite unchanged. The attitude of the governing classes, and especially of those who conduct educational propaganda, on the subject of the dignity of labor, is almost exactly that which the governing classes of the world have always preached to what were called the 'honest poor'. Industry, sobriety, willingness to work long hours for distant advantages, even submissiveness to authority, all these reappear; moreover authority still represents the will of the Ruler of the Universe, Who, however, is now called by a new name, Dialectical Materialism. - -The victory of the proletariat in Russia has some points in common with the victory of the feminists in some other countries. For ages, men had conceded the superior saintliness of women, and had consoled women for their inferiority by maintaining that saintliness is more desirable than power. At last the feminists decided that they would have both, since the pioneers among them believed all that the men had told them about the desirability of virtue, but not what they had told them about the worthlessness of political power. A similar thing has happened in Russia as regards manual work. For ages, the rich and their sycophants have written in praise of 'honest toil', have praised the simple life, have professed a religion which teaches that the poor are much more likely to go to heaven than the rich, and in general have tried to make manual workers believe that there is some special nobility about altering the position of matter in space, just as men tried to make women believe that they derived some special nobility from their sexual enslavement. In Russia, all this teaching about the excellence of manual work has been taken seriously, with the result that the manual worker is more honored than anyone else. What are, in essence, revivalist appeals are made, but not for the old purposes: they are made to secure shock workers for special tasks. Manual work is the ideal which is held before the young, and is the basis of all ethical teaching. - -For the present, possibly, this is all to the good. A large country, full of natural resources, awaits development, and has has to be developed with very little use of credit. In these circumstances, hard work is necessary, and is likely to bring a great reward. But what will happen when the point has been reached where everybody could be comfortable without working long hours? - -In the West, we have various ways of dealing with this problem. We have no attempt at economic justice, so that a large proportion of the total produce goes to a small minority of the population, many of whom do no work at all. Owing to the absence of any central control over production, we produce hosts of things that are not wanted. We keep a large percentage of the working population idle, because we can dispense with their labor by making the others overwork. When all these methods prove inadequate, we have a war: we cause a number of people to manufacture high explosives, and a number of others to explode them, as if we were children who had just discovered fireworks. By a combination of all these devices we manage, though with difficulty, to keep alive the notion that a great deal of severe manual work must be the lot of the average man. - -In Russia, owing to more economic justice and central control over production, the problem will have to be differently solved. the rational solution would be, as soon as the necessaries and elementary comforts can be provided for all, to reduce the hours of labor gradually, allowing a popular vote to decide, at each stage, whether more leisure or more goods were to be preferred. But, having taught the supreme virtue of hard work, it is difficult to see how the authorities can aim at a paradise in which there will be much leisure and little work. It seems more likely that they will find continually fresh schemes, by which present leisure is to be sacrificed to future productivity. I read recently of an ingenious plan put forward by Russian engineers, for making the White Sea and the northern coasts of Siberia warm, by putting a dam across the Kara Sea. An admirable project, but liable to postpone proletarian comfort for a generation, while the nobility of toil is being displayed amid the ice-fields and snowstorms of the Arctic Ocean. This sort of thing, if it happens, will be the result of regarding the virtue of hard work as an end in itself, rather than as a means to a state of affairs in which it is no longer needed. - -The fact is that moving matter about, while a certain amount of it is necessary to our existence, is emphatically not one of the ends of human life. If it were, we should have to consider every navvy superior to Shakespeare. We have been misled in this matter by two causes. One is the necessity of keeping the poor contented, which has led the rich, for thousands of years, to preach the dignity of labor, while taking care themselves to remain undignified in this respect. The other is the new pleasure in mechanism, which makes us delight in the astonishingly clever changes that we can produce on the earth's surface. Neither of these motives makes any great appeal to the actual worker. If you ask him what he thinks the best part of his life, he is not likely to say: 'I enjoy manual work because it makes me feel that I am fulfilling man's noblest task, and because I like to think how much man can transform his planet. It is true that my body demands periods of rest, which I have to fill in as best I may, but I am never so happy as when the morning comes and I can return to the toil from which my contentment springs.' I have never heard working men say this sort of thing. They consider work, as it should be considered, a necessary means to a livelihood, and it is from their leisure that they derive whatever happiness they may enjoy. - -It will be said that, while a little leisure is pleasant, men would not know how to fill their days if they had only four hours of work out of the twenty-four. In so far as this is true in the modern world, it is a condemnation of our civilization; it would not have been true at any earlier period. There was formerly a capacity for light-heartedness and play which has been to some extent inhibited by the cult of efficiency. The modern man thinks that everything ought to be done for the sake of something else, and never for its own sake. Serious-minded persons, for example, are continually condemning the habit of going to the cinema, and telling us that it leads the young into crime. But all the work that goes to producing a cinema is respectable, because it is work, and because it brings a money profit. The notion that the desirable activities are those that bring a profit has made everything topsy-turvy. The butcher who provides you with meat and the baker who provides you with bread are praiseworthy, because they are making money; but when you enjoy the food they have provided, you are merely frivolous, unless you eat only to get strength for your work. Broadly speaking, it is held that getting money is good and spending money is bad. Seeing that they are two sides of one transaction, this is absurd; one might as well maintain that keys are good, but keyholes are bad. Whatever merit there may be in the production of goods must be entirely derivative from the advantage to be obtained by consuming them. The individual, in our society, works for profit; but the social purpose of his work lies in the consumption of what he produces. It is this divorce between the individual and the social purpose of production that makes it so difficult for men to think clearly in a world in which profit-making is the incentive to industry. We think too much of production, and too little of consumption. One result is that we attach too little importance to enjoyment and simple happiness, and that we do not judge production by the pleasure that it gives to the consumer. - -When I suggest that working hours should be reduced to four, I am not meaning to imply that all the remaining time should necessarily be spent in pure frivolity. I mean that four hours' work a day should entitle a man to the necessities and elementary comforts of life, and that the rest of his time should be his to use as he might see fit. It is an essential part of any such social system that education should be carried further than it usually is at present, and should aim, in part, at providing tastes which would enable a man to use leisure intelligently. I am not thinking mainly of the sort of things that would be considered 'highbrow'. Peasant dances have died out except in remote rural areas, but the impulses which caused them to be cultivated must still exist in human nature. The pleasures of urban populations have become mainly passive: seeing cinemas, watching football matches, listening to the radio, and so on. This results from the fact that their active energies are fully taken up with work; if they had more leisure, they would again enjoy pleasures in which they took an active part. - -In the past, there was a small leisure class and a larger working class. The leisure class enjoyed advantages for which there was no basis in social justice; this necessarily made it oppressive, limited its sympathies, and caused it to invent theories by which to justify its privileges. These facts greatly diminished its excellence, but in spite of this drawback it contributed nearly the whole of what we call civilization. It cultivated the arts and discovered the sciences; it wrote the books, invented the philosophies, and refined social relations. Even the liberation of the oppressed has usually been inaugurated from above. Without the leisure class, mankind would never have emerged from barbarism. - -The method of a leisure class without duties was, however, extraordinarily wasteful. None of the members of the class had to be taught to be industrious, and the class as a whole was not exceptionally intelligent. The class might produce one Darwin, but against him had to be set tens of thousands of country gentlemen who never thought of anything more intelligent than fox-hunting and punishing poachers. At present, the universities are supposed to provide, in a more systematic way, what the leisure class provided accidentally and as a by-product. This is a great improvement, but it has certain drawbacks. University life is so different from life in the world at large that men who live in academic milieu tend to be unaware of the preoccupations and problems of ordinary men and women; moreover their ways of expressing themselves are usually such as to rob their opinions of the influence that they ought to have upon the general public. Another disadvantage is that in universities studies are organized, and the man who thinks of some original line of research is likely to be discouraged. Academic institutions, therefore, useful as they are, are not adequate guardians of the interests of civilization in a world where everyone outside their walls is too busy for unutilitarian pursuits. - -In a world where no one is compelled to work more than four hours a day, every person possessed of scientific curiosity will be able to indulge it, and every painter will be able to paint without starving, however excellent his pictures may be. Young writers will not be obliged to draw attention to themselves by sensational pot-boilers, with a view to acquiring the economic independence needed for monumental works, for which, when the time at last comes, they will have lost the taste and capacity. Men who, in their professional work, have become interested in some phase of economics or government, will be able to develop their ideas without the academic detachment that makes the work of university economists often seem lacking in reality. Medical men will have the time to learn about the progress of medicine, teachers will not be exasperatedly struggling to teach by routine methods things which they learnt in their youth, which may, in the interval, have been proved to be untrue. - -Above all, there will be happiness and joy of life, instead of frayed nerves, weariness, and dyspepsia. The work exacted will be enough to make leisure delightful, but not enough to produce exhaustion. Since men will not be tired in their spare time, they will not demand only such amusements as are passive and vapid. At least one per cent will probably devote the time not spent in professional work to pursuits of some public importance, and, since they will not depend upon these pursuits for their livelihood, their originality will be unhampered, and there will be no need to conform to the standards set by elderly pundits. But it is not only in these exceptional cases that the advantages of leisure will appear. Ordinary men and women, having the opportunity of a happy life, will become more kindly and less persecuting and less inclined to view others with suspicion. The taste for war will die out, partly for this reason, and partly because it will involve long and severe work for all. Good nature is, of all moral qualities, the one that the world needs most, and good nature is the result of ease and security, not of a life of arduous struggle. Modern methods of production have given us the possibility of ease and security for all; we have chosen, instead, to have overwork for some and starvation for others. Hitherto we have continued to be as energetic as we were before there were machines; in this we have been foolish, but there is no reason to go on being foolish forever. - -[1] Since then, members of the Communist Party have succeeded to this privilege of the warriors and priests. diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/wrap.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/wrap.js deleted file mode 100644 index 0cfb76d17..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/node_modules/wordwrap/test/wrap.js +++ /dev/null @@ -1,31 +0,0 @@ -var assert = require('assert'); -var wordwrap = require('wordwrap'); - -var fs = require('fs'); -var idleness = fs.readFileSync(__dirname + '/idleness.txt', 'utf8'); - -exports.stop80 = function () { - var lines = wordwrap(80)(idleness).split(/\n/); - var words = idleness.split(/\s+/); - - lines.forEach(function (line) { - assert.ok(line.length <= 80, 'line > 80 columns'); - var chunks = line.match(/\S/) ? line.split(/\s+/) : []; - assert.deepEqual(chunks, words.splice(0, chunks.length)); - }); -}; - -exports.start20stop60 = function () { - var lines = wordwrap(20, 100)(idleness).split(/\n/); - var words = idleness.split(/\s+/); - - lines.forEach(function (line) { - assert.ok(line.length <= 100, 'line > 100 columns'); - var chunks = line - .split(/\s+/) - .filter(function (x) { return x.match(/\S/) }) - ; - assert.deepEqual(chunks, words.splice(0, chunks.length)); - assert.deepEqual(line.slice(0, 20), new Array(20 + 1).join(' ')); - }); -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/package.json b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/package.json deleted file mode 100644 index a37f7d949..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "optimist", - "version": "0.3.7", - "description": "Light-weight option parsing with an argv hash. No optstrings attached.", - "main": "./index.js", - "dependencies": { - "wordwrap": "~0.0.2" - }, - "devDependencies": { - "hashish": "~0.0.4", - "tap": "~0.4.0" - }, - "scripts": { - "test": "tap ./test/*.js" - }, - "repository": { - "type": "git", - "url": "http://github.com/substack/node-optimist.git" - }, - "keywords": [ - "argument", - "args", - "option", - "parser", - "parsing", - "cli", - "command" - ], - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "license": "MIT/X11", - "engine": { - "node": ">=0.4" - }, - "readme": "optimist\n========\n\nOptimist is a node.js library for option parsing for people who hate option\nparsing. More specifically, this module is for people who like all the --bells\nand -whistlz of program usage but think optstrings are a waste of time.\n\nWith optimist, option parsing doesn't have to suck (as much).\n\n[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist)\n\nexamples\n========\n\nWith Optimist, the options are just a hash! No optstrings attached.\n-------------------------------------------------------------------\n\nxup.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\n\nif (argv.rif - 5 * argv.xup > 7.138) {\n console.log('Buy more riffiwobbles');\n}\nelse {\n console.log('Sell the xupptumblers');\n}\n````\n\n***\n\n $ ./xup.js --rif=55 --xup=9.52\n Buy more riffiwobbles\n \n $ ./xup.js --rif 12 --xup 8.1\n Sell the xupptumblers\n\n![This one's optimistic.](http://substack.net/images/optimistic.png)\n\nBut wait! There's more! You can do short options:\n-------------------------------------------------\n \nshort.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\nconsole.log('(%d,%d)', argv.x, argv.y);\n````\n\n***\n\n $ ./short.js -x 10 -y 21\n (10,21)\n\nAnd booleans, both long and short (and grouped):\n----------------------------------\n\nbool.js:\n\n````javascript\n#!/usr/bin/env node\nvar util = require('util');\nvar argv = require('optimist').argv;\n\nif (argv.s) {\n util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: ');\n}\nconsole.log(\n (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '')\n);\n````\n\n***\n\n $ ./bool.js -s\n The cat says: meow\n \n $ ./bool.js -sp\n The cat says: meow.\n\n $ ./bool.js -sp --fr\n Le chat dit: miaou.\n\nAnd non-hypenated options too! Just use `argv._`!\n-------------------------------------------------\n \nnonopt.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist').argv;\nconsole.log('(%d,%d)', argv.x, argv.y);\nconsole.log(argv._);\n````\n\n***\n\n $ ./nonopt.js -x 6.82 -y 3.35 moo\n (6.82,3.35)\n [ 'moo' ]\n \n $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz\n (0.54,1.12)\n [ 'foo', 'bar', 'baz' ]\n\nPlus, Optimist comes with .usage() and .demand()!\n-------------------------------------------------\n\ndivide.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .usage('Usage: $0 -x [num] -y [num]')\n .demand(['x','y'])\n .argv;\n\nconsole.log(argv.x / argv.y);\n````\n\n***\n \n $ ./divide.js -x 55 -y 11\n 5\n \n $ node ./divide.js -x 4.91 -z 2.51\n Usage: node ./divide.js -x [num] -y [num]\n\n Options:\n -x [required]\n -y [required]\n\n Missing required arguments: y\n\nEVEN MORE HOLY COW\n------------------\n\ndefault_singles.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .default('x', 10)\n .default('y', 10)\n .argv\n;\nconsole.log(argv.x + argv.y);\n````\n\n***\n\n $ ./default_singles.js -x 5\n 15\n\ndefault_hash.js:\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .default({ x : 10, y : 10 })\n .argv\n;\nconsole.log(argv.x + argv.y);\n````\n\n***\n\n $ ./default_hash.js -y 7\n 17\n\nAnd if you really want to get all descriptive about it...\n---------------------------------------------------------\n\nboolean_single.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .boolean('v')\n .argv\n;\nconsole.dir(argv);\n````\n\n***\n\n $ ./boolean_single.js -v foo bar baz\n true\n [ 'bar', 'baz', 'foo' ]\n\nboolean_double.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .boolean(['x','y','z'])\n .argv\n;\nconsole.dir([ argv.x, argv.y, argv.z ]);\nconsole.dir(argv._);\n````\n\n***\n\n $ ./boolean_double.js -x -z one two three\n [ true, false, true ]\n [ 'one', 'two', 'three' ]\n\nOptimist is here to help...\n---------------------------\n\nYou can describe parameters for help messages and set aliases. Optimist figures\nout how to format a handy help string automatically.\n\nline_count.js\n\n````javascript\n#!/usr/bin/env node\nvar argv = require('optimist')\n .usage('Count the lines in a file.\\nUsage: $0')\n .demand('f')\n .alias('f', 'file')\n .describe('f', 'Load a file')\n .argv\n;\n\nvar fs = require('fs');\nvar s = fs.createReadStream(argv.file);\n\nvar lines = 0;\ns.on('data', function (buf) {\n lines += buf.toString().match(/\\n/g).length;\n});\n\ns.on('end', function () {\n console.log(lines);\n});\n````\n\n***\n\n $ node line_count.js\n Count the lines in a file.\n Usage: node ./line_count.js\n\n Options:\n -f, --file Load a file [required]\n\n Missing required arguments: f\n\n $ node line_count.js --file line_count.js \n 20\n \n $ node line_count.js -f line_count.js \n 20\n\nmethods\n=======\n\nBy itself,\n\n````javascript\nrequire('optimist').argv\n`````\n\nwill use `process.argv` array to construct the `argv` object.\n\nYou can pass in the `process.argv` yourself:\n\n````javascript\nrequire('optimist')([ '-x', '1', '-y', '2' ]).argv\n````\n\nor use .parse() to do the same thing:\n\n````javascript\nrequire('optimist').parse([ '-x', '1', '-y', '2' ])\n````\n\nThe rest of these methods below come in just before the terminating `.argv`.\n\n.alias(key, alias)\n------------------\n\nSet key names as equivalent such that updates to a key will propagate to aliases\nand vice-versa.\n\nOptionally `.alias()` can take an object that maps keys to aliases.\n\n.default(key, value)\n--------------------\n\nSet `argv[key]` to `value` if no option was specified on `process.argv`.\n\nOptionally `.default()` can take an object that maps keys to default values.\n\n.demand(key)\n------------\n\nIf `key` is a string, show the usage information and exit if `key` wasn't\nspecified in `process.argv`.\n\nIf `key` is a number, demand at least as many non-option arguments, which show\nup in `argv._`.\n\nIf `key` is an Array, demand each element.\n\n.describe(key, desc)\n--------------------\n\nDescribe a `key` for the generated usage information.\n\nOptionally `.describe()` can take an object that maps keys to descriptions.\n\n.options(key, opt)\n------------------\n\nInstead of chaining together `.alias().demand().default()`, you can specify\nkeys in `opt` for each of the chainable methods.\n\nFor example:\n\n````javascript\nvar argv = require('optimist')\n .options('f', {\n alias : 'file',\n default : '/etc/passwd',\n })\n .argv\n;\n````\n\nis the same as\n\n````javascript\nvar argv = require('optimist')\n .alias('f', 'file')\n .default('f', '/etc/passwd')\n .argv\n;\n````\n\nOptionally `.options()` can take an object that maps keys to `opt` parameters.\n\n.usage(message)\n---------------\n\nSet a usage message to show which commands to use. Inside `message`, the string\n`$0` will get interpolated to the current script name or node command for the\npresent script similar to how `$0` works in bash or perl.\n\n.check(fn)\n----------\n\nCheck that certain conditions are met in the provided arguments.\n\nIf `fn` throws or returns `false`, show the thrown error, usage information, and\nexit.\n\n.boolean(key)\n-------------\n\nInterpret `key` as a boolean. If a non-flag option follows `key` in\n`process.argv`, that string won't get set as the value of `key`.\n\nIf `key` never shows up as a flag in `process.arguments`, `argv[key]` will be\n`false`.\n\nIf `key` is an Array, interpret all the elements as booleans.\n\n.string(key)\n------------\n\nTell the parser logic not to interpret `key` as a number or boolean.\nThis can be useful if you need to preserve leading zeros in an input.\n\nIf `key` is an Array, interpret all the elements as strings.\n\n.wrap(columns)\n--------------\n\nFormat usage output to wrap at `columns` many columns.\n\n.help()\n-------\n\nReturn the generated usage string.\n\n.showHelp(fn=console.error)\n---------------------------\n\nPrint the usage data using `fn` for printing.\n\n.parse(args)\n------------\n\nParse `args` instead of `process.argv`. Returns the `argv` object.\n\n.argv\n-----\n\nGet the arguments as a plain old object.\n\nArguments without a corresponding flag show up in the `argv._` array.\n\nThe script name or node command is available at `argv.$0` similarly to how `$0`\nworks in bash or perl.\n\nparsing tricks\n==============\n\nstop parsing\n------------\n\nUse `--` to stop parsing flags and stuff the remainder into `argv._`.\n\n $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4\n { _: [ '-c', '3', '-d', '4' ],\n '$0': 'node ./examples/reflect.js',\n a: 1,\n b: 2 }\n\nnegate fields\n-------------\n\nIf you want to explicity set a field to false instead of just leaving it\nundefined or to override a default you can do `--no-key`.\n\n $ node examples/reflect.js -a --no-b\n { _: [],\n '$0': 'node ./examples/reflect.js',\n a: true,\n b: false }\n\nnumbers\n-------\n\nEvery argument that looks like a number (`!isNaN(Number(arg))`) is converted to\none. This way you can just `net.createConnection(argv.port)` and you can add\nnumbers out of `argv` with `+` without having that mean concatenation,\nwhich is super frustrating.\n\nduplicates\n----------\n\nIf you specify a flag multiple times it will get turned into an array containing\nall the values in order.\n\n $ node examples/reflect.js -x 5 -x 8 -x 0\n { _: [],\n '$0': 'node ./examples/reflect.js',\n x: [ 5, 8, 0 ] }\n\ndot notation\n------------\n\nWhen you use dots (`.`s) in argument names, an implicit object path is assumed.\nThis lets you organize arguments into nested objects.\n\n $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5\n { _: [],\n '$0': 'node ./examples/reflect.js',\n foo: { bar: { baz: 33 }, quux: 5 } }\n\ninstallation\n============\n\nWith [npm](http://github.com/isaacs/npm), just do:\n npm install optimist\n \nor clone this project on github:\n\n git clone http://github.com/substack/node-optimist.git\n\nTo run the tests with [expresso](http://github.com/visionmedia/expresso),\njust do:\n \n expresso\n\ninspired By\n===========\n\nThis module is loosely inspired by Perl's\n[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).\n", - "readmeFilename": "readme.markdown", - "bugs": { - "url": "https://github.com/substack/node-optimist/issues" - }, - "homepage": "https://github.com/substack/node-optimist", - "_id": "optimist@0.3.7", - "_from": "optimist@~0.3" -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/readme.markdown b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/readme.markdown deleted file mode 100644 index ad9d3fd68..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/readme.markdown +++ /dev/null @@ -1,487 +0,0 @@ -optimist -======== - -Optimist is a node.js library for option parsing for people who hate option -parsing. More specifically, this module is for people who like all the --bells -and -whistlz of program usage but think optstrings are a waste of time. - -With optimist, option parsing doesn't have to suck (as much). - -[![build status](https://secure.travis-ci.org/substack/node-optimist.png)](http://travis-ci.org/substack/node-optimist) - -examples -======== - -With Optimist, the options are just a hash! No optstrings attached. -------------------------------------------------------------------- - -xup.js: - -````javascript -#!/usr/bin/env node -var argv = require('optimist').argv; - -if (argv.rif - 5 * argv.xup > 7.138) { - console.log('Buy more riffiwobbles'); -} -else { - console.log('Sell the xupptumblers'); -} -```` - -*** - - $ ./xup.js --rif=55 --xup=9.52 - Buy more riffiwobbles - - $ ./xup.js --rif 12 --xup 8.1 - Sell the xupptumblers - -![This one's optimistic.](http://substack.net/images/optimistic.png) - -But wait! There's more! You can do short options: -------------------------------------------------- - -short.js: - -````javascript -#!/usr/bin/env node -var argv = require('optimist').argv; -console.log('(%d,%d)', argv.x, argv.y); -```` - -*** - - $ ./short.js -x 10 -y 21 - (10,21) - -And booleans, both long and short (and grouped): ----------------------------------- - -bool.js: - -````javascript -#!/usr/bin/env node -var util = require('util'); -var argv = require('optimist').argv; - -if (argv.s) { - util.print(argv.fr ? 'Le chat dit: ' : 'The cat says: '); -} -console.log( - (argv.fr ? 'miaou' : 'meow') + (argv.p ? '.' : '') -); -```` - -*** - - $ ./bool.js -s - The cat says: meow - - $ ./bool.js -sp - The cat says: meow. - - $ ./bool.js -sp --fr - Le chat dit: miaou. - -And non-hypenated options too! Just use `argv._`! -------------------------------------------------- - -nonopt.js: - -````javascript -#!/usr/bin/env node -var argv = require('optimist').argv; -console.log('(%d,%d)', argv.x, argv.y); -console.log(argv._); -```` - -*** - - $ ./nonopt.js -x 6.82 -y 3.35 moo - (6.82,3.35) - [ 'moo' ] - - $ ./nonopt.js foo -x 0.54 bar -y 1.12 baz - (0.54,1.12) - [ 'foo', 'bar', 'baz' ] - -Plus, Optimist comes with .usage() and .demand()! -------------------------------------------------- - -divide.js: - -````javascript -#!/usr/bin/env node -var argv = require('optimist') - .usage('Usage: $0 -x [num] -y [num]') - .demand(['x','y']) - .argv; - -console.log(argv.x / argv.y); -```` - -*** - - $ ./divide.js -x 55 -y 11 - 5 - - $ node ./divide.js -x 4.91 -z 2.51 - Usage: node ./divide.js -x [num] -y [num] - - Options: - -x [required] - -y [required] - - Missing required arguments: y - -EVEN MORE HOLY COW ------------------- - -default_singles.js: - -````javascript -#!/usr/bin/env node -var argv = require('optimist') - .default('x', 10) - .default('y', 10) - .argv -; -console.log(argv.x + argv.y); -```` - -*** - - $ ./default_singles.js -x 5 - 15 - -default_hash.js: - -````javascript -#!/usr/bin/env node -var argv = require('optimist') - .default({ x : 10, y : 10 }) - .argv -; -console.log(argv.x + argv.y); -```` - -*** - - $ ./default_hash.js -y 7 - 17 - -And if you really want to get all descriptive about it... ---------------------------------------------------------- - -boolean_single.js - -````javascript -#!/usr/bin/env node -var argv = require('optimist') - .boolean('v') - .argv -; -console.dir(argv); -```` - -*** - - $ ./boolean_single.js -v foo bar baz - true - [ 'bar', 'baz', 'foo' ] - -boolean_double.js - -````javascript -#!/usr/bin/env node -var argv = require('optimist') - .boolean(['x','y','z']) - .argv -; -console.dir([ argv.x, argv.y, argv.z ]); -console.dir(argv._); -```` - -*** - - $ ./boolean_double.js -x -z one two three - [ true, false, true ] - [ 'one', 'two', 'three' ] - -Optimist is here to help... ---------------------------- - -You can describe parameters for help messages and set aliases. Optimist figures -out how to format a handy help string automatically. - -line_count.js - -````javascript -#!/usr/bin/env node -var argv = require('optimist') - .usage('Count the lines in a file.\nUsage: $0') - .demand('f') - .alias('f', 'file') - .describe('f', 'Load a file') - .argv -; - -var fs = require('fs'); -var s = fs.createReadStream(argv.file); - -var lines = 0; -s.on('data', function (buf) { - lines += buf.toString().match(/\n/g).length; -}); - -s.on('end', function () { - console.log(lines); -}); -```` - -*** - - $ node line_count.js - Count the lines in a file. - Usage: node ./line_count.js - - Options: - -f, --file Load a file [required] - - Missing required arguments: f - - $ node line_count.js --file line_count.js - 20 - - $ node line_count.js -f line_count.js - 20 - -methods -======= - -By itself, - -````javascript -require('optimist').argv -````` - -will use `process.argv` array to construct the `argv` object. - -You can pass in the `process.argv` yourself: - -````javascript -require('optimist')([ '-x', '1', '-y', '2' ]).argv -```` - -or use .parse() to do the same thing: - -````javascript -require('optimist').parse([ '-x', '1', '-y', '2' ]) -```` - -The rest of these methods below come in just before the terminating `.argv`. - -.alias(key, alias) ------------------- - -Set key names as equivalent such that updates to a key will propagate to aliases -and vice-versa. - -Optionally `.alias()` can take an object that maps keys to aliases. - -.default(key, value) --------------------- - -Set `argv[key]` to `value` if no option was specified on `process.argv`. - -Optionally `.default()` can take an object that maps keys to default values. - -.demand(key) ------------- - -If `key` is a string, show the usage information and exit if `key` wasn't -specified in `process.argv`. - -If `key` is a number, demand at least as many non-option arguments, which show -up in `argv._`. - -If `key` is an Array, demand each element. - -.describe(key, desc) --------------------- - -Describe a `key` for the generated usage information. - -Optionally `.describe()` can take an object that maps keys to descriptions. - -.options(key, opt) ------------------- - -Instead of chaining together `.alias().demand().default()`, you can specify -keys in `opt` for each of the chainable methods. - -For example: - -````javascript -var argv = require('optimist') - .options('f', { - alias : 'file', - default : '/etc/passwd', - }) - .argv -; -```` - -is the same as - -````javascript -var argv = require('optimist') - .alias('f', 'file') - .default('f', '/etc/passwd') - .argv -; -```` - -Optionally `.options()` can take an object that maps keys to `opt` parameters. - -.usage(message) ---------------- - -Set a usage message to show which commands to use. Inside `message`, the string -`$0` will get interpolated to the current script name or node command for the -present script similar to how `$0` works in bash or perl. - -.check(fn) ----------- - -Check that certain conditions are met in the provided arguments. - -If `fn` throws or returns `false`, show the thrown error, usage information, and -exit. - -.boolean(key) -------------- - -Interpret `key` as a boolean. If a non-flag option follows `key` in -`process.argv`, that string won't get set as the value of `key`. - -If `key` never shows up as a flag in `process.arguments`, `argv[key]` will be -`false`. - -If `key` is an Array, interpret all the elements as booleans. - -.string(key) ------------- - -Tell the parser logic not to interpret `key` as a number or boolean. -This can be useful if you need to preserve leading zeros in an input. - -If `key` is an Array, interpret all the elements as strings. - -.wrap(columns) --------------- - -Format usage output to wrap at `columns` many columns. - -.help() -------- - -Return the generated usage string. - -.showHelp(fn=console.error) ---------------------------- - -Print the usage data using `fn` for printing. - -.parse(args) ------------- - -Parse `args` instead of `process.argv`. Returns the `argv` object. - -.argv ------ - -Get the arguments as a plain old object. - -Arguments without a corresponding flag show up in the `argv._` array. - -The script name or node command is available at `argv.$0` similarly to how `$0` -works in bash or perl. - -parsing tricks -============== - -stop parsing ------------- - -Use `--` to stop parsing flags and stuff the remainder into `argv._`. - - $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4 - { _: [ '-c', '3', '-d', '4' ], - '$0': 'node ./examples/reflect.js', - a: 1, - b: 2 } - -negate fields -------------- - -If you want to explicity set a field to false instead of just leaving it -undefined or to override a default you can do `--no-key`. - - $ node examples/reflect.js -a --no-b - { _: [], - '$0': 'node ./examples/reflect.js', - a: true, - b: false } - -numbers -------- - -Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to -one. This way you can just `net.createConnection(argv.port)` and you can add -numbers out of `argv` with `+` without having that mean concatenation, -which is super frustrating. - -duplicates ----------- - -If you specify a flag multiple times it will get turned into an array containing -all the values in order. - - $ node examples/reflect.js -x 5 -x 8 -x 0 - { _: [], - '$0': 'node ./examples/reflect.js', - x: [ 5, 8, 0 ] } - -dot notation ------------- - -When you use dots (`.`s) in argument names, an implicit object path is assumed. -This lets you organize arguments into nested objects. - - $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5 - { _: [], - '$0': 'node ./examples/reflect.js', - foo: { bar: { baz: 33 }, quux: 5 } } - -installation -============ - -With [npm](http://github.com/isaacs/npm), just do: - npm install optimist - -or clone this project on github: - - git clone http://github.com/substack/node-optimist.git - -To run the tests with [expresso](http://github.com/visionmedia/expresso), -just do: - - expresso - -inspired By -=========== - -This module is loosely inspired by Perl's -[Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm). diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_.js deleted file mode 100644 index d9c58b368..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_.js +++ /dev/null @@ -1,71 +0,0 @@ -var spawn = require('child_process').spawn; -var test = require('tap').test; - -test('dotSlashEmpty', testCmd('./bin.js', [])); - -test('dotSlashArgs', testCmd('./bin.js', [ 'a', 'b', 'c' ])); - -test('nodeEmpty', testCmd('node bin.js', [])); - -test('nodeArgs', testCmd('node bin.js', [ 'x', 'y', 'z' ])); - -test('whichNodeEmpty', function (t) { - var which = spawn('which', ['node']); - - which.stdout.on('data', function (buf) { - t.test( - testCmd(buf.toString().trim() + ' bin.js', []) - ); - t.end(); - }); - - which.stderr.on('data', function (err) { - assert.error(err); - t.end(); - }); -}); - -test('whichNodeArgs', function (t) { - var which = spawn('which', ['node']); - - which.stdout.on('data', function (buf) { - t.test( - testCmd(buf.toString().trim() + ' bin.js', [ 'q', 'r' ]) - ); - t.end(); - }); - - which.stderr.on('data', function (err) { - t.error(err); - t.end(); - }); -}); - -function testCmd (cmd, args) { - - return function (t) { - var to = setTimeout(function () { - assert.fail('Never got stdout data.') - }, 5000); - - var oldDir = process.cwd(); - process.chdir(__dirname + '/_'); - - var cmds = cmd.split(' '); - - var bin = spawn(cmds[0], cmds.slice(1).concat(args.map(String))); - process.chdir(oldDir); - - bin.stderr.on('data', function (err) { - t.error(err); - t.end(); - }); - - bin.stdout.on('data', function (buf) { - clearTimeout(to); - var _ = JSON.parse(buf.toString()); - t.same(_.map(String), args.map(String)); - t.end(); - }); - }; -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_/argv.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_/argv.js deleted file mode 100644 index 3d096062c..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_/argv.js +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -console.log(JSON.stringify(process.argv)); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_/bin.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_/bin.js deleted file mode 100644 index 4a18d85f3..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/_/bin.js +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env node -var argv = require('../../index').argv -console.log(JSON.stringify(argv._)); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/parse.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/parse.js deleted file mode 100644 index d320f4336..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/parse.js +++ /dev/null @@ -1,446 +0,0 @@ -var optimist = require('../index'); -var path = require('path'); -var test = require('tap').test; - -var $0 = 'node ./' + path.relative(process.cwd(), __filename); - -test('short boolean', function (t) { - var parse = optimist.parse([ '-b' ]); - t.same(parse, { b : true, _ : [], $0 : $0 }); - t.same(typeof parse.b, 'boolean'); - t.end(); -}); - -test('long boolean', function (t) { - t.same( - optimist.parse([ '--bool' ]), - { bool : true, _ : [], $0 : $0 } - ); - t.end(); -}); - -test('bare', function (t) { - t.same( - optimist.parse([ 'foo', 'bar', 'baz' ]), - { _ : [ 'foo', 'bar', 'baz' ], $0 : $0 } - ); - t.end(); -}); - -test('short group', function (t) { - t.same( - optimist.parse([ '-cats' ]), - { c : true, a : true, t : true, s : true, _ : [], $0 : $0 } - ); - t.end(); -}); - -test('short group next', function (t) { - t.same( - optimist.parse([ '-cats', 'meow' ]), - { c : true, a : true, t : true, s : 'meow', _ : [], $0 : $0 } - ); - t.end(); -}); - -test('short capture', function (t) { - t.same( - optimist.parse([ '-h', 'localhost' ]), - { h : 'localhost', _ : [], $0 : $0 } - ); - t.end(); -}); - -test('short captures', function (t) { - t.same( - optimist.parse([ '-h', 'localhost', '-p', '555' ]), - { h : 'localhost', p : 555, _ : [], $0 : $0 } - ); - t.end(); -}); - -test('long capture sp', function (t) { - t.same( - optimist.parse([ '--pow', 'xixxle' ]), - { pow : 'xixxle', _ : [], $0 : $0 } - ); - t.end(); -}); - -test('long capture eq', function (t) { - t.same( - optimist.parse([ '--pow=xixxle' ]), - { pow : 'xixxle', _ : [], $0 : $0 } - ); - t.end() -}); - -test('long captures sp', function (t) { - t.same( - optimist.parse([ '--host', 'localhost', '--port', '555' ]), - { host : 'localhost', port : 555, _ : [], $0 : $0 } - ); - t.end(); -}); - -test('long captures eq', function (t) { - t.same( - optimist.parse([ '--host=localhost', '--port=555' ]), - { host : 'localhost', port : 555, _ : [], $0 : $0 } - ); - t.end(); -}); - -test('mixed short bool and capture', function (t) { - t.same( - optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), - { - f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ], $0 : $0, - } - ); - t.end(); -}); - -test('short and long', function (t) { - t.same( - optimist.parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), - { - f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ], $0 : $0, - } - ); - t.end(); -}); - -test('no', function (t) { - t.same( - optimist.parse([ '--no-moo' ]), - { moo : false, _ : [], $0 : $0 } - ); - t.end(); -}); - -test('multi', function (t) { - t.same( - optimist.parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), - { v : ['a','b','c'], _ : [], $0 : $0 } - ); - t.end(); -}); - -test('comprehensive', function (t) { - t.same( - optimist.parse([ - '--name=meowmers', 'bare', '-cats', 'woo', - '-h', 'awesome', '--multi=quux', - '--key', 'value', - '-b', '--bool', '--no-meep', '--multi=baz', - '--', '--not-a-flag', 'eek' - ]), - { - c : true, - a : true, - t : true, - s : 'woo', - h : 'awesome', - b : true, - bool : true, - key : 'value', - multi : [ 'quux', 'baz' ], - meep : false, - name : 'meowmers', - _ : [ 'bare', '--not-a-flag', 'eek' ], - $0 : $0 - } - ); - t.end(); -}); - -test('nums', function (t) { - var argv = optimist.parse([ - '-x', '1234', - '-y', '5.67', - '-z', '1e7', - '-w', '10f', - '--hex', '0xdeadbeef', - '789', - ]); - t.same(argv, { - x : 1234, - y : 5.67, - z : 1e7, - w : '10f', - hex : 0xdeadbeef, - _ : [ 789 ], - $0 : $0 - }); - t.same(typeof argv.x, 'number'); - t.same(typeof argv.y, 'number'); - t.same(typeof argv.z, 'number'); - t.same(typeof argv.w, 'string'); - t.same(typeof argv.hex, 'number'); - t.same(typeof argv._[0], 'number'); - t.end(); -}); - -test('flag boolean', function (t) { - var parse = optimist([ '-t', 'moo' ]).boolean(['t']).argv; - t.same(parse, { t : true, _ : [ 'moo' ], $0 : $0 }); - t.same(typeof parse.t, 'boolean'); - t.end(); -}); - -test('flag boolean value', function (t) { - var parse = optimist(['--verbose', 'false', 'moo', '-t', 'true']) - .boolean(['t', 'verbose']).default('verbose', true).argv; - - t.same(parse, { - verbose: false, - t: true, - _: ['moo'], - $0 : $0 - }); - - t.same(typeof parse.verbose, 'boolean'); - t.same(typeof parse.t, 'boolean'); - t.end(); -}); - -test('flag boolean default false', function (t) { - var parse = optimist(['moo']) - .boolean(['t', 'verbose']) - .default('verbose', false) - .default('t', false).argv; - - t.same(parse, { - verbose: false, - t: false, - _: ['moo'], - $0 : $0 - }); - - t.same(typeof parse.verbose, 'boolean'); - t.same(typeof parse.t, 'boolean'); - t.end(); - -}); - -test('boolean groups', function (t) { - var parse = optimist([ '-x', '-z', 'one', 'two', 'three' ]) - .boolean(['x','y','z']).argv; - - t.same(parse, { - x : true, - y : false, - z : true, - _ : [ 'one', 'two', 'three' ], - $0 : $0 - }); - - t.same(typeof parse.x, 'boolean'); - t.same(typeof parse.y, 'boolean'); - t.same(typeof parse.z, 'boolean'); - t.end(); -}); - -test('newlines in params' , function (t) { - var args = optimist.parse([ '-s', "X\nX" ]) - t.same(args, { _ : [], s : "X\nX", $0 : $0 }); - - // reproduce in bash: - // VALUE="new - // line" - // node program.js --s="$VALUE" - args = optimist.parse([ "--s=X\nX" ]) - t.same(args, { _ : [], s : "X\nX", $0 : $0 }); - t.end(); -}); - -test('strings' , function (t) { - var s = optimist([ '-s', '0001234' ]).string('s').argv.s; - t.same(s, '0001234'); - t.same(typeof s, 'string'); - - var x = optimist([ '-x', '56' ]).string('x').argv.x; - t.same(x, '56'); - t.same(typeof x, 'string'); - t.end(); -}); - -test('stringArgs', function (t) { - var s = optimist([ ' ', ' ' ]).string('_').argv._; - t.same(s.length, 2); - t.same(typeof s[0], 'string'); - t.same(s[0], ' '); - t.same(typeof s[1], 'string'); - t.same(s[1], ' '); - t.end(); -}); - -test('slashBreak', function (t) { - t.same( - optimist.parse([ '-I/foo/bar/baz' ]), - { I : '/foo/bar/baz', _ : [], $0 : $0 } - ); - t.same( - optimist.parse([ '-xyz/foo/bar/baz' ]), - { x : true, y : true, z : '/foo/bar/baz', _ : [], $0 : $0 } - ); - t.end(); -}); - -test('alias', function (t) { - var argv = optimist([ '-f', '11', '--zoom', '55' ]) - .alias('z', 'zoom') - .argv - ; - t.equal(argv.zoom, 55); - t.equal(argv.z, argv.zoom); - t.equal(argv.f, 11); - t.end(); -}); - -test('multiAlias', function (t) { - var argv = optimist([ '-f', '11', '--zoom', '55' ]) - .alias('z', [ 'zm', 'zoom' ]) - .argv - ; - t.equal(argv.zoom, 55); - t.equal(argv.z, argv.zoom); - t.equal(argv.z, argv.zm); - t.equal(argv.f, 11); - t.end(); -}); - -test('boolean default true', function (t) { - var argv = optimist.options({ - sometrue: { - boolean: true, - default: true - } - }).argv; - - t.equal(argv.sometrue, true); - t.end(); -}); - -test('boolean default false', function (t) { - var argv = optimist.options({ - somefalse: { - boolean: true, - default: false - } - }).argv; - - t.equal(argv.somefalse, false); - t.end(); -}); - -test('nested dotted objects', function (t) { - var argv = optimist([ - '--foo.bar', '3', '--foo.baz', '4', - '--foo.quux.quibble', '5', '--foo.quux.o_O', - '--beep.boop' - ]).argv; - - t.same(argv.foo, { - bar : 3, - baz : 4, - quux : { - quibble : 5, - o_O : true - }, - }); - t.same(argv.beep, { boop : true }); - t.end(); -}); - -test('boolean and alias with chainable api', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - herp: { alias: 'h', boolean: true } - }; - var aliasedArgv = optimist(aliased) - .boolean('herp') - .alias('h', 'herp') - .argv; - var propertyArgv = optimist(regular) - .boolean('herp') - .alias('h', 'herp') - .argv; - var expected = { - herp: true, - h: true, - '_': [ 'derp' ], - '$0': $0, - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias with options hash', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - herp: { alias: 'h', boolean: true } - }; - var aliasedArgv = optimist(aliased) - .options(opts) - .argv; - var propertyArgv = optimist(regular).options(opts).argv; - var expected = { - herp: true, - h: true, - '_': [ 'derp' ], - '$0': $0, - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - - t.end(); -}); - -test('boolean and alias using explicit true', function (t) { - var aliased = [ '-h', 'true' ]; - var regular = [ '--herp', 'true' ]; - var opts = { - herp: { alias: 'h', boolean: true } - }; - var aliasedArgv = optimist(aliased) - .boolean('h') - .alias('h', 'herp') - .argv; - var propertyArgv = optimist(regular) - .boolean('h') - .alias('h', 'herp') - .argv; - var expected = { - herp: true, - h: true, - '_': [ ], - '$0': $0, - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -// regression, see https://github.com/substack/node-optimist/issues/71 -test('boolean and --x=true', function(t) { - var parsed = optimist(['--boool', '--other=true']).boolean('boool').argv; - - t.same(parsed.boool, true); - t.same(parsed.other, 'true'); - - parsed = optimist(['--boool', '--other=false']).boolean('boool').argv; - - t.same(parsed.boool, true); - t.same(parsed.other, 'false'); - t.end(); -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/usage.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/usage.js deleted file mode 100644 index 300454c1e..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/optimist/test/usage.js +++ /dev/null @@ -1,292 +0,0 @@ -var Hash = require('hashish'); -var optimist = require('../index'); -var test = require('tap').test; - -test('usageFail', function (t) { - var r = checkUsage(function () { - return optimist('-x 10 -z 20'.split(' ')) - .usage('Usage: $0 -x NUM -y NUM') - .demand(['x','y']) - .argv; - }); - t.same( - r.result, - { x : 10, z : 20, _ : [], $0 : './usage' } - ); - - t.same( - r.errors.join('\n').split(/\n+/), - [ - 'Usage: ./usage -x NUM -y NUM', - 'Options:', - ' -x [required]', - ' -y [required]', - 'Missing required arguments: y', - ] - ); - t.same(r.logs, []); - t.ok(r.exit); - t.end(); -}); - - -test('usagePass', function (t) { - var r = checkUsage(function () { - return optimist('-x 10 -y 20'.split(' ')) - .usage('Usage: $0 -x NUM -y NUM') - .demand(['x','y']) - .argv; - }); - t.same(r, { - result : { x : 10, y : 20, _ : [], $0 : './usage' }, - errors : [], - logs : [], - exit : false, - }); - t.end(); -}); - -test('checkPass', function (t) { - var r = checkUsage(function () { - return optimist('-x 10 -y 20'.split(' ')) - .usage('Usage: $0 -x NUM -y NUM') - .check(function (argv) { - if (!('x' in argv)) throw 'You forgot about -x'; - if (!('y' in argv)) throw 'You forgot about -y'; - }) - .argv; - }); - t.same(r, { - result : { x : 10, y : 20, _ : [], $0 : './usage' }, - errors : [], - logs : [], - exit : false, - }); - t.end(); -}); - -test('checkFail', function (t) { - var r = checkUsage(function () { - return optimist('-x 10 -z 20'.split(' ')) - .usage('Usage: $0 -x NUM -y NUM') - .check(function (argv) { - if (!('x' in argv)) throw 'You forgot about -x'; - if (!('y' in argv)) throw 'You forgot about -y'; - }) - .argv; - }); - - t.same( - r.result, - { x : 10, z : 20, _ : [], $0 : './usage' } - ); - - t.same( - r.errors.join('\n').split(/\n+/), - [ - 'Usage: ./usage -x NUM -y NUM', - 'You forgot about -y' - ] - ); - - t.same(r.logs, []); - t.ok(r.exit); - t.end(); -}); - -test('checkCondPass', function (t) { - function checker (argv) { - return 'x' in argv && 'y' in argv; - } - - var r = checkUsage(function () { - return optimist('-x 10 -y 20'.split(' ')) - .usage('Usage: $0 -x NUM -y NUM') - .check(checker) - .argv; - }); - t.same(r, { - result : { x : 10, y : 20, _ : [], $0 : './usage' }, - errors : [], - logs : [], - exit : false, - }); - t.end(); -}); - -test('checkCondFail', function (t) { - function checker (argv) { - return 'x' in argv && 'y' in argv; - } - - var r = checkUsage(function () { - return optimist('-x 10 -z 20'.split(' ')) - .usage('Usage: $0 -x NUM -y NUM') - .check(checker) - .argv; - }); - - t.same( - r.result, - { x : 10, z : 20, _ : [], $0 : './usage' } - ); - - t.same( - r.errors.join('\n').split(/\n+/).join('\n'), - 'Usage: ./usage -x NUM -y NUM\n' - + 'Argument check failed: ' + checker.toString() - ); - - t.same(r.logs, []); - t.ok(r.exit); - t.end(); -}); - -test('countPass', function (t) { - var r = checkUsage(function () { - return optimist('1 2 3 --moo'.split(' ')) - .usage('Usage: $0 [x] [y] [z] {OPTIONS}') - .demand(3) - .argv; - }); - t.same(r, { - result : { _ : [ '1', '2', '3' ], moo : true, $0 : './usage' }, - errors : [], - logs : [], - exit : false, - }); - t.end(); -}); - -test('countFail', function (t) { - var r = checkUsage(function () { - return optimist('1 2 --moo'.split(' ')) - .usage('Usage: $0 [x] [y] [z] {OPTIONS}') - .demand(3) - .argv; - }); - t.same( - r.result, - { _ : [ '1', '2' ], moo : true, $0 : './usage' } - ); - - t.same( - r.errors.join('\n').split(/\n+/), - [ - 'Usage: ./usage [x] [y] [z] {OPTIONS}', - 'Not enough non-option arguments: got 2, need at least 3', - ] - ); - - t.same(r.logs, []); - t.ok(r.exit); - t.end(); -}); - -test('defaultSingles', function (t) { - var r = checkUsage(function () { - return optimist('--foo 50 --baz 70 --powsy'.split(' ')) - .default('foo', 5) - .default('bar', 6) - .default('baz', 7) - .argv - ; - }); - t.same(r.result, { - foo : '50', - bar : 6, - baz : '70', - powsy : true, - _ : [], - $0 : './usage', - }); - t.end(); -}); - -test('defaultAliases', function (t) { - var r = checkUsage(function () { - return optimist('') - .alias('f', 'foo') - .default('f', 5) - .argv - ; - }); - t.same(r.result, { - f : '5', - foo : '5', - _ : [], - $0 : './usage', - }); - t.end(); -}); - -test('defaultHash', function (t) { - var r = checkUsage(function () { - return optimist('--foo 50 --baz 70'.split(' ')) - .default({ foo : 10, bar : 20, quux : 30 }) - .argv - ; - }); - t.same(r.result, { - _ : [], - $0 : './usage', - foo : 50, - baz : 70, - bar : 20, - quux : 30, - }); - t.end(); -}); - -test('rebase', function (t) { - t.equal( - optimist.rebase('/home/substack', '/home/substack/foo/bar/baz'), - './foo/bar/baz' - ); - t.equal( - optimist.rebase('/home/substack/foo/bar/baz', '/home/substack'), - '../../..' - ); - t.equal( - optimist.rebase('/home/substack/foo', '/home/substack/pow/zoom.txt'), - '../pow/zoom.txt' - ); - t.end(); -}); - -function checkUsage (f) { - - var exit = false; - - process._exit = process.exit; - process._env = process.env; - process._argv = process.argv; - - process.exit = function (t) { exit = true }; - process.env = Hash.merge(process.env, { _ : 'node' }); - process.argv = [ './usage' ]; - - var errors = []; - var logs = []; - - console._error = console.error; - console.error = function (msg) { errors.push(msg) }; - console._log = console.log; - console.log = function (msg) { logs.push(msg) }; - - var result = f(); - - process.exit = process._exit; - process.env = process._env; - process.argv = process._argv; - - console.error = console._error; - console.log = console._log; - - return { - errors : errors, - logs : logs, - exit : exit, - result : result, - }; -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/.npmignore b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/.npmignore deleted file mode 100644 index 94fceeb20..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -tmp/ -node_modules/ diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/.travis.yml b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/.travis.yml deleted file mode 100644 index d95912721..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js -node_js: - - "0.4" - - "0.6" - - "0.8" - - "0.10" - - "0.11" diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/LICENSE b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/LICENSE deleted file mode 100644 index dd7706f0c..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -UglifyJS is released under the BSD license: - -Copyright 2012-2013 (c) Mihai Bazon - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, -OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR -TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF -THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -SUCH DAMAGE. diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/README.md b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/README.md deleted file mode 100644 index 749b8cec5..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/README.md +++ /dev/null @@ -1,588 +0,0 @@ -UglifyJS 2 -========== -[![Build Status](https://travis-ci.org/mishoo/UglifyJS2.png)](https://travis-ci.org/mishoo/UglifyJS2) - -UglifyJS is a JavaScript parser, minifier, compressor or beautifier toolkit. - -This page documents the command line utility. For -[API and internals documentation see my website](http://lisperator.net/uglifyjs/). -There's also an -[in-browser online demo](http://lisperator.net/uglifyjs/#demo) (for Firefox, -Chrome and probably Safari). - -Install -------- - -First make sure you have installed the latest version of [node.js](http://nodejs.org/) -(You may need to restart your computer after this step). - -From NPM for use as a command line app: - - npm install uglify-js -g - -From NPM for programmatic use: - - npm install uglify-js - -From Git: - - git clone git://github.com/mishoo/UglifyJS2.git - cd UglifyJS2 - npm link . - -Usage ------ - - uglifyjs [input files] [options] - -UglifyJS2 can take multiple input files. It's recommended that you pass the -input files first, then pass the options. UglifyJS will parse input files -in sequence and apply any compression options. The files are parsed in the -same global scope, that is, a reference from a file to some -variable/function declared in another file will be matched properly. - -If you want to read from STDIN instead, pass a single dash instead of input -files. - -The available options are: - - --source-map Specify an output file where to generate source map. - [string] - --source-map-root The path to the original source to be included in the - source map. [string] - --source-map-url The path to the source map to be added in //@ - sourceMappingURL. Defaults to the value passed with - --source-map. [string] - --in-source-map Input source map, useful if you're compressing JS that was - generated from some other original code. - --screw-ie8 Pass this flag if you don't care about full compliance with - Internet Explorer 6-8 quirks (by default UglifyJS will try - to be IE-proof). - -p, --prefix Skip prefix for original filenames that appear in source - maps. For example -p 3 will drop 3 directories from file - names and ensure they are relative paths. - -o, --output Output file (default STDOUT). - -b, --beautify Beautify output/specify output options. [string] - -m, --mangle Mangle names/pass mangler options. [string] - -r, --reserved Reserved names to exclude from mangling. - -c, --compress Enable compressor/pass compressor options. Pass options - like -c hoist_vars=false,if_return=false. Use -c with no - argument to use the default compression options. [string] - -d, --define Global definitions [string] - --comments Preserve copyright comments in the output. By default this - works like Google Closure, keeping JSDoc-style comments - that contain "@license" or "@preserve". You can optionally - pass one of the following arguments to this flag: - - "all" to keep all comments - - a valid JS regexp (needs to start with a slash) to keep - only comments that match. - Note that currently not *all* comments can be kept when - compression is on, because of dead code removal or - cascading statements into sequences. [string] - --stats Display operations run time on STDERR. [boolean] - --acorn Use Acorn for parsing. [boolean] - --spidermonkey Assume input files are SpiderMonkey AST format (as JSON). - [boolean] - --self Build itself (UglifyJS2) as a library (implies - --wrap=UglifyJS --export-all) [boolean] - --wrap Embed everything in a big function, making the “exports” - and “global” variables available. You need to pass an - argument to this option to specify the name that your - module will take when included in, say, a browser. - [string] - --export-all Only used when --wrap, this tells UglifyJS to add code to - automatically export all globals. [boolean] - --lint Display some scope warnings [boolean] - -v, --verbose Verbose [boolean] - -V, --version Print version number and exit. [boolean] - -Specify `--output` (`-o`) to declare the output file. Otherwise the output -goes to STDOUT. - -## Source map options - -UglifyJS2 can generate a source map file, which is highly useful for -debugging your compressed JavaScript. To get a source map, pass -`--source-map output.js.map` (full path to the file where you want the -source map dumped). - -Additionally you might need `--source-map-root` to pass the URL where the -original files can be found. In case you are passing full paths to input -files to UglifyJS, you can use `--prefix` (`-p`) to specify the number of -directories to drop from the path prefix when declaring files in the source -map. - -For example: - - uglifyjs /home/doe/work/foo/src/js/file1.js \ - /home/doe/work/foo/src/js/file2.js \ - -o foo.min.js \ - --source-map foo.min.js.map \ - --source-map-root http://foo.com/src \ - -p 5 -c -m - -The above will compress and mangle `file1.js` and `file2.js`, will drop the -output in `foo.min.js` and the source map in `foo.min.js.map`. The source -mapping will refer to `http://foo.com/src/js/file1.js` and -`http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src` -as the source map root, and the original files as `js/file1.js` and -`js/file2.js`). - -### Composed source map - -When you're compressing JS code that was output by a compiler such as -CoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd -like to map back to the original code (i.e. CoffeeScript). UglifyJS has an -option to take an input source map. Assuming you have a mapping from -CoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript → -compressed JS by mapping every token in the compiled JS to its original -location. - -To use this feature you need to pass `--in-source-map -/path/to/input/source.map`. Normally the input source map should also point -to the file containing the generated JS, so if that's correct you can omit -input files from the command line. - -## Mangler options - -To enable the mangler you need to pass `--mangle` (`-m`). The following -(comma-separated) options are supported: - -- `sort` — to assign shorter names to most frequently used variables. This - saves a few hundred bytes on jQuery before gzip, but the output is - _bigger_ after gzip (and seems to happen for other libraries I tried it - on) therefore it's not enabled by default. - -- `toplevel` — mangle names declared in the toplevel scope (disabled by - default). - -- `eval` — mangle names visible in scopes where `eval` or `when` are used - (disabled by default). - -When mangling is enabled but you want to prevent certain names from being -mangled, you can declare those names with `--reserved` (`-r`) — pass a -comma-separated list of names. For example: - - uglifyjs ... -m -r '$,require,exports' - -to prevent the `require`, `exports` and `$` names from being changed. - -## Compressor options - -You need to pass `--compress` (`-c`) to enable the compressor. Optionally -you can pass a comma-separated list of options. Options are in the form -`foo=bar`, or just `foo` (the latter implies a boolean option that you want -to set `true`; it's effectively a shortcut for `foo=true`). - -- `sequences` -- join consecutive simple statements using the comma operator -- `properties` -- rewrite property access using the dot notation, for - example `foo["bar"] → foo.bar` -- `dead_code` -- remove unreachable code -- `drop_debugger` -- remove `debugger;` statements -- `unsafe` (default: false) -- apply "unsafe" transformations (discussion below) -- `conditionals` -- apply optimizations for `if`-s and conditional - expressions -- `comparisons` -- apply certain optimizations to binary nodes, for example: - `!(a <= b) → a > b` (only when `unsafe`), attempts to negate binary nodes, - e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc. -- `evaluate` -- attempt to evaluate constant expressions -- `booleans` -- various optimizations for boolean context, for example `!!a - ? b : c → a ? b : c` -- `loops` -- optimizations for `do`, `while` and `for` loops when we can - statically determine the condition -- `unused` -- drop unreferenced functions and variables -- `hoist_funs` -- hoist function declarations -- `hoist_vars` (default: false) -- hoist `var` declarations (this is `false` - by default because it seems to increase the size of the output in general) -- `if_return` -- optimizations for if/return and if/continue -- `join_vars` -- join consecutive `var` statements -- `cascade` -- small optimization for sequences, transform `x, x` into `x` - and `x = something(), x` into `x = something()` -- `warnings` -- display warnings when dropping unreachable code or unused - declarations etc. - -### The `unsafe` option - -It enables some transformations that *might* break code logic in certain -contrived cases, but should be fine for most code. You might want to try it -on your own code, it should reduce the minified size. Here's what happens -when this flag is on: - -- `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[1, 2, 3 ]` -- `new Object()` → `{}` -- `String(exp)` or `exp.toString()` → `"" + exp` -- `new Object/RegExp/Function/Error/Array (...)` → we discard the `new` -- `typeof foo == "undefined"` → `foo === void 0` -- `void 0` → `"undefined"` (if there is a variable named "undefined" in - scope; we do it because the variable name will be mangled, typically - reduced to a single character). - -### Conditional compilation - -You can use the `--define` (`-d`) switch in order to declare global -variables that UglifyJS will assume to be constants (unless defined in -scope). For example if you pass `--define DEBUG=false` then, coupled with -dead code removal UglifyJS will discard the following from the output: -```javascript -if (DEBUG) { - console.log("debug stuff"); -} -``` - -UglifyJS will warn about the condition being always false and about dropping -unreachable code; for now there is no option to turn off only this specific -warning, you can pass `warnings=false` to turn off *all* warnings. - -Another way of doing that is to declare your globals as constants in a -separate file and include it into the build. For example you can have a -`build/defines.js` file with the following: -```javascript -const DEBUG = false; -const PRODUCTION = true; -// etc. -``` - -and build your code like this: - - uglifyjs build/defines.js js/foo.js js/bar.js... -c - -UglifyJS will notice the constants and, since they cannot be altered, it -will evaluate references to them to the value itself and drop unreachable -code as usual. The possible downside of this approach is that the build -will contain the `const` declarations. - - -## Beautifier options - -The code generator tries to output shortest code possible by default. In -case you want beautified output, pass `--beautify` (`-b`). Optionally you -can pass additional arguments that control the code output: - -- `beautify` (default `true`) -- whether to actually beautify the output. - Passing `-b` will set this to true, but you might need to pass `-b` even - when you want to generate minified code, in order to specify additional - arguments, so you can use `-b beautify=false` to override it. -- `indent-level` (default 4) -- `indent-start` (default 0) -- prefix all lines by that many spaces -- `quote-keys` (default `false`) -- pass `true` to quote all keys in literal - objects -- `space-colon` (default `true`) -- insert a space after the colon signs -- `ascii-only` (default `false`) -- escape Unicode characters in strings and - regexps -- `inline-script` (default `false`) -- escape the slash in occurrences of - ` 0) { - sys.error("WARN: Ignoring input files since --self was passed"); - } - files = UglifyJS.FILES; - if (!ARGS.wrap) ARGS.wrap = "UglifyJS"; - ARGS.export_all = true; -} - -var ORIG_MAP = ARGS.in_source_map; - -if (ORIG_MAP) { - ORIG_MAP = JSON.parse(fs.readFileSync(ORIG_MAP)); - if (files.length == 0) { - sys.error("INFO: Using file from the input source map: " + ORIG_MAP.file); - files = [ ORIG_MAP.file ]; - } - if (ARGS.source_map_root == null) { - ARGS.source_map_root = ORIG_MAP.sourceRoot; - } -} - -if (files.length == 0) { - files = [ "-" ]; -} - -if (files.indexOf("-") >= 0 && ARGS.source_map) { - sys.error("ERROR: Source map doesn't work with input from STDIN"); - process.exit(1); -} - -if (files.filter(function(el){ return el == "-" }).length > 1) { - sys.error("ERROR: Can read a single file from STDIN (two or more dashes specified)"); - process.exit(1); -} - -var STATS = {}; -var OUTPUT_FILE = ARGS.o; -var TOPLEVEL = null; - -var SOURCE_MAP = ARGS.source_map ? UglifyJS.SourceMap({ - file: OUTPUT_FILE, - root: ARGS.source_map_root, - orig: ORIG_MAP, -}) : null; - -OUTPUT_OPTIONS.source_map = SOURCE_MAP; - -try { - var output = UglifyJS.OutputStream(OUTPUT_OPTIONS); - var compressor = COMPRESS && UglifyJS.Compressor(COMPRESS); -} catch(ex) { - if (ex instanceof UglifyJS.DefaultsError) { - sys.error(ex.msg); - sys.error("Supported options:"); - sys.error(sys.inspect(ex.defs)); - process.exit(1); - } -} - -async.eachLimit(files, 1, function (file, cb) { - read_whole_file(file, function (err, code) { - if (err) { - sys.error("ERROR: can't read file: " + filename); - process.exit(1); - } - if (ARGS.p != null) { - file = file.replace(/^\/+/, "").split(/\/+/).slice(ARGS.p).join("/"); - } - time_it("parse", function(){ - if (ARGS.spidermonkey) { - var program = JSON.parse(code); - if (!TOPLEVEL) TOPLEVEL = program; - else TOPLEVEL.body = TOPLEVEL.body.concat(program.body); - } - else if (ARGS.acorn) { - TOPLEVEL = acorn.parse(code, { - locations : true, - trackComments : true, - sourceFile : file, - program : TOPLEVEL - }); - } - else { - TOPLEVEL = UglifyJS.parse(code, { - filename : file, - toplevel : TOPLEVEL, - expression : ARGS.expr, - }); - }; - }); - cb(); - }); -}, function () { - if (ARGS.acorn || ARGS.spidermonkey) time_it("convert_ast", function(){ - TOPLEVEL = UglifyJS.AST_Node.from_mozilla_ast(TOPLEVEL); - }); - - if (ARGS.wrap) { - TOPLEVEL = TOPLEVEL.wrap_commonjs(ARGS.wrap, ARGS.export_all); - } - - if (ARGS.enclose) { - var arg_parameter_list = ARGS.enclose; - - if (!(arg_parameter_list instanceof Array)) { - arg_parameter_list = [arg_parameter_list]; - } - - TOPLEVEL = TOPLEVEL.wrap_enclose(arg_parameter_list); - } - - var SCOPE_IS_NEEDED = COMPRESS || MANGLE || ARGS.lint; - - if (SCOPE_IS_NEEDED) { - time_it("scope", function(){ - TOPLEVEL.figure_out_scope({ screw_ie8: ARGS.screw_ie8 }); - if (ARGS.lint) { - TOPLEVEL.scope_warnings(); - } - }); - } - - if (COMPRESS) { - time_it("squeeze", function(){ - TOPLEVEL = TOPLEVEL.transform(compressor); - }); - } - - if (SCOPE_IS_NEEDED) { - time_it("scope", function(){ - TOPLEVEL.figure_out_scope({ screw_ie8: ARGS.screw_ie8 }); - if (MANGLE) { - TOPLEVEL.compute_char_frequency(MANGLE); - } - }); - } - - if (MANGLE) time_it("mangle", function(){ - TOPLEVEL.mangle_names(MANGLE); - }); - time_it("generate", function(){ - TOPLEVEL.print(output); - }); - - output = output.get(); - - if (SOURCE_MAP) { - fs.writeFileSync(ARGS.source_map, SOURCE_MAP, "utf8"); - output += "\n//# sourceMappingURL=" + (ARGS.source_map_url || ARGS.source_map); - } - - if (OUTPUT_FILE) { - fs.writeFileSync(OUTPUT_FILE, output, "utf8"); - } else { - sys.print(output); - sys.error("\n"); - } - - if (ARGS.stats) { - sys.error(UglifyJS.string_template("Timing information (compressed {count} files):", { - count: files.length - })); - for (var i in STATS) if (STATS.hasOwnProperty(i)) { - sys.error(UglifyJS.string_template("- {name}: {time}s", { - name: i, - time: (STATS[i] / 1000).toFixed(3) - })); - } - } -}); - -/* -----[ functions ]----- */ - -function normalize(o) { - for (var i in o) if (o.hasOwnProperty(i) && /-/.test(i)) { - o[i.replace(/-/g, "_")] = o[i]; - delete o[i]; - } -} - -function getOptions(x, constants) { - x = ARGS[x]; - if (!x) return null; - var ret = {}; - if (x !== true) { - var ast; - try { - ast = UglifyJS.parse(x); - } catch(ex) { - if (ex instanceof UglifyJS.JS_Parse_Error) { - sys.error("Error parsing arguments in: " + x); - process.exit(1); - } - } - ast.walk(new UglifyJS.TreeWalker(function(node){ - if (node instanceof UglifyJS.AST_Toplevel) return; // descend - if (node instanceof UglifyJS.AST_SimpleStatement) return; // descend - if (node instanceof UglifyJS.AST_Seq) return; // descend - if (node instanceof UglifyJS.AST_Assign) { - var name = node.left.print_to_string({ beautify: false }).replace(/-/g, "_"); - var value = node.right; - if (constants) - value = new Function("return (" + value.print_to_string() + ")")(); - ret[name] = value; - return true; // no descend - } - sys.error(node.TYPE) - sys.error("Error parsing arguments in: " + x); - process.exit(1); - })); - } - return ret; -} - -function read_whole_file(filename, cb) { - if (filename == "-") { - var chunks = []; - process.stdin.setEncoding('utf-8'); - process.stdin.on('data', function (chunk) { - chunks.push(chunk); - }).on('end', function () { - cb(null, chunks.join("")); - }); - process.openStdin(); - } else { - fs.readFile(filename, "utf-8", cb); - } -} - -function time_it(name, cont) { - var t1 = new Date().getTime(); - var ret = cont(); - if (ARGS.stats) { - var spent = new Date().getTime() - t1; - if (STATS[name]) STATS[name] += spent; - else STATS[name] = spent; - } - return ret; -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/ast.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/ast.js deleted file mode 100644 index a1301da8b..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/ast.js +++ /dev/null @@ -1,985 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -function DEFNODE(type, props, methods, base) { - if (arguments.length < 4) base = AST_Node; - if (!props) props = []; - else props = props.split(/\s+/); - var self_props = props; - if (base && base.PROPS) - props = props.concat(base.PROPS); - var code = "return function AST_" + type + "(props){ if (props) { "; - for (var i = props.length; --i >= 0;) { - code += "this." + props[i] + " = props." + props[i] + ";"; - } - var proto = base && new base; - if (proto && proto.initialize || (methods && methods.initialize)) - code += "this.initialize();"; - code += "}}"; - var ctor = new Function(code)(); - if (proto) { - ctor.prototype = proto; - ctor.BASE = base; - } - if (base) base.SUBCLASSES.push(ctor); - ctor.prototype.CTOR = ctor; - ctor.PROPS = props || null; - ctor.SELF_PROPS = self_props; - ctor.SUBCLASSES = []; - if (type) { - ctor.prototype.TYPE = ctor.TYPE = type; - } - if (methods) for (i in methods) if (methods.hasOwnProperty(i)) { - if (/^\$/.test(i)) { - ctor[i.substr(1)] = methods[i]; - } else { - ctor.prototype[i] = methods[i]; - } - } - ctor.DEFMETHOD = function(name, method) { - this.prototype[name] = method; - }; - return ctor; -}; - -var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", { -}, null); - -var AST_Node = DEFNODE("Node", "start end", { - clone: function() { - return new this.CTOR(this); - }, - $documentation: "Base class of all AST nodes", - $propdoc: { - start: "[AST_Token] The first token of this node", - end: "[AST_Token] The last token of this node" - }, - _walk: function(visitor) { - return visitor._visit(this); - }, - walk: function(visitor) { - return this._walk(visitor); // not sure the indirection will be any help - } -}, null); - -AST_Node.warn_function = null; -AST_Node.warn = function(txt, props) { - if (AST_Node.warn_function) - AST_Node.warn_function(string_template(txt, props)); -}; - -/* -----[ statements ]----- */ - -var AST_Statement = DEFNODE("Statement", null, { - $documentation: "Base class of all statements", -}); - -var AST_Debugger = DEFNODE("Debugger", null, { - $documentation: "Represents a debugger statement", -}, AST_Statement); - -var AST_Directive = DEFNODE("Directive", "value scope", { - $documentation: "Represents a directive, like \"use strict\";", - $propdoc: { - value: "[string] The value of this directive as a plain string (it's not an AST_String!)", - scope: "[AST_Scope/S] The scope that this directive affects" - }, -}, AST_Statement); - -var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { - $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", - $propdoc: { - body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.body._walk(visitor); - }); - } -}, AST_Statement); - -function walk_body(node, visitor) { - if (node.body instanceof AST_Statement) { - node.body._walk(visitor); - } - else node.body.forEach(function(stat){ - stat._walk(visitor); - }); -}; - -var AST_Block = DEFNODE("Block", "body", { - $documentation: "A body of statements (usually bracketed)", - $propdoc: { - body: "[AST_Statement*] an array of statements" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - walk_body(this, visitor); - }); - } -}, AST_Statement); - -var AST_BlockStatement = DEFNODE("BlockStatement", null, { - $documentation: "A block statement", -}, AST_Block); - -var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { - $documentation: "The empty statement (empty block or simply a semicolon)", - _walk: function(visitor) { - return visitor._visit(this); - } -}, AST_Statement); - -var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { - $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", - $propdoc: { - body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.body._walk(visitor); - }); - } -}, AST_Statement); - -var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { - $documentation: "Statement with a label", - $propdoc: { - label: "[AST_Label] a label definition" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.label._walk(visitor); - this.body._walk(visitor); - }); - } -}, AST_StatementWithBody); - -var AST_DWLoop = DEFNODE("DWLoop", "condition", { - $documentation: "Base class for do/while statements", - $propdoc: { - condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.condition._walk(visitor); - this.body._walk(visitor); - }); - } -}, AST_StatementWithBody); - -var AST_Do = DEFNODE("Do", null, { - $documentation: "A `do` statement", -}, AST_DWLoop); - -var AST_While = DEFNODE("While", null, { - $documentation: "A `while` statement", -}, AST_DWLoop); - -var AST_For = DEFNODE("For", "init condition step", { - $documentation: "A `for` statement", - $propdoc: { - init: "[AST_Node?] the `for` initialization code, or null if empty", - condition: "[AST_Node?] the `for` termination clause, or null if empty", - step: "[AST_Node?] the `for` update clause, or null if empty" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - if (this.init) this.init._walk(visitor); - if (this.condition) this.condition._walk(visitor); - if (this.step) this.step._walk(visitor); - this.body._walk(visitor); - }); - } -}, AST_StatementWithBody); - -var AST_ForIn = DEFNODE("ForIn", "init name object", { - $documentation: "A `for ... in` statement", - $propdoc: { - init: "[AST_Node] the `for/in` initialization code", - name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var", - object: "[AST_Node] the object that we're looping through" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.init._walk(visitor); - this.object._walk(visitor); - this.body._walk(visitor); - }); - } -}, AST_StatementWithBody); - -var AST_With = DEFNODE("With", "expression", { - $documentation: "A `with` statement", - $propdoc: { - expression: "[AST_Node] the `with` expression" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.expression._walk(visitor); - this.body._walk(visitor); - }); - } -}, AST_StatementWithBody); - -/* -----[ scope and functions ]----- */ - -var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", { - $documentation: "Base class for all statements introducing a lexical scope", - $propdoc: { - directives: "[string*/S] an array of directives declared in this scope", - variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope", - functions: "[Object/S] like `variables`, but only lists function declarations", - uses_with: "[boolean/S] tells whether this scope uses the `with` statement", - uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", - parent_scope: "[AST_Scope?/S] link to the parent scope", - enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", - cname: "[integer/S] current index for mangling variables (used internally by the mangler)", - }, -}, AST_Block); - -var AST_Toplevel = DEFNODE("Toplevel", "globals", { - $documentation: "The toplevel scope", - $propdoc: { - globals: "[Object/S] a map of name -> SymbolDef for all undeclared names", - }, - wrap_enclose: function(arg_parameter_pairs) { - var self = this; - var args = []; - var parameters = []; - - arg_parameter_pairs.forEach(function(pair) { - var split = pair.split(":"); - - args.push(split[0]); - parameters.push(split[1]); - }); - - var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")"; - wrapped_tl = parse(wrapped_tl); - wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ - if (node instanceof AST_Directive && node.value == "$ORIG") { - return MAP.splice(self.body); - } - })); - return wrapped_tl; - }, - wrap_commonjs: function(name, export_all) { - var self = this; - var to_export = []; - if (export_all) { - self.figure_out_scope(); - self.walk(new TreeWalker(function(node){ - if (node instanceof AST_SymbolDeclaration && node.definition().global) { - if (!find_if(function(n){ return n.name == node.name }, to_export)) - to_export.push(node); - } - })); - } - var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))"; - wrapped_tl = parse(wrapped_tl); - wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ - if (node instanceof AST_SimpleStatement) { - node = node.body; - if (node instanceof AST_String) switch (node.getValue()) { - case "$ORIG": - return MAP.splice(self.body); - case "$EXPORTS": - var body = []; - to_export.forEach(function(sym){ - body.push(new AST_SimpleStatement({ - body: new AST_Assign({ - left: new AST_Sub({ - expression: new AST_SymbolRef({ name: "exports" }), - property: new AST_String({ value: sym.name }), - }), - operator: "=", - right: new AST_SymbolRef(sym), - }), - })); - }); - return MAP.splice(body); - } - } - })); - return wrapped_tl; - } -}, AST_Scope); - -var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", { - $documentation: "Base class for functions", - $propdoc: { - name: "[AST_SymbolDeclaration?] the name of this function", - argnames: "[AST_SymbolFunarg*] array of function arguments", - uses_arguments: "[boolean/S] tells whether this function accesses the arguments array" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - if (this.name) this.name._walk(visitor); - this.argnames.forEach(function(arg){ - arg._walk(visitor); - }); - walk_body(this, visitor); - }); - } -}, AST_Scope); - -var AST_Accessor = DEFNODE("Accessor", null, { - $documentation: "A setter/getter function" -}, AST_Lambda); - -var AST_Function = DEFNODE("Function", null, { - $documentation: "A function expression" -}, AST_Lambda); - -var AST_Defun = DEFNODE("Defun", null, { - $documentation: "A function definition" -}, AST_Lambda); - -/* -----[ JUMPS ]----- */ - -var AST_Jump = DEFNODE("Jump", null, { - $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)" -}, AST_Statement); - -var AST_Exit = DEFNODE("Exit", "value", { - $documentation: "Base class for “exits” (`return` and `throw`)", - $propdoc: { - value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" - }, - _walk: function(visitor) { - return visitor._visit(this, this.value && function(){ - this.value._walk(visitor); - }); - } -}, AST_Jump); - -var AST_Return = DEFNODE("Return", null, { - $documentation: "A `return` statement" -}, AST_Exit); - -var AST_Throw = DEFNODE("Throw", null, { - $documentation: "A `throw` statement" -}, AST_Exit); - -var AST_LoopControl = DEFNODE("LoopControl", "label", { - $documentation: "Base class for loop control statements (`break` and `continue`)", - $propdoc: { - label: "[AST_LabelRef?] the label, or null if none", - }, - _walk: function(visitor) { - return visitor._visit(this, this.label && function(){ - this.label._walk(visitor); - }); - } -}, AST_Jump); - -var AST_Break = DEFNODE("Break", null, { - $documentation: "A `break` statement" -}, AST_LoopControl); - -var AST_Continue = DEFNODE("Continue", null, { - $documentation: "A `continue` statement" -}, AST_LoopControl); - -/* -----[ IF ]----- */ - -var AST_If = DEFNODE("If", "condition alternative", { - $documentation: "A `if` statement", - $propdoc: { - condition: "[AST_Node] the `if` condition", - alternative: "[AST_Statement?] the `else` part, or null if not present" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.condition._walk(visitor); - this.body._walk(visitor); - if (this.alternative) this.alternative._walk(visitor); - }); - } -}, AST_StatementWithBody); - -/* -----[ SWITCH ]----- */ - -var AST_Switch = DEFNODE("Switch", "expression", { - $documentation: "A `switch` statement", - $propdoc: { - expression: "[AST_Node] the `switch` “discriminant”" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.expression._walk(visitor); - walk_body(this, visitor); - }); - } -}, AST_Block); - -var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { - $documentation: "Base class for `switch` branches", -}, AST_Block); - -var AST_Default = DEFNODE("Default", null, { - $documentation: "A `default` switch branch", -}, AST_SwitchBranch); - -var AST_Case = DEFNODE("Case", "expression", { - $documentation: "A `case` switch branch", - $propdoc: { - expression: "[AST_Node] the `case` expression" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.expression._walk(visitor); - walk_body(this, visitor); - }); - } -}, AST_SwitchBranch); - -/* -----[ EXCEPTIONS ]----- */ - -var AST_Try = DEFNODE("Try", "bcatch bfinally", { - $documentation: "A `try` statement", - $propdoc: { - bcatch: "[AST_Catch?] the catch block, or null if not present", - bfinally: "[AST_Finally?] the finally block, or null if not present" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - walk_body(this, visitor); - if (this.bcatch) this.bcatch._walk(visitor); - if (this.bfinally) this.bfinally._walk(visitor); - }); - } -}, AST_Block); - -// XXX: this is wrong according to ECMA-262 (12.4). the catch block -// should introduce another scope, as the argname should be visible -// only inside the catch block. However, doing it this way because of -// IE which simply introduces the name in the surrounding scope. If -// we ever want to fix this then AST_Catch should inherit from -// AST_Scope. -var AST_Catch = DEFNODE("Catch", "argname", { - $documentation: "A `catch` node; only makes sense as part of a `try` statement", - $propdoc: { - argname: "[AST_SymbolCatch] symbol for the exception" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.argname._walk(visitor); - walk_body(this, visitor); - }); - } -}, AST_Block); - -var AST_Finally = DEFNODE("Finally", null, { - $documentation: "A `finally` node; only makes sense as part of a `try` statement" -}, AST_Block); - -/* -----[ VAR/CONST ]----- */ - -var AST_Definitions = DEFNODE("Definitions", "definitions", { - $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", - $propdoc: { - definitions: "[AST_VarDef*] array of variable definitions" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.definitions.forEach(function(def){ - def._walk(visitor); - }); - }); - } -}, AST_Statement); - -var AST_Var = DEFNODE("Var", null, { - $documentation: "A `var` statement" -}, AST_Definitions); - -var AST_Const = DEFNODE("Const", null, { - $documentation: "A `const` statement" -}, AST_Definitions); - -var AST_VarDef = DEFNODE("VarDef", "name value", { - $documentation: "A variable declaration; only appears in a AST_Definitions node", - $propdoc: { - name: "[AST_SymbolVar|AST_SymbolConst] name of the variable", - value: "[AST_Node?] initializer, or null of there's no initializer" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.name._walk(visitor); - if (this.value) this.value._walk(visitor); - }); - } -}); - -/* -----[ OTHER ]----- */ - -var AST_Call = DEFNODE("Call", "expression args", { - $documentation: "A function call expression", - $propdoc: { - expression: "[AST_Node] expression to invoke as function", - args: "[AST_Node*] array of arguments" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.expression._walk(visitor); - this.args.forEach(function(arg){ - arg._walk(visitor); - }); - }); - } -}); - -var AST_New = DEFNODE("New", null, { - $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" -}, AST_Call); - -var AST_Seq = DEFNODE("Seq", "car cdr", { - $documentation: "A sequence expression (two comma-separated expressions)", - $propdoc: { - car: "[AST_Node] first element in sequence", - cdr: "[AST_Node] second element in sequence" - }, - $cons: function(x, y) { - var seq = new AST_Seq(x); - seq.car = x; - seq.cdr = y; - return seq; - }, - $from_array: function(array) { - if (array.length == 0) return null; - if (array.length == 1) return array[0].clone(); - var list = null; - for (var i = array.length; --i >= 0;) { - list = AST_Seq.cons(array[i], list); - } - var p = list; - while (p) { - if (p.cdr && !p.cdr.cdr) { - p.cdr = p.cdr.car; - break; - } - p = p.cdr; - } - return list; - }, - to_array: function() { - var p = this, a = []; - while (p) { - a.push(p.car); - if (p.cdr && !(p.cdr instanceof AST_Seq)) { - a.push(p.cdr); - break; - } - p = p.cdr; - } - return a; - }, - add: function(node) { - var p = this; - while (p) { - if (!(p.cdr instanceof AST_Seq)) { - var cell = AST_Seq.cons(p.cdr, node); - return p.cdr = cell; - } - p = p.cdr; - } - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.car._walk(visitor); - if (this.cdr) this.cdr._walk(visitor); - }); - } -}); - -var AST_PropAccess = DEFNODE("PropAccess", "expression property", { - $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", - $propdoc: { - expression: "[AST_Node] the “container” expression", - property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node" - } -}); - -var AST_Dot = DEFNODE("Dot", null, { - $documentation: "A dotted property access expression", - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.expression._walk(visitor); - }); - } -}, AST_PropAccess); - -var AST_Sub = DEFNODE("Sub", null, { - $documentation: "Index-style property access, i.e. `a[\"foo\"]`", - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.expression._walk(visitor); - this.property._walk(visitor); - }); - } -}, AST_PropAccess); - -var AST_Unary = DEFNODE("Unary", "operator expression", { - $documentation: "Base class for unary expressions", - $propdoc: { - operator: "[string] the operator", - expression: "[AST_Node] expression that this unary operator applies to" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.expression._walk(visitor); - }); - } -}); - -var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { - $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" -}, AST_Unary); - -var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { - $documentation: "Unary postfix expression, i.e. `i++`" -}, AST_Unary); - -var AST_Binary = DEFNODE("Binary", "left operator right", { - $documentation: "Binary expression, i.e. `a + b`", - $propdoc: { - left: "[AST_Node] left-hand side expression", - operator: "[string] the operator", - right: "[AST_Node] right-hand side expression" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.left._walk(visitor); - this.right._walk(visitor); - }); - } -}); - -var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { - $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", - $propdoc: { - condition: "[AST_Node]", - consequent: "[AST_Node]", - alternative: "[AST_Node]" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.condition._walk(visitor); - this.consequent._walk(visitor); - this.alternative._walk(visitor); - }); - } -}); - -var AST_Assign = DEFNODE("Assign", null, { - $documentation: "An assignment expression — `a = b + 5`", -}, AST_Binary); - -/* -----[ LITERALS ]----- */ - -var AST_Array = DEFNODE("Array", "elements", { - $documentation: "An array literal", - $propdoc: { - elements: "[AST_Node*] array of elements" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.elements.forEach(function(el){ - el._walk(visitor); - }); - }); - } -}); - -var AST_Object = DEFNODE("Object", "properties", { - $documentation: "An object literal", - $propdoc: { - properties: "[AST_ObjectProperty*] array of properties" - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.properties.forEach(function(prop){ - prop._walk(visitor); - }); - }); - } -}); - -var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { - $documentation: "Base class for literal object properties", - $propdoc: { - key: "[string] the property name; it's always a plain string in our AST, no matter if it was a string, number or identifier in original code", - value: "[AST_Node] property value. For setters and getters this is an AST_Function." - }, - _walk: function(visitor) { - return visitor._visit(this, function(){ - this.value._walk(visitor); - }); - } -}); - -var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, { - $documentation: "A key: value object property", -}, AST_ObjectProperty); - -var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { - $documentation: "An object setter property", -}, AST_ObjectProperty); - -var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { - $documentation: "An object getter property", -}, AST_ObjectProperty); - -var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { - $propdoc: { - name: "[string] name of this symbol", - scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", - thedef: "[SymbolDef/S] the definition of this symbol" - }, - $documentation: "Base class for all symbols", -}); - -var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, { - $documentation: "The name of a property accessor (setter/getter function)" -}, AST_Symbol); - -var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { - $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", - $propdoc: { - init: "[AST_Node*/S] array of initializers for this declaration." - } -}, AST_Symbol); - -var AST_SymbolVar = DEFNODE("SymbolVar", null, { - $documentation: "Symbol defining a variable", -}, AST_SymbolDeclaration); - -var AST_SymbolConst = DEFNODE("SymbolConst", null, { - $documentation: "A constant declaration" -}, AST_SymbolDeclaration); - -var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { - $documentation: "Symbol naming a function argument", -}, AST_SymbolVar); - -var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { - $documentation: "Symbol defining a function", -}, AST_SymbolDeclaration); - -var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { - $documentation: "Symbol naming a function expression", -}, AST_SymbolDeclaration); - -var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { - $documentation: "Symbol naming the exception in catch", -}, AST_SymbolDeclaration); - -var AST_Label = DEFNODE("Label", "references", { - $documentation: "Symbol naming a label (declaration)", - $propdoc: { - references: "[AST_LabelRef*] a list of nodes referring to this label" - } -}, AST_Symbol); - -var AST_SymbolRef = DEFNODE("SymbolRef", null, { - $documentation: "Reference to some symbol (not definition/declaration)", -}, AST_Symbol); - -var AST_LabelRef = DEFNODE("LabelRef", null, { - $documentation: "Reference to a label symbol", -}, AST_Symbol); - -var AST_This = DEFNODE("This", null, { - $documentation: "The `this` symbol", -}, AST_Symbol); - -var AST_Constant = DEFNODE("Constant", null, { - $documentation: "Base class for all constants", - getValue: function() { - return this.value; - } -}); - -var AST_String = DEFNODE("String", "value", { - $documentation: "A string literal", - $propdoc: { - value: "[string] the contents of this string" - } -}, AST_Constant); - -var AST_Number = DEFNODE("Number", "value", { - $documentation: "A number literal", - $propdoc: { - value: "[number] the numeric value" - } -}, AST_Constant); - -var AST_RegExp = DEFNODE("RegExp", "value", { - $documentation: "A regexp literal", - $propdoc: { - value: "[RegExp] the actual regexp" - } -}, AST_Constant); - -var AST_Atom = DEFNODE("Atom", null, { - $documentation: "Base class for atoms", -}, AST_Constant); - -var AST_Null = DEFNODE("Null", null, { - $documentation: "The `null` atom", - value: null -}, AST_Atom); - -var AST_NaN = DEFNODE("NaN", null, { - $documentation: "The impossible value", - value: 0/0 -}, AST_Atom); - -var AST_Undefined = DEFNODE("Undefined", null, { - $documentation: "The `undefined` value", - value: (function(){}()) -}, AST_Atom); - -var AST_Hole = DEFNODE("Hole", null, { - $documentation: "A hole in an array", - value: (function(){}()) -}, AST_Atom); - -var AST_Infinity = DEFNODE("Infinity", null, { - $documentation: "The `Infinity` value", - value: 1/0 -}, AST_Atom); - -var AST_Boolean = DEFNODE("Boolean", null, { - $documentation: "Base class for booleans", -}, AST_Atom); - -var AST_False = DEFNODE("False", null, { - $documentation: "The `false` atom", - value: false -}, AST_Boolean); - -var AST_True = DEFNODE("True", null, { - $documentation: "The `true` atom", - value: true -}, AST_Boolean); - -/* -----[ TreeWalker ]----- */ - -function TreeWalker(callback) { - this.visit = callback; - this.stack = []; -}; -TreeWalker.prototype = { - _visit: function(node, descend) { - this.stack.push(node); - var ret = this.visit(node, descend ? function(){ - descend.call(node); - } : noop); - if (!ret && descend) { - descend.call(node); - } - this.stack.pop(); - return ret; - }, - parent: function(n) { - return this.stack[this.stack.length - 2 - (n || 0)]; - }, - push: function (node) { - this.stack.push(node); - }, - pop: function() { - return this.stack.pop(); - }, - self: function() { - return this.stack[this.stack.length - 1]; - }, - find_parent: function(type) { - var stack = this.stack; - for (var i = stack.length; --i >= 0;) { - var x = stack[i]; - if (x instanceof type) return x; - } - }, - in_boolean_context: function() { - var stack = this.stack; - var i = stack.length, self = stack[--i]; - while (i > 0) { - var p = stack[--i]; - if ((p instanceof AST_If && p.condition === self) || - (p instanceof AST_Conditional && p.condition === self) || - (p instanceof AST_DWLoop && p.condition === self) || - (p instanceof AST_For && p.condition === self) || - (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self)) - { - return true; - } - if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||"))) - return false; - self = p; - } - }, - loopcontrol_target: function(label) { - var stack = this.stack; - if (label) { - for (var i = stack.length; --i >= 0;) { - var x = stack[i]; - if (x instanceof AST_LabeledStatement && x.label.name == label.name) { - return x.body; - } - } - } else { - for (var i = stack.length; --i >= 0;) { - var x = stack[i]; - if (x instanceof AST_Switch - || x instanceof AST_For - || x instanceof AST_ForIn - || x instanceof AST_DWLoop) return x; - } - } - } -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/compress.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/compress.js deleted file mode 100644 index 57554fa5e..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/compress.js +++ /dev/null @@ -1,2028 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -function Compressor(options, false_by_default) { - if (!(this instanceof Compressor)) - return new Compressor(options, false_by_default); - TreeTransformer.call(this, this.before, this.after); - this.options = defaults(options, { - sequences : !false_by_default, - properties : !false_by_default, - dead_code : !false_by_default, - drop_debugger : !false_by_default, - unsafe : false, - unsafe_comps : false, - conditionals : !false_by_default, - comparisons : !false_by_default, - evaluate : !false_by_default, - booleans : !false_by_default, - loops : !false_by_default, - unused : !false_by_default, - hoist_funs : !false_by_default, - hoist_vars : false, - if_return : !false_by_default, - join_vars : !false_by_default, - cascade : !false_by_default, - side_effects : !false_by_default, - screw_ie8 : false, - - warnings : true, - global_defs : {} - }, true); -}; - -Compressor.prototype = new TreeTransformer; -merge(Compressor.prototype, { - option: function(key) { return this.options[key] }, - warn: function() { - if (this.options.warnings) - AST_Node.warn.apply(AST_Node, arguments); - }, - before: function(node, descend, in_list) { - if (node._squeezed) return node; - if (node instanceof AST_Scope) { - node.drop_unused(this); - node = node.hoist_declarations(this); - } - descend(node, this); - node = node.optimize(this); - if (node instanceof AST_Scope) { - // dead code removal might leave further unused declarations. - // this'll usually save very few bytes, but the performance - // hit seems negligible so I'll just drop it here. - - // no point to repeat warnings. - var save_warnings = this.options.warnings; - this.options.warnings = false; - node.drop_unused(this); - this.options.warnings = save_warnings; - } - node._squeezed = true; - return node; - } -}); - -(function(){ - - function OPT(node, optimizer) { - node.DEFMETHOD("optimize", function(compressor){ - var self = this; - if (self._optimized) return self; - var opt = optimizer(self, compressor); - opt._optimized = true; - if (opt === self) return opt; - return opt.transform(compressor); - }); - }; - - OPT(AST_Node, function(self, compressor){ - return self; - }); - - AST_Node.DEFMETHOD("equivalent_to", function(node){ - // XXX: this is a rather expensive way to test two node's equivalence: - return this.print_to_string() == node.print_to_string(); - }); - - function make_node(ctor, orig, props) { - if (!props) props = {}; - if (orig) { - if (!props.start) props.start = orig.start; - if (!props.end) props.end = orig.end; - } - return new ctor(props); - }; - - function make_node_from_constant(compressor, val, orig) { - // XXX: WIP. - // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){ - // if (node instanceof AST_SymbolRef) { - // var scope = compressor.find_parent(AST_Scope); - // var def = scope.find_variable(node); - // node.thedef = def; - // return node; - // } - // })).transform(compressor); - - if (val instanceof AST_Node) return val.transform(compressor); - switch (typeof val) { - case "string": - return make_node(AST_String, orig, { - value: val - }).optimize(compressor); - case "number": - return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, { - value: val - }).optimize(compressor); - case "boolean": - return make_node(val ? AST_True : AST_False, orig).optimize(compressor); - case "undefined": - return make_node(AST_Undefined, orig).optimize(compressor); - default: - if (val === null) { - return make_node(AST_Null, orig).optimize(compressor); - } - if (val instanceof RegExp) { - return make_node(AST_RegExp, orig).optimize(compressor); - } - throw new Error(string_template("Can't handle constant of type: {type}", { - type: typeof val - })); - } - }; - - function as_statement_array(thing) { - if (thing === null) return []; - if (thing instanceof AST_BlockStatement) return thing.body; - if (thing instanceof AST_EmptyStatement) return []; - if (thing instanceof AST_Statement) return [ thing ]; - throw new Error("Can't convert thing to statement array"); - }; - - function is_empty(thing) { - if (thing === null) return true; - if (thing instanceof AST_EmptyStatement) return true; - if (thing instanceof AST_BlockStatement) return thing.body.length == 0; - return false; - }; - - function loop_body(x) { - if (x instanceof AST_Switch) return x; - if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) { - return (x.body instanceof AST_BlockStatement ? x.body : x); - } - return x; - }; - - function tighten_body(statements, compressor) { - var CHANGED; - do { - CHANGED = false; - statements = eliminate_spurious_blocks(statements); - if (compressor.option("dead_code")) { - statements = eliminate_dead_code(statements, compressor); - } - if (compressor.option("if_return")) { - statements = handle_if_return(statements, compressor); - } - if (compressor.option("sequences")) { - statements = sequencesize(statements, compressor); - } - if (compressor.option("join_vars")) { - statements = join_consecutive_vars(statements, compressor); - } - } while (CHANGED); - return statements; - - function eliminate_spurious_blocks(statements) { - var seen_dirs = []; - return statements.reduce(function(a, stat){ - if (stat instanceof AST_BlockStatement) { - CHANGED = true; - a.push.apply(a, eliminate_spurious_blocks(stat.body)); - } else if (stat instanceof AST_EmptyStatement) { - CHANGED = true; - } else if (stat instanceof AST_Directive) { - if (seen_dirs.indexOf(stat.value) < 0) { - a.push(stat); - seen_dirs.push(stat.value); - } else { - CHANGED = true; - } - } else { - a.push(stat); - } - return a; - }, []); - }; - - function handle_if_return(statements, compressor) { - var self = compressor.self(); - var in_lambda = self instanceof AST_Lambda; - var ret = []; - loop: for (var i = statements.length; --i >= 0;) { - var stat = statements[i]; - switch (true) { - case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0): - CHANGED = true; - // note, ret.length is probably always zero - // because we drop unreachable code before this - // step. nevertheless, it's good to check. - continue loop; - case stat instanceof AST_If: - if (stat.body instanceof AST_Return) { - //--- - // pretty silly case, but: - // if (foo()) return; return; ==> foo(); return; - if (((in_lambda && ret.length == 0) - || (ret[0] instanceof AST_Return && !ret[0].value)) - && !stat.body.value && !stat.alternative) { - CHANGED = true; - var cond = make_node(AST_SimpleStatement, stat.condition, { - body: stat.condition - }); - ret.unshift(cond); - continue loop; - } - //--- - // if (foo()) return x; return y; ==> return foo() ? x : y; - if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) { - CHANGED = true; - stat = stat.clone(); - stat.alternative = ret[0]; - ret[0] = stat.transform(compressor); - continue loop; - } - //--- - // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; - if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) { - CHANGED = true; - stat = stat.clone(); - stat.alternative = ret[0] || make_node(AST_Return, stat, { - value: make_node(AST_Undefined, stat) - }); - ret[0] = stat.transform(compressor); - continue loop; - } - //--- - // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... } - if (!stat.body.value && in_lambda) { - CHANGED = true; - stat = stat.clone(); - stat.condition = stat.condition.negate(compressor); - stat.body = make_node(AST_BlockStatement, stat, { - body: as_statement_array(stat.alternative).concat(ret) - }); - stat.alternative = null; - ret = [ stat.transform(compressor) ]; - continue loop; - } - //--- - if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement - && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) { - CHANGED = true; - ret.push(make_node(AST_Return, ret[0], { - value: make_node(AST_Undefined, ret[0]) - }).transform(compressor)); - ret = as_statement_array(stat.alternative).concat(ret); - ret.unshift(stat); - continue loop; - } - } - - var ab = aborts(stat.body); - var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null; - if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) - || (ab instanceof AST_Continue && self === loop_body(lct)) - || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { - if (ab.label) { - remove(ab.label.thedef.references, ab.label); - } - CHANGED = true; - var body = as_statement_array(stat.body).slice(0, -1); - stat = stat.clone(); - stat.condition = stat.condition.negate(compressor); - stat.body = make_node(AST_BlockStatement, stat, { - body: ret - }); - stat.alternative = make_node(AST_BlockStatement, stat, { - body: body - }); - ret = [ stat.transform(compressor) ]; - continue loop; - } - - var ab = aborts(stat.alternative); - var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null; - if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) - || (ab instanceof AST_Continue && self === loop_body(lct)) - || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { - if (ab.label) { - remove(ab.label.thedef.references, ab.label); - } - CHANGED = true; - stat = stat.clone(); - stat.body = make_node(AST_BlockStatement, stat.body, { - body: as_statement_array(stat.body).concat(ret) - }); - stat.alternative = make_node(AST_BlockStatement, stat.alternative, { - body: as_statement_array(stat.alternative).slice(0, -1) - }); - ret = [ stat.transform(compressor) ]; - continue loop; - } - - ret.unshift(stat); - break; - default: - ret.unshift(stat); - break; - } - } - return ret; - }; - - function eliminate_dead_code(statements, compressor) { - var has_quit = false; - var orig = statements.length; - var self = compressor.self(); - statements = statements.reduce(function(a, stat){ - if (has_quit) { - extract_declarations_from_unreachable_code(compressor, stat, a); - } else { - if (stat instanceof AST_LoopControl) { - var lct = compressor.loopcontrol_target(stat.label); - if ((stat instanceof AST_Break - && lct instanceof AST_BlockStatement - && loop_body(lct) === self) || (stat instanceof AST_Continue - && loop_body(lct) === self)) { - if (stat.label) { - remove(stat.label.thedef.references, stat.label); - } - } else { - a.push(stat); - } - } else { - a.push(stat); - } - if (aborts(stat)) has_quit = true; - } - return a; - }, []); - CHANGED = statements.length != orig; - return statements; - }; - - function sequencesize(statements, compressor) { - if (statements.length < 2) return statements; - var seq = [], ret = []; - function push_seq() { - seq = AST_Seq.from_array(seq); - if (seq) ret.push(make_node(AST_SimpleStatement, seq, { - body: seq - })); - seq = []; - }; - statements.forEach(function(stat){ - if (stat instanceof AST_SimpleStatement) seq.push(stat.body); - else push_seq(), ret.push(stat); - }); - push_seq(); - ret = sequencesize_2(ret, compressor); - CHANGED = ret.length != statements.length; - return ret; - }; - - function sequencesize_2(statements, compressor) { - function cons_seq(right) { - ret.pop(); - var left = prev.body; - if (left instanceof AST_Seq) { - left.add(right); - } else { - left = AST_Seq.cons(left, right); - } - return left.transform(compressor); - }; - var ret = [], prev = null; - statements.forEach(function(stat){ - if (prev) { - if (stat instanceof AST_For) { - var opera = {}; - try { - prev.body.walk(new TreeWalker(function(node){ - if (node instanceof AST_Binary && node.operator == "in") - throw opera; - })); - if (stat.init && !(stat.init instanceof AST_Definitions)) { - stat.init = cons_seq(stat.init); - } - else if (!stat.init) { - stat.init = prev.body; - ret.pop(); - } - } catch(ex) { - if (ex !== opera) throw ex; - } - } - else if (stat instanceof AST_If) { - stat.condition = cons_seq(stat.condition); - } - else if (stat instanceof AST_With) { - stat.expression = cons_seq(stat.expression); - } - else if (stat instanceof AST_Exit && stat.value) { - stat.value = cons_seq(stat.value); - } - else if (stat instanceof AST_Exit) { - stat.value = cons_seq(make_node(AST_Undefined, stat)); - } - else if (stat instanceof AST_Switch) { - stat.expression = cons_seq(stat.expression); - } - } - ret.push(stat); - prev = stat instanceof AST_SimpleStatement ? stat : null; - }); - return ret; - }; - - function join_consecutive_vars(statements, compressor) { - var prev = null; - return statements.reduce(function(a, stat){ - if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) { - prev.definitions = prev.definitions.concat(stat.definitions); - CHANGED = true; - } - else if (stat instanceof AST_For - && prev instanceof AST_Definitions - && (!stat.init || stat.init.TYPE == prev.TYPE)) { - CHANGED = true; - a.pop(); - if (stat.init) { - stat.init.definitions = prev.definitions.concat(stat.init.definitions); - } else { - stat.init = prev; - } - a.push(stat); - prev = stat; - } - else { - prev = stat; - a.push(stat); - } - return a; - }, []); - }; - - }; - - function extract_declarations_from_unreachable_code(compressor, stat, target) { - compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start); - stat.walk(new TreeWalker(function(node){ - if (node instanceof AST_Definitions) { - compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start); - node.remove_initializers(); - target.push(node); - return true; - } - if (node instanceof AST_Defun) { - target.push(node); - return true; - } - if (node instanceof AST_Scope) { - return true; - } - })); - }; - - /* -----[ boolean/negation helpers ]----- */ - - // methods to determine whether an expression has a boolean result type - (function (def){ - var unary_bool = [ "!", "delete" ]; - var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ]; - def(AST_Node, function(){ return false }); - def(AST_UnaryPrefix, function(){ - return member(this.operator, unary_bool); - }); - def(AST_Binary, function(){ - return member(this.operator, binary_bool) || - ( (this.operator == "&&" || this.operator == "||") && - this.left.is_boolean() && this.right.is_boolean() ); - }); - def(AST_Conditional, function(){ - return this.consequent.is_boolean() && this.alternative.is_boolean(); - }); - def(AST_Assign, function(){ - return this.operator == "=" && this.right.is_boolean(); - }); - def(AST_Seq, function(){ - return this.cdr.is_boolean(); - }); - def(AST_True, function(){ return true }); - def(AST_False, function(){ return true }); - })(function(node, func){ - node.DEFMETHOD("is_boolean", func); - }); - - // methods to determine if an expression has a string result type - (function (def){ - def(AST_Node, function(){ return false }); - def(AST_String, function(){ return true }); - def(AST_UnaryPrefix, function(){ - return this.operator == "typeof"; - }); - def(AST_Binary, function(compressor){ - return this.operator == "+" && - (this.left.is_string(compressor) || this.right.is_string(compressor)); - }); - def(AST_Assign, function(compressor){ - return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); - }); - def(AST_Seq, function(compressor){ - return this.cdr.is_string(compressor); - }); - def(AST_Conditional, function(compressor){ - return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); - }); - def(AST_Call, function(compressor){ - return compressor.option("unsafe") - && this.expression instanceof AST_SymbolRef - && this.expression.name == "String" - && this.expression.undeclared(); - }); - })(function(node, func){ - node.DEFMETHOD("is_string", func); - }); - - function best_of(ast1, ast2) { - return ast1.print_to_string().length > - ast2.print_to_string().length - ? ast2 : ast1; - }; - - // methods to evaluate a constant expression - (function (def){ - // The evaluate method returns an array with one or two - // elements. If the node has been successfully reduced to a - // constant, then the second element tells us the value; - // otherwise the second element is missing. The first element - // of the array is always an AST_Node descendant; when - // evaluation was successful it's a node that represents the - // constant; otherwise it's the original node. - AST_Node.DEFMETHOD("evaluate", function(compressor){ - if (!compressor.option("evaluate")) return [ this ]; - try { - var val = this._eval(), ast = make_node_from_constant(compressor, val, this); - return [ best_of(ast, this), val ]; - } catch(ex) { - if (ex !== def) throw ex; - return [ this ]; - } - }); - def(AST_Statement, function(){ - throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); - }); - def(AST_Function, function(){ - // XXX: AST_Function inherits from AST_Scope, which itself - // inherits from AST_Statement; however, an AST_Function - // isn't really a statement. This could byte in other - // places too. :-( Wish JS had multiple inheritance. - return [ this ]; - }); - function ev(node) { - return node._eval(); - }; - def(AST_Node, function(){ - throw def; // not constant - }); - def(AST_Constant, function(){ - return this.getValue(); - }); - def(AST_UnaryPrefix, function(){ - var e = this.expression; - switch (this.operator) { - case "!": return !ev(e); - case "typeof": - // Function would be evaluated to an array and so typeof would - // incorrectly return 'object'. Hence making is a special case. - if (e instanceof AST_Function) return typeof function(){}; - - e = ev(e); - - // typeof returns "object" or "function" on different platforms - // so cannot evaluate reliably - if (e instanceof RegExp) throw def; - - return typeof e; - case "void": return void ev(e); - case "~": return ~ev(e); - case "-": - e = ev(e); - if (e === 0) throw def; - return -e; - case "+": return +ev(e); - } - throw def; - }); - def(AST_Binary, function(){ - var left = this.left, right = this.right; - switch (this.operator) { - case "&&" : return ev(left) && ev(right); - case "||" : return ev(left) || ev(right); - case "|" : return ev(left) | ev(right); - case "&" : return ev(left) & ev(right); - case "^" : return ev(left) ^ ev(right); - case "+" : return ev(left) + ev(right); - case "*" : return ev(left) * ev(right); - case "/" : return ev(left) / ev(right); - case "%" : return ev(left) % ev(right); - case "-" : return ev(left) - ev(right); - case "<<" : return ev(left) << ev(right); - case ">>" : return ev(left) >> ev(right); - case ">>>" : return ev(left) >>> ev(right); - case "==" : return ev(left) == ev(right); - case "===" : return ev(left) === ev(right); - case "!=" : return ev(left) != ev(right); - case "!==" : return ev(left) !== ev(right); - case "<" : return ev(left) < ev(right); - case "<=" : return ev(left) <= ev(right); - case ">" : return ev(left) > ev(right); - case ">=" : return ev(left) >= ev(right); - case "in" : return ev(left) in ev(right); - case "instanceof" : return ev(left) instanceof ev(right); - } - throw def; - }); - def(AST_Conditional, function(){ - return ev(this.condition) - ? ev(this.consequent) - : ev(this.alternative); - }); - def(AST_SymbolRef, function(){ - var d = this.definition(); - if (d && d.constant && d.init) return ev(d.init); - throw def; - }); - })(function(node, func){ - node.DEFMETHOD("_eval", func); - }); - - // method to negate an expression - (function(def){ - function basic_negation(exp) { - return make_node(AST_UnaryPrefix, exp, { - operator: "!", - expression: exp - }); - }; - def(AST_Node, function(){ - return basic_negation(this); - }); - def(AST_Statement, function(){ - throw new Error("Cannot negate a statement"); - }); - def(AST_Function, function(){ - return basic_negation(this); - }); - def(AST_UnaryPrefix, function(){ - if (this.operator == "!") - return this.expression; - return basic_negation(this); - }); - def(AST_Seq, function(compressor){ - var self = this.clone(); - self.cdr = self.cdr.negate(compressor); - return self; - }); - def(AST_Conditional, function(compressor){ - var self = this.clone(); - self.consequent = self.consequent.negate(compressor); - self.alternative = self.alternative.negate(compressor); - return best_of(basic_negation(this), self); - }); - def(AST_Binary, function(compressor){ - var self = this.clone(), op = this.operator; - if (compressor.option("unsafe_comps")) { - switch (op) { - case "<=" : self.operator = ">" ; return self; - case "<" : self.operator = ">=" ; return self; - case ">=" : self.operator = "<" ; return self; - case ">" : self.operator = "<=" ; return self; - } - } - switch (op) { - case "==" : self.operator = "!="; return self; - case "!=" : self.operator = "=="; return self; - case "===": self.operator = "!=="; return self; - case "!==": self.operator = "==="; return self; - case "&&": - self.operator = "||"; - self.left = self.left.negate(compressor); - self.right = self.right.negate(compressor); - return best_of(basic_negation(this), self); - case "||": - self.operator = "&&"; - self.left = self.left.negate(compressor); - self.right = self.right.negate(compressor); - return best_of(basic_negation(this), self); - } - return basic_negation(this); - }); - })(function(node, func){ - node.DEFMETHOD("negate", function(compressor){ - return func.call(this, compressor); - }); - }); - - // determine if expression has side effects - (function(def){ - def(AST_Node, function(){ return true }); - - def(AST_EmptyStatement, function(){ return false }); - def(AST_Constant, function(){ return false }); - def(AST_This, function(){ return false }); - - def(AST_Block, function(){ - for (var i = this.body.length; --i >= 0;) { - if (this.body[i].has_side_effects()) - return true; - } - return false; - }); - - def(AST_SimpleStatement, function(){ - return this.body.has_side_effects(); - }); - def(AST_Defun, function(){ return true }); - def(AST_Function, function(){ return false }); - def(AST_Binary, function(){ - return this.left.has_side_effects() - || this.right.has_side_effects(); - }); - def(AST_Assign, function(){ return true }); - def(AST_Conditional, function(){ - return this.condition.has_side_effects() - || this.consequent.has_side_effects() - || this.alternative.has_side_effects(); - }); - def(AST_Unary, function(){ - return this.operator == "delete" - || this.operator == "++" - || this.operator == "--" - || this.expression.has_side_effects(); - }); - def(AST_SymbolRef, function(){ return false }); - def(AST_Object, function(){ - for (var i = this.properties.length; --i >= 0;) - if (this.properties[i].has_side_effects()) - return true; - return false; - }); - def(AST_ObjectProperty, function(){ - return this.value.has_side_effects(); - }); - def(AST_Array, function(){ - for (var i = this.elements.length; --i >= 0;) - if (this.elements[i].has_side_effects()) - return true; - return false; - }); - // def(AST_Dot, function(){ - // return this.expression.has_side_effects(); - // }); - // def(AST_Sub, function(){ - // return this.expression.has_side_effects() - // || this.property.has_side_effects(); - // }); - def(AST_PropAccess, function(){ - return true; - }); - def(AST_Seq, function(){ - return this.car.has_side_effects() - || this.cdr.has_side_effects(); - }); - })(function(node, func){ - node.DEFMETHOD("has_side_effects", func); - }); - - // tell me if a statement aborts - function aborts(thing) { - return thing && thing.aborts(); - }; - (function(def){ - def(AST_Statement, function(){ return null }); - def(AST_Jump, function(){ return this }); - function block_aborts(){ - var n = this.body.length; - return n > 0 && aborts(this.body[n - 1]); - }; - def(AST_BlockStatement, block_aborts); - def(AST_SwitchBranch, block_aborts); - def(AST_If, function(){ - return this.alternative && aborts(this.body) && aborts(this.alternative); - }); - })(function(node, func){ - node.DEFMETHOD("aborts", func); - }); - - /* -----[ optimizers ]----- */ - - OPT(AST_Directive, function(self, compressor){ - if (self.scope.has_directive(self.value) !== self.scope) { - return make_node(AST_EmptyStatement, self); - } - return self; - }); - - OPT(AST_Debugger, function(self, compressor){ - if (compressor.option("drop_debugger")) - return make_node(AST_EmptyStatement, self); - return self; - }); - - OPT(AST_LabeledStatement, function(self, compressor){ - if (self.body instanceof AST_Break - && compressor.loopcontrol_target(self.body.label) === self.body) { - return make_node(AST_EmptyStatement, self); - } - return self.label.references.length == 0 ? self.body : self; - }); - - OPT(AST_Block, function(self, compressor){ - self.body = tighten_body(self.body, compressor); - return self; - }); - - OPT(AST_BlockStatement, function(self, compressor){ - self.body = tighten_body(self.body, compressor); - switch (self.body.length) { - case 1: return self.body[0]; - case 0: return make_node(AST_EmptyStatement, self); - } - return self; - }); - - AST_Scope.DEFMETHOD("drop_unused", function(compressor){ - var self = this; - if (compressor.option("unused") - && !(self instanceof AST_Toplevel) - && !self.uses_eval - ) { - var in_use = []; - var initializations = new Dictionary(); - // pass 1: find out which symbols are directly used in - // this scope (not in nested scopes). - var scope = this; - var tw = new TreeWalker(function(node, descend){ - if (node !== self) { - if (node instanceof AST_Defun) { - initializations.add(node.name.name, node); - return true; // don't go in nested scopes - } - if (node instanceof AST_Definitions && scope === self) { - node.definitions.forEach(function(def){ - if (def.value) { - initializations.add(def.name.name, def.value); - if (def.value.has_side_effects()) { - def.value.walk(tw); - } - } - }); - return true; - } - if (node instanceof AST_SymbolRef) { - push_uniq(in_use, node.definition()); - return true; - } - if (node instanceof AST_Scope) { - var save_scope = scope; - scope = node; - descend(); - scope = save_scope; - return true; - } - } - }); - self.walk(tw); - // pass 2: for every used symbol we need to walk its - // initialization code to figure out if it uses other - // symbols (that may not be in_use). - for (var i = 0; i < in_use.length; ++i) { - in_use[i].orig.forEach(function(decl){ - // undeclared globals will be instanceof AST_SymbolRef - var init = initializations.get(decl.name); - if (init) init.forEach(function(init){ - var tw = new TreeWalker(function(node){ - if (node instanceof AST_SymbolRef) { - push_uniq(in_use, node.definition()); - } - }); - init.walk(tw); - }); - }); - } - // pass 3: we should drop declarations not in_use - var tt = new TreeTransformer( - function before(node, descend, in_list) { - if (node instanceof AST_Lambda) { - for (var a = node.argnames, i = a.length; --i >= 0;) { - var sym = a[i]; - if (sym.unreferenced()) { - a.pop(); - compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", { - name : sym.name, - file : sym.start.file, - line : sym.start.line, - col : sym.start.col - }); - } - else break; - } - } - if (node instanceof AST_Defun && node !== self) { - if (!member(node.name.definition(), in_use)) { - compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", { - name : node.name.name, - file : node.name.start.file, - line : node.name.start.line, - col : node.name.start.col - }); - return make_node(AST_EmptyStatement, node); - } - return node; - } - if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) { - var def = node.definitions.filter(function(def){ - if (member(def.name.definition(), in_use)) return true; - var w = { - name : def.name.name, - file : def.name.start.file, - line : def.name.start.line, - col : def.name.start.col - }; - if (def.value && def.value.has_side_effects()) { - def._unused_side_effects = true; - compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w); - return true; - } - compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w); - return false; - }); - // place uninitialized names at the start - def = mergeSort(def, function(a, b){ - if (!a.value && b.value) return -1; - if (!b.value && a.value) return 1; - return 0; - }); - // for unused names whose initialization has - // side effects, we can cascade the init. code - // into the next one, or next statement. - var side_effects = []; - for (var i = 0; i < def.length;) { - var x = def[i]; - if (x._unused_side_effects) { - side_effects.push(x.value); - def.splice(i, 1); - } else { - if (side_effects.length > 0) { - side_effects.push(x.value); - x.value = AST_Seq.from_array(side_effects); - side_effects = []; - } - ++i; - } - } - if (side_effects.length > 0) { - side_effects = make_node(AST_BlockStatement, node, { - body: [ make_node(AST_SimpleStatement, node, { - body: AST_Seq.from_array(side_effects) - }) ] - }); - } else { - side_effects = null; - } - if (def.length == 0 && !side_effects) { - return make_node(AST_EmptyStatement, node); - } - if (def.length == 0) { - return side_effects; - } - node.definitions = def; - if (side_effects) { - side_effects.body.unshift(node); - node = side_effects; - } - return node; - } - if (node instanceof AST_For && node.init instanceof AST_BlockStatement) { - descend(node, this); - // certain combination of unused name + side effect leads to: - // https://github.com/mishoo/UglifyJS2/issues/44 - // that's an invalid AST. - // We fix it at this stage by moving the `var` outside the `for`. - var body = node.init.body.slice(0, -1); - node.init = node.init.body.slice(-1)[0].body; - body.push(node); - return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, { - body: body - }); - } - if (node instanceof AST_Scope && node !== self) - return node; - } - ); - self.transform(tt); - } - }); - - AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){ - var hoist_funs = compressor.option("hoist_funs"); - var hoist_vars = compressor.option("hoist_vars"); - var self = this; - if (hoist_funs || hoist_vars) { - var dirs = []; - var hoisted = []; - var vars = new Dictionary(), vars_found = 0, var_decl = 0; - // let's count var_decl first, we seem to waste a lot of - // space if we hoist `var` when there's only one. - self.walk(new TreeWalker(function(node){ - if (node instanceof AST_Scope && node !== self) - return true; - if (node instanceof AST_Var) { - ++var_decl; - return true; - } - })); - hoist_vars = hoist_vars && var_decl > 1; - var tt = new TreeTransformer( - function before(node) { - if (node !== self) { - if (node instanceof AST_Directive) { - dirs.push(node); - return make_node(AST_EmptyStatement, node); - } - if (node instanceof AST_Defun && hoist_funs) { - hoisted.push(node); - return make_node(AST_EmptyStatement, node); - } - if (node instanceof AST_Var && hoist_vars) { - node.definitions.forEach(function(def){ - vars.set(def.name.name, def); - ++vars_found; - }); - var seq = node.to_assignments(); - var p = tt.parent(); - if (p instanceof AST_ForIn && p.init === node) { - if (seq == null) return node.definitions[0].name; - return seq; - } - if (p instanceof AST_For && p.init === node) { - return seq; - } - if (!seq) return make_node(AST_EmptyStatement, node); - return make_node(AST_SimpleStatement, node, { - body: seq - }); - } - if (node instanceof AST_Scope) - return node; // to avoid descending in nested scopes - } - } - ); - self = self.transform(tt); - if (vars_found > 0) { - // collect only vars which don't show up in self's arguments list - var defs = []; - vars.each(function(def, name){ - if (self instanceof AST_Lambda - && find_if(function(x){ return x.name == def.name.name }, - self.argnames)) { - vars.del(name); - } else { - def = def.clone(); - def.value = null; - defs.push(def); - vars.set(name, def); - } - }); - if (defs.length > 0) { - // try to merge in assignments - for (var i = 0; i < self.body.length;) { - if (self.body[i] instanceof AST_SimpleStatement) { - var expr = self.body[i].body, sym, assign; - if (expr instanceof AST_Assign - && expr.operator == "=" - && (sym = expr.left) instanceof AST_Symbol - && vars.has(sym.name)) - { - var def = vars.get(sym.name); - if (def.value) break; - def.value = expr.right; - remove(defs, def); - defs.push(def); - self.body.splice(i, 1); - continue; - } - if (expr instanceof AST_Seq - && (assign = expr.car) instanceof AST_Assign - && assign.operator == "=" - && (sym = assign.left) instanceof AST_Symbol - && vars.has(sym.name)) - { - var def = vars.get(sym.name); - if (def.value) break; - def.value = assign.right; - remove(defs, def); - defs.push(def); - self.body[i].body = expr.cdr; - continue; - } - } - if (self.body[i] instanceof AST_EmptyStatement) { - self.body.splice(i, 1); - continue; - } - if (self.body[i] instanceof AST_BlockStatement) { - var tmp = [ i, 1 ].concat(self.body[i].body); - self.body.splice.apply(self.body, tmp); - continue; - } - break; - } - defs = make_node(AST_Var, self, { - definitions: defs - }); - hoisted.push(defs); - }; - } - self.body = dirs.concat(hoisted, self.body); - } - return self; - }); - - OPT(AST_SimpleStatement, function(self, compressor){ - if (compressor.option("side_effects")) { - if (!self.body.has_side_effects()) { - compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start); - return make_node(AST_EmptyStatement, self); - } - } - return self; - }); - - OPT(AST_DWLoop, function(self, compressor){ - var cond = self.condition.evaluate(compressor); - self.condition = cond[0]; - if (!compressor.option("loops")) return self; - if (cond.length > 1) { - if (cond[1]) { - return make_node(AST_For, self, { - body: self.body - }); - } else if (self instanceof AST_While) { - if (compressor.option("dead_code")) { - var a = []; - extract_declarations_from_unreachable_code(compressor, self.body, a); - return make_node(AST_BlockStatement, self, { body: a }); - } - } - } - return self; - }); - - function if_break_in_loop(self, compressor) { - function drop_it(rest) { - rest = as_statement_array(rest); - if (self.body instanceof AST_BlockStatement) { - self.body = self.body.clone(); - self.body.body = rest.concat(self.body.body.slice(1)); - self.body = self.body.transform(compressor); - } else { - self.body = make_node(AST_BlockStatement, self.body, { - body: rest - }).transform(compressor); - } - if_break_in_loop(self, compressor); - } - var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; - if (first instanceof AST_If) { - if (first.body instanceof AST_Break - && compressor.loopcontrol_target(first.body.label) === self) { - if (self.condition) { - self.condition = make_node(AST_Binary, self.condition, { - left: self.condition, - operator: "&&", - right: first.condition.negate(compressor), - }); - } else { - self.condition = first.condition.negate(compressor); - } - drop_it(first.alternative); - } - else if (first.alternative instanceof AST_Break - && compressor.loopcontrol_target(first.alternative.label) === self) { - if (self.condition) { - self.condition = make_node(AST_Binary, self.condition, { - left: self.condition, - operator: "&&", - right: first.condition, - }); - } else { - self.condition = first.condition; - } - drop_it(first.body); - } - } - }; - - OPT(AST_While, function(self, compressor) { - if (!compressor.option("loops")) return self; - self = AST_DWLoop.prototype.optimize.call(self, compressor); - if (self instanceof AST_While) { - if_break_in_loop(self, compressor); - self = make_node(AST_For, self, self).transform(compressor); - } - return self; - }); - - OPT(AST_For, function(self, compressor){ - var cond = self.condition; - if (cond) { - cond = cond.evaluate(compressor); - self.condition = cond[0]; - } - if (!compressor.option("loops")) return self; - if (cond) { - if (cond.length > 1 && !cond[1]) { - if (compressor.option("dead_code")) { - var a = []; - if (self.init instanceof AST_Statement) { - a.push(self.init); - } - else if (self.init) { - a.push(make_node(AST_SimpleStatement, self.init, { - body: self.init - })); - } - extract_declarations_from_unreachable_code(compressor, self.body, a); - return make_node(AST_BlockStatement, self, { body: a }); - } - } - } - if_break_in_loop(self, compressor); - return self; - }); - - OPT(AST_If, function(self, compressor){ - if (!compressor.option("conditionals")) return self; - // if condition can be statically determined, warn and drop - // one of the blocks. note, statically determined implies - // “has no side effects”; also it doesn't work for cases like - // `x && true`, though it probably should. - var cond = self.condition.evaluate(compressor); - self.condition = cond[0]; - if (cond.length > 1) { - if (cond[1]) { - compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start); - if (compressor.option("dead_code")) { - var a = []; - if (self.alternative) { - extract_declarations_from_unreachable_code(compressor, self.alternative, a); - } - a.push(self.body); - return make_node(AST_BlockStatement, self, { body: a }).transform(compressor); - } - } else { - compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start); - if (compressor.option("dead_code")) { - var a = []; - extract_declarations_from_unreachable_code(compressor, self.body, a); - if (self.alternative) a.push(self.alternative); - return make_node(AST_BlockStatement, self, { body: a }).transform(compressor); - } - } - } - if (is_empty(self.alternative)) self.alternative = null; - var negated = self.condition.negate(compressor); - var negated_is_best = best_of(self.condition, negated) === negated; - if (self.alternative && negated_is_best) { - negated_is_best = false; // because we already do the switch here. - self.condition = negated; - var tmp = self.body; - self.body = self.alternative || make_node(AST_EmptyStatement); - self.alternative = tmp; - } - if (is_empty(self.body) && is_empty(self.alternative)) { - return make_node(AST_SimpleStatement, self.condition, { - body: self.condition - }).transform(compressor); - } - if (self.body instanceof AST_SimpleStatement - && self.alternative instanceof AST_SimpleStatement) { - return make_node(AST_SimpleStatement, self, { - body: make_node(AST_Conditional, self, { - condition : self.condition, - consequent : self.body.body, - alternative : self.alternative.body - }) - }).transform(compressor); - } - if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { - if (negated_is_best) return make_node(AST_SimpleStatement, self, { - body: make_node(AST_Binary, self, { - operator : "||", - left : negated, - right : self.body.body - }) - }).transform(compressor); - return make_node(AST_SimpleStatement, self, { - body: make_node(AST_Binary, self, { - operator : "&&", - left : self.condition, - right : self.body.body - }) - }).transform(compressor); - } - if (self.body instanceof AST_EmptyStatement - && self.alternative - && self.alternative instanceof AST_SimpleStatement) { - return make_node(AST_SimpleStatement, self, { - body: make_node(AST_Binary, self, { - operator : "||", - left : self.condition, - right : self.alternative.body - }) - }).transform(compressor); - } - if (self.body instanceof AST_Exit - && self.alternative instanceof AST_Exit - && self.body.TYPE == self.alternative.TYPE) { - return make_node(self.body.CTOR, self, { - value: make_node(AST_Conditional, self, { - condition : self.condition, - consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor), - alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor) - }) - }).transform(compressor); - } - if (self.body instanceof AST_If - && !self.body.alternative - && !self.alternative) { - self.condition = make_node(AST_Binary, self.condition, { - operator: "&&", - left: self.condition, - right: self.body.condition - }).transform(compressor); - self.body = self.body.body; - } - if (aborts(self.body)) { - if (self.alternative) { - var alt = self.alternative; - self.alternative = null; - return make_node(AST_BlockStatement, self, { - body: [ self, alt ] - }).transform(compressor); - } - } - if (aborts(self.alternative)) { - var body = self.body; - self.body = self.alternative; - self.condition = negated_is_best ? negated : self.condition.negate(compressor); - self.alternative = null; - return make_node(AST_BlockStatement, self, { - body: [ self, body ] - }).transform(compressor); - } - return self; - }); - - OPT(AST_Switch, function(self, compressor){ - if (self.body.length == 0 && compressor.option("conditionals")) { - return make_node(AST_SimpleStatement, self, { - body: self.expression - }).transform(compressor); - } - for(;;) { - var last_branch = self.body[self.body.length - 1]; - if (last_branch) { - var stat = last_branch.body[last_branch.body.length - 1]; // last statement - if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self) - last_branch.body.pop(); - if (last_branch instanceof AST_Default && last_branch.body.length == 0) { - self.body.pop(); - continue; - } - } - break; - } - var exp = self.expression.evaluate(compressor); - out: if (exp.length == 2) try { - // constant expression - self.expression = exp[0]; - if (!compressor.option("dead_code")) break out; - var value = exp[1]; - var in_if = false; - var in_block = false; - var started = false; - var stopped = false; - var ruined = false; - var tt = new TreeTransformer(function(node, descend, in_list){ - if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) { - // no need to descend these node types - return node; - } - else if (node instanceof AST_Switch && node === self) { - node = node.clone(); - descend(node, this); - return ruined ? node : make_node(AST_BlockStatement, node, { - body: node.body.reduce(function(a, branch){ - return a.concat(branch.body); - }, []) - }).transform(compressor); - } - else if (node instanceof AST_If || node instanceof AST_Try) { - var save = in_if; - in_if = !in_block; - descend(node, this); - in_if = save; - return node; - } - else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) { - var save = in_block; - in_block = true; - descend(node, this); - in_block = save; - return node; - } - else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) { - if (in_if) { - ruined = true; - return node; - } - if (in_block) return node; - stopped = true; - return in_list ? MAP.skip : make_node(AST_EmptyStatement, node); - } - else if (node instanceof AST_SwitchBranch && this.parent() === self) { - if (stopped) return MAP.skip; - if (node instanceof AST_Case) { - var exp = node.expression.evaluate(compressor); - if (exp.length < 2) { - // got a case with non-constant expression, baling out - throw self; - } - if (exp[1] === value || started) { - started = true; - if (aborts(node)) stopped = true; - descend(node, this); - return node; - } - return MAP.skip; - } - descend(node, this); - return node; - } - }); - tt.stack = compressor.stack.slice(); // so that's able to see parent nodes - self = self.transform(tt); - } catch(ex) { - if (ex !== self) throw ex; - } - return self; - }); - - OPT(AST_Case, function(self, compressor){ - self.body = tighten_body(self.body, compressor); - return self; - }); - - OPT(AST_Try, function(self, compressor){ - self.body = tighten_body(self.body, compressor); - return self; - }); - - AST_Definitions.DEFMETHOD("remove_initializers", function(){ - this.definitions.forEach(function(def){ def.value = null }); - }); - - AST_Definitions.DEFMETHOD("to_assignments", function(){ - var assignments = this.definitions.reduce(function(a, def){ - if (def.value) { - var name = make_node(AST_SymbolRef, def.name, def.name); - a.push(make_node(AST_Assign, def, { - operator : "=", - left : name, - right : def.value - })); - } - return a; - }, []); - if (assignments.length == 0) return null; - return AST_Seq.from_array(assignments); - }); - - OPT(AST_Definitions, function(self, compressor){ - if (self.definitions.length == 0) - return make_node(AST_EmptyStatement, self); - return self; - }); - - OPT(AST_Function, function(self, compressor){ - self = AST_Lambda.prototype.optimize.call(self, compressor); - if (compressor.option("unused")) { - if (self.name && self.name.unreferenced()) { - self.name = null; - } - } - return self; - }); - - OPT(AST_Call, function(self, compressor){ - if (compressor.option("unsafe")) { - var exp = self.expression; - if (exp instanceof AST_SymbolRef && exp.undeclared()) { - switch (exp.name) { - case "Array": - if (self.args.length != 1) { - return make_node(AST_Array, self, { - elements: self.args - }); - } - break; - case "Object": - if (self.args.length == 0) { - return make_node(AST_Object, self, { - properties: [] - }); - } - break; - case "String": - if (self.args.length == 0) return make_node(AST_String, self, { - value: "" - }); - return make_node(AST_Binary, self, { - left: self.args[0], - operator: "+", - right: make_node(AST_String, self, { value: "" }) - }); - case "Function": - if (all(self.args, function(x){ return x instanceof AST_String })) { - // quite a corner-case, but we can handle it: - // https://github.com/mishoo/UglifyJS2/issues/203 - // if the code argument is a constant, then we can minify it. - try { - var code = "(function(" + self.args.slice(0, -1).map(function(arg){ - return arg.value; - }).join(",") + "){" + self.args[self.args.length - 1].value + "})()"; - var ast = parse(code); - ast.figure_out_scope(); - var comp = new Compressor(compressor.options); - ast = ast.transform(comp); - ast.figure_out_scope(); - ast.mangle_names(); - var fun = ast.body[0].body.expression; - var args = fun.argnames.map(function(arg, i){ - return make_node(AST_String, self.args[i], { - value: arg.print_to_string() - }); - }); - var code = OutputStream(); - AST_BlockStatement.prototype._codegen.call(fun, fun, code); - code = code.toString().replace(/^\{|\}$/g, ""); - args.push(make_node(AST_String, self.args[self.args.length - 1], { - value: code - })); - self.args = args; - return self; - } catch(ex) { - if (ex instanceof JS_Parse_Error) { - compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start); - compressor.warn(ex.toString()); - } else { - console.log(ex); - } - } - } - break; - } - } - else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) { - return make_node(AST_Binary, self, { - left: make_node(AST_String, self, { value: "" }), - operator: "+", - right: exp.expression - }).transform(compressor); - } - } - if (compressor.option("side_effects")) { - if (self.expression instanceof AST_Function - && self.args.length == 0 - && !AST_Block.prototype.has_side_effects.call(self.expression)) { - return make_node(AST_Undefined, self).transform(compressor); - } - } - return self; - }); - - OPT(AST_New, function(self, compressor){ - if (compressor.option("unsafe")) { - var exp = self.expression; - if (exp instanceof AST_SymbolRef && exp.undeclared()) { - switch (exp.name) { - case "Object": - case "RegExp": - case "Function": - case "Error": - case "Array": - return make_node(AST_Call, self, self).transform(compressor); - } - } - } - return self; - }); - - OPT(AST_Seq, function(self, compressor){ - if (!compressor.option("side_effects")) - return self; - if (!self.car.has_side_effects()) { - // we shouldn't compress (1,eval)(something) to - // eval(something) because that changes the meaning of - // eval (becomes lexical instead of global). - var p; - if (!(self.cdr instanceof AST_SymbolRef - && self.cdr.name == "eval" - && self.cdr.undeclared() - && (p = compressor.parent()) instanceof AST_Call - && p.expression === self)) { - return self.cdr; - } - } - if (compressor.option("cascade")) { - if (self.car instanceof AST_Assign - && !self.car.left.has_side_effects() - && self.car.left.equivalent_to(self.cdr)) { - return self.car; - } - if (!self.car.has_side_effects() - && !self.cdr.has_side_effects() - && self.car.equivalent_to(self.cdr)) { - return self.car; - } - } - return self; - }); - - AST_Unary.DEFMETHOD("lift_sequences", function(compressor){ - if (compressor.option("sequences")) { - if (this.expression instanceof AST_Seq) { - var seq = this.expression; - var x = seq.to_array(); - this.expression = x.pop(); - x.push(this); - seq = AST_Seq.from_array(x).transform(compressor); - return seq; - } - } - return this; - }); - - OPT(AST_UnaryPostfix, function(self, compressor){ - return self.lift_sequences(compressor); - }); - - OPT(AST_UnaryPrefix, function(self, compressor){ - self = self.lift_sequences(compressor); - var e = self.expression; - if (compressor.option("booleans") && compressor.in_boolean_context()) { - switch (self.operator) { - case "!": - if (e instanceof AST_UnaryPrefix && e.operator == "!") { - // !!foo ==> foo, if we're in boolean context - return e.expression; - } - break; - case "typeof": - // typeof always returns a non-empty string, thus it's - // always true in booleans - compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start); - return make_node(AST_True, self); - } - if (e instanceof AST_Binary && self.operator == "!") { - self = best_of(self, e.negate(compressor)); - } - } - return self.evaluate(compressor)[0]; - }); - - AST_Binary.DEFMETHOD("lift_sequences", function(compressor){ - if (compressor.option("sequences")) { - if (this.left instanceof AST_Seq) { - var seq = this.left; - var x = seq.to_array(); - this.left = x.pop(); - x.push(this); - seq = AST_Seq.from_array(x).transform(compressor); - return seq; - } - if (this.right instanceof AST_Seq - && !(this.operator == "||" || this.operator == "&&") - && !this.left.has_side_effects()) { - var seq = this.right; - var x = seq.to_array(); - this.right = x.pop(); - x.push(this); - seq = AST_Seq.from_array(x).transform(compressor); - return seq; - } - } - return this; - }); - - var commutativeOperators = makePredicate("== === != !== * & | ^"); - - OPT(AST_Binary, function(self, compressor){ - function reverse(op, force) { - if (force || !(self.left.has_side_effects() || self.right.has_side_effects())) { - if (op) self.operator = op; - var tmp = self.left; - self.left = self.right; - self.right = tmp; - } - }; - if (commutativeOperators(self.operator)) { - if (self.right instanceof AST_Constant - && !(self.left instanceof AST_Constant)) { - // if right is a constant, whatever side effects the - // left side might have could not influence the - // result. hence, force switch. - reverse(null, true); - } - } - self = self.lift_sequences(compressor); - if (compressor.option("comparisons")) switch (self.operator) { - case "===": - case "!==": - if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || - (self.left.is_boolean() && self.right.is_boolean())) { - self.operator = self.operator.substr(0, 2); - } - // XXX: intentionally falling down to the next case - case "==": - case "!=": - if (self.left instanceof AST_String - && self.left.value == "undefined" - && self.right instanceof AST_UnaryPrefix - && self.right.operator == "typeof" - && compressor.option("unsafe")) { - if (!(self.right.expression instanceof AST_SymbolRef) - || !self.right.expression.undeclared()) { - self.right = self.right.expression; - self.left = make_node(AST_Undefined, self.left).optimize(compressor); - if (self.operator.length == 2) self.operator += "="; - } - } - break; - } - if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) { - case "&&": - var ll = self.left.evaluate(compressor); - var rr = self.right.evaluate(compressor); - if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) { - compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start); - return make_node(AST_False, self); - } - if (ll.length > 1 && ll[1]) { - return rr[0]; - } - if (rr.length > 1 && rr[1]) { - return ll[0]; - } - break; - case "||": - var ll = self.left.evaluate(compressor); - var rr = self.right.evaluate(compressor); - if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) { - compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start); - return make_node(AST_True, self); - } - if (ll.length > 1 && !ll[1]) { - return rr[0]; - } - if (rr.length > 1 && !rr[1]) { - return ll[0]; - } - break; - case "+": - var ll = self.left.evaluate(compressor); - var rr = self.right.evaluate(compressor); - if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) || - (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) { - compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start); - return make_node(AST_True, self); - } - break; - } - var exp = self.evaluate(compressor); - if (exp.length > 1) { - if (best_of(exp[0], self) !== self) - return exp[0]; - } - if (compressor.option("comparisons")) { - if (!(compressor.parent() instanceof AST_Binary) - || compressor.parent() instanceof AST_Assign) { - var negated = make_node(AST_UnaryPrefix, self, { - operator: "!", - expression: self.negate(compressor) - }); - self = best_of(self, negated); - } - switch (self.operator) { - case "<": reverse(">"); break; - case "<=": reverse(">="); break; - } - } - if (self.operator == "+" && self.right instanceof AST_String - && self.right.getValue() === "" && self.left instanceof AST_Binary - && self.left.operator == "+" && self.left.is_string(compressor)) { - return self.left; - } - return self; - }); - - OPT(AST_SymbolRef, function(self, compressor){ - if (self.undeclared()) { - var defines = compressor.option("global_defs"); - if (defines && defines.hasOwnProperty(self.name)) { - return make_node_from_constant(compressor, defines[self.name], self); - } - switch (self.name) { - case "undefined": - return make_node(AST_Undefined, self); - case "NaN": - return make_node(AST_NaN, self); - case "Infinity": - return make_node(AST_Infinity, self); - } - } - return self; - }); - - OPT(AST_Undefined, function(self, compressor){ - if (compressor.option("unsafe")) { - var scope = compressor.find_parent(AST_Scope); - var undef = scope.find_variable("undefined"); - if (undef) { - var ref = make_node(AST_SymbolRef, self, { - name : "undefined", - scope : scope, - thedef : undef - }); - ref.reference(); - return ref; - } - } - return self; - }); - - var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ]; - OPT(AST_Assign, function(self, compressor){ - self = self.lift_sequences(compressor); - if (self.operator == "=" - && self.left instanceof AST_SymbolRef - && self.right instanceof AST_Binary - && self.right.left instanceof AST_SymbolRef - && self.right.left.name == self.left.name - && member(self.right.operator, ASSIGN_OPS)) { - self.operator = self.right.operator + "="; - self.right = self.right.right; - } - return self; - }); - - OPT(AST_Conditional, function(self, compressor){ - if (!compressor.option("conditionals")) return self; - if (self.condition instanceof AST_Seq) { - var car = self.condition.car; - self.condition = self.condition.cdr; - return AST_Seq.cons(car, self); - } - var cond = self.condition.evaluate(compressor); - if (cond.length > 1) { - if (cond[1]) { - compressor.warn("Condition always true [{file}:{line},{col}]", self.start); - return self.consequent; - } else { - compressor.warn("Condition always false [{file}:{line},{col}]", self.start); - return self.alternative; - } - } - var negated = cond[0].negate(compressor); - if (best_of(cond[0], negated) === negated) { - self = make_node(AST_Conditional, self, { - condition: negated, - consequent: self.alternative, - alternative: self.consequent - }); - } - var consequent = self.consequent; - var alternative = self.alternative; - if (consequent instanceof AST_Assign - && alternative instanceof AST_Assign - && consequent.operator == alternative.operator - && consequent.left.equivalent_to(alternative.left) - ) { - /* - * Stuff like this: - * if (foo) exp = something; else exp = something_else; - * ==> - * exp = foo ? something : something_else; - */ - self = make_node(AST_Assign, self, { - operator: consequent.operator, - left: consequent.left, - right: make_node(AST_Conditional, self, { - condition: self.condition, - consequent: consequent.right, - alternative: alternative.right - }) - }); - } - return self; - }); - - OPT(AST_Boolean, function(self, compressor){ - if (compressor.option("booleans")) { - var p = compressor.parent(); - if (p instanceof AST_Binary && (p.operator == "==" - || p.operator == "!=")) { - compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", { - operator : p.operator, - value : self.value, - file : p.start.file, - line : p.start.line, - col : p.start.col, - }); - return make_node(AST_Number, self, { - value: +self.value - }); - } - return make_node(AST_UnaryPrefix, self, { - operator: "!", - expression: make_node(AST_Number, self, { - value: 1 - self.value - }) - }); - } - return self; - }); - - OPT(AST_Sub, function(self, compressor){ - var prop = self.property; - if (prop instanceof AST_String && compressor.option("properties")) { - prop = prop.getValue(); - if ((compressor.option("screw_ie8") && RESERVED_WORDS(prop)) - || (!(RESERVED_WORDS(prop)) && is_identifier_string(prop))) { - return make_node(AST_Dot, self, { - expression : self.expression, - property : prop - }); - } - } - return self; - }); - - function literals_in_boolean_context(self, compressor) { - if (compressor.option("booleans") && compressor.in_boolean_context()) { - return make_node(AST_True, self); - } - return self; - }; - OPT(AST_Array, literals_in_boolean_context); - OPT(AST_Object, literals_in_boolean_context); - OPT(AST_RegExp, literals_in_boolean_context); - -})(); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/mozilla-ast.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/mozilla-ast.js deleted file mode 100644 index d79509422..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/mozilla-ast.js +++ /dev/null @@ -1,267 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -(function(){ - - var MOZ_TO_ME = { - TryStatement : function(M) { - return new AST_Try({ - start : my_start_token(M), - end : my_end_token(M), - body : from_moz(M.block).body, - bcatch : from_moz(M.handlers[0]), - bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null - }); - }, - CatchClause : function(M) { - return new AST_Catch({ - start : my_start_token(M), - end : my_end_token(M), - argname : from_moz(M.param), - body : from_moz(M.body).body - }); - }, - ObjectExpression : function(M) { - return new AST_Object({ - start : my_start_token(M), - end : my_end_token(M), - properties : M.properties.map(function(prop){ - var key = prop.key; - var name = key.type == "Identifier" ? key.name : key.value; - var args = { - start : my_start_token(key), - end : my_end_token(prop.value), - key : name, - value : from_moz(prop.value) - }; - switch (prop.kind) { - case "init": - return new AST_ObjectKeyVal(args); - case "set": - args.value.name = from_moz(key); - return new AST_ObjectSetter(args); - case "get": - args.value.name = from_moz(key); - return new AST_ObjectGetter(args); - } - }) - }); - }, - SequenceExpression : function(M) { - return AST_Seq.from_array(M.expressions.map(from_moz)); - }, - MemberExpression : function(M) { - return new (M.computed ? AST_Sub : AST_Dot)({ - start : my_start_token(M), - end : my_end_token(M), - property : M.computed ? from_moz(M.property) : M.property.name, - expression : from_moz(M.object) - }); - }, - SwitchCase : function(M) { - return new (M.test ? AST_Case : AST_Default)({ - start : my_start_token(M), - end : my_end_token(M), - expression : from_moz(M.test), - body : M.consequent.map(from_moz) - }); - }, - Literal : function(M) { - var val = M.value, args = { - start : my_start_token(M), - end : my_end_token(M) - }; - if (val === null) return new AST_Null(args); - switch (typeof val) { - case "string": - args.value = val; - return new AST_String(args); - case "number": - args.value = val; - return new AST_Number(args); - case "boolean": - return new (val ? AST_True : AST_False)(args); - default: - args.value = val; - return new AST_RegExp(args); - } - }, - UnaryExpression: From_Moz_Unary, - UpdateExpression: From_Moz_Unary, - Identifier: function(M) { - var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; - return new (M.name == "this" ? AST_This - : p.type == "LabeledStatement" ? AST_Label - : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar) - : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) - : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) - : p.type == "CatchClause" ? AST_SymbolCatch - : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef - : AST_SymbolRef)({ - start : my_start_token(M), - end : my_end_token(M), - name : M.name - }); - } - }; - - function From_Moz_Unary(M) { - var prefix = "prefix" in M ? M.prefix - : M.type == "UnaryExpression" ? true : false; - return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ - start : my_start_token(M), - end : my_end_token(M), - operator : M.operator, - expression : from_moz(M.argument) - }); - }; - - var ME_TO_MOZ = {}; - - map("Node", AST_Node); - map("Program", AST_Toplevel, "body@body"); - map("Function", AST_Function, "id>name, params@argnames, body%body"); - map("EmptyStatement", AST_EmptyStatement); - map("BlockStatement", AST_BlockStatement, "body@body"); - map("ExpressionStatement", AST_SimpleStatement, "expression>body"); - map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); - map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); - map("BreakStatement", AST_Break, "label>label"); - map("ContinueStatement", AST_Continue, "label>label"); - map("WithStatement", AST_With, "object>expression, body>body"); - map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); - map("ReturnStatement", AST_Return, "argument>value"); - map("ThrowStatement", AST_Throw, "argument>value"); - map("WhileStatement", AST_While, "test>condition, body>body"); - map("DoWhileStatement", AST_Do, "test>condition, body>body"); - map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); - map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); - map("DebuggerStatement", AST_Debugger); - map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body"); - map("VariableDeclaration", AST_Var, "declarations@definitions"); - map("VariableDeclarator", AST_VarDef, "id>name, init>value"); - - map("ThisExpression", AST_This); - map("ArrayExpression", AST_Array, "elements@elements"); - map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body"); - map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); - map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); - map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); - map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); - map("NewExpression", AST_New, "callee>expression, arguments@args"); - map("CallExpression", AST_Call, "callee>expression, arguments@args"); - - /* -----[ tools ]----- */ - - function my_start_token(moznode) { - return new AST_Token({ - file : moznode.loc && moznode.loc.source, - line : moznode.loc && moznode.loc.start.line, - col : moznode.loc && moznode.loc.start.column, - pos : moznode.start, - endpos : moznode.start - }); - }; - - function my_end_token(moznode) { - return new AST_Token({ - file : moznode.loc && moznode.loc.source, - line : moznode.loc && moznode.loc.end.line, - col : moznode.loc && moznode.loc.end.column, - pos : moznode.end, - endpos : moznode.end - }); - }; - - function map(moztype, mytype, propmap) { - var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; - moz_to_me += "return new mytype({\n" + - "start: my_start_token(M),\n" + - "end: my_end_token(M)"; - - if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){ - var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop); - if (!m) throw new Error("Can't understand property map: " + prop); - var moz = "M." + m[1], how = m[2], my = m[3]; - moz_to_me += ",\n" + my + ": "; - if (how == "@") { - moz_to_me += moz + ".map(from_moz)"; - } else if (how == ">") { - moz_to_me += "from_moz(" + moz + ")"; - } else if (how == "=") { - moz_to_me += moz; - } else if (how == "%") { - moz_to_me += "from_moz(" + moz + ").body"; - } else throw new Error("Can't understand operator in propmap: " + prop); - }); - moz_to_me += "\n})}"; - - // moz_to_me = parse(moz_to_me).print_to_string({ beautify: true }); - // console.log(moz_to_me); - - moz_to_me = new Function("mytype", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( - mytype, my_start_token, my_end_token, from_moz - ); - return MOZ_TO_ME[moztype] = moz_to_me; - }; - - var FROM_MOZ_STACK = null; - - function from_moz(node) { - FROM_MOZ_STACK.push(node); - var ret = node != null ? MOZ_TO_ME[node.type](node) : null; - FROM_MOZ_STACK.pop(); - return ret; - }; - - AST_Node.from_mozilla_ast = function(node){ - var save_stack = FROM_MOZ_STACK; - FROM_MOZ_STACK = []; - var ast = from_moz(node); - FROM_MOZ_STACK = save_stack; - return ast; - }; - -})(); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/output.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/output.js deleted file mode 100644 index 60a4a26ce..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/output.js +++ /dev/null @@ -1,1229 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -function OutputStream(options) { - - options = defaults(options, { - indent_start : 0, - indent_level : 4, - quote_keys : false, - space_colon : true, - ascii_only : false, - inline_script : false, - width : 80, - max_line_len : 32000, - ie_proof : true, - beautify : false, - source_map : null, - bracketize : false, - semicolons : true, - comments : false, - preserve_line : false, - negate_iife : !(options && options.beautify), - }, true); - - var indentation = 0; - var current_col = 0; - var current_line = 1; - var current_pos = 0; - var OUTPUT = ""; - - function to_ascii(str, identifier) { - return str.replace(/[\u0080-\uffff]/g, function(ch) { - var code = ch.charCodeAt(0).toString(16); - if (code.length <= 2 && !identifier) { - while (code.length < 2) code = "0" + code; - return "\\x" + code; - } else { - while (code.length < 4) code = "0" + code; - return "\\u" + code; - } - }); - }; - - function make_string(str) { - var dq = 0, sq = 0; - str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){ - switch (s) { - case "\\": return "\\\\"; - case "\b": return "\\b"; - case "\f": return "\\f"; - case "\n": return "\\n"; - case "\r": return "\\r"; - case "\u2028": return "\\u2028"; - case "\u2029": return "\\u2029"; - case '"': ++dq; return '"'; - case "'": ++sq; return "'"; - case "\0": return "\\0"; - } - return s; - }); - if (options.ascii_only) str = to_ascii(str); - if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'"; - else return '"' + str.replace(/\x22/g, '\\"') + '"'; - }; - - function encode_string(str) { - var ret = make_string(str); - if (options.inline_script) - ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1"); - return ret; - }; - - function make_name(name) { - name = name.toString(); - if (options.ascii_only) - name = to_ascii(name, true); - return name; - }; - - function make_indent(back) { - return repeat_string(" ", options.indent_start + indentation - back * options.indent_level); - }; - - /* -----[ beautification/minification ]----- */ - - var might_need_space = false; - var might_need_semicolon = false; - var last = null; - - function last_char() { - return last.charAt(last.length - 1); - }; - - function maybe_newline() { - if (options.max_line_len && current_col > options.max_line_len) - print("\n"); - }; - - var requireSemicolonChars = makePredicate("( [ + * / - , ."); - - function print(str) { - str = String(str); - var ch = str.charAt(0); - if (might_need_semicolon) { - if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) { - if (options.semicolons || requireSemicolonChars(ch)) { - OUTPUT += ";"; - current_col++; - current_pos++; - } else { - OUTPUT += "\n"; - current_pos++; - current_line++; - current_col = 0; - } - if (!options.beautify) - might_need_space = false; - } - might_need_semicolon = false; - maybe_newline(); - } - - if (!options.beautify && options.preserve_line && stack[stack.length - 1]) { - var target_line = stack[stack.length - 1].start.line; - while (current_line < target_line) { - OUTPUT += "\n"; - current_pos++; - current_line++; - current_col = 0; - might_need_space = false; - } - } - - if (might_need_space) { - var prev = last_char(); - if ((is_identifier_char(prev) - && (is_identifier_char(ch) || ch == "\\")) - || (/^[\+\-\/]$/.test(ch) && ch == prev)) - { - OUTPUT += " "; - current_col++; - current_pos++; - } - might_need_space = false; - } - var a = str.split(/\r?\n/), n = a.length - 1; - current_line += n; - if (n == 0) { - current_col += a[n].length; - } else { - current_col = a[n].length; - } - current_pos += str.length; - last = str; - OUTPUT += str; - }; - - var space = options.beautify ? function() { - print(" "); - } : function() { - might_need_space = true; - }; - - var indent = options.beautify ? function(half) { - if (options.beautify) { - print(make_indent(half ? 0.5 : 0)); - } - } : noop; - - var with_indent = options.beautify ? function(col, cont) { - if (col === true) col = next_indent(); - var save_indentation = indentation; - indentation = col; - var ret = cont(); - indentation = save_indentation; - return ret; - } : function(col, cont) { return cont() }; - - var newline = options.beautify ? function() { - print("\n"); - } : noop; - - var semicolon = options.beautify ? function() { - print(";"); - } : function() { - might_need_semicolon = true; - }; - - function force_semicolon() { - might_need_semicolon = false; - print(";"); - }; - - function next_indent() { - return indentation + options.indent_level; - }; - - function with_block(cont) { - var ret; - print("{"); - newline(); - with_indent(next_indent(), function(){ - ret = cont(); - }); - indent(); - print("}"); - return ret; - }; - - function with_parens(cont) { - print("("); - //XXX: still nice to have that for argument lists - //var ret = with_indent(current_col, cont); - var ret = cont(); - print(")"); - return ret; - }; - - function with_square(cont) { - print("["); - //var ret = with_indent(current_col, cont); - var ret = cont(); - print("]"); - return ret; - }; - - function comma() { - print(","); - space(); - }; - - function colon() { - print(":"); - if (options.space_colon) space(); - }; - - var add_mapping = options.source_map ? function(token, name) { - try { - if (token) options.source_map.add( - token.file || "?", - current_line, current_col, - token.line, token.col, - (!name && token.type == "name") ? token.value : name - ); - } catch(ex) { - AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", { - file: token.file, - line: token.line, - col: token.col, - cline: current_line, - ccol: current_col, - name: name || "" - }) - } - } : noop; - - function get() { - return OUTPUT; - }; - - var stack = []; - return { - get : get, - toString : get, - indent : indent, - indentation : function() { return indentation }, - current_width : function() { return current_col - indentation }, - should_break : function() { return options.width && this.current_width() >= options.width }, - newline : newline, - print : print, - space : space, - comma : comma, - colon : colon, - last : function() { return last }, - semicolon : semicolon, - force_semicolon : force_semicolon, - to_ascii : to_ascii, - print_name : function(name) { print(make_name(name)) }, - print_string : function(str) { print(encode_string(str)) }, - next_indent : next_indent, - with_indent : with_indent, - with_block : with_block, - with_parens : with_parens, - with_square : with_square, - add_mapping : add_mapping, - option : function(opt) { return options[opt] }, - line : function() { return current_line }, - col : function() { return current_col }, - pos : function() { return current_pos }, - push_node : function(node) { stack.push(node) }, - pop_node : function() { return stack.pop() }, - stack : function() { return stack }, - parent : function(n) { - return stack[stack.length - 2 - (n || 0)]; - } - }; - -}; - -/* -----[ code generators ]----- */ - -(function(){ - - /* -----[ utils ]----- */ - - function DEFPRINT(nodetype, generator) { - nodetype.DEFMETHOD("_codegen", generator); - }; - - AST_Node.DEFMETHOD("print", function(stream, force_parens){ - var self = this, generator = self._codegen; - stream.push_node(self); - var needs_parens = self.needs_parens(stream); - var fc = self instanceof AST_Function && stream.option("negate_iife"); - if (force_parens || (needs_parens && !fc)) { - stream.with_parens(function(){ - self.add_comments(stream); - self.add_source_map(stream); - generator(self, stream); - }); - } else { - self.add_comments(stream); - if (needs_parens && fc) stream.print("!"); - self.add_source_map(stream); - generator(self, stream); - } - stream.pop_node(); - }); - - AST_Node.DEFMETHOD("print_to_string", function(options){ - var s = OutputStream(options); - this.print(s); - return s.get(); - }); - - /* -----[ comments ]----- */ - - AST_Node.DEFMETHOD("add_comments", function(output){ - var c = output.option("comments"), self = this; - if (c) { - var start = self.start; - if (start && !start._comments_dumped) { - start._comments_dumped = true; - var comments = start.comments_before; - - // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112 - // if this node is `return` or `throw`, we cannot allow comments before - // the returned or thrown value. - if (self instanceof AST_Exit && - self.value && self.value.start.comments_before.length > 0) { - comments = (comments || []).concat(self.value.start.comments_before); - self.value.start.comments_before = []; - } - - if (c.test) { - comments = comments.filter(function(comment){ - return c.test(comment.value); - }); - } else if (typeof c == "function") { - comments = comments.filter(function(comment){ - return c(self, comment); - }); - } - comments.forEach(function(c){ - if (c.type == "comment1") { - output.print("//" + c.value + "\n"); - output.indent(); - } - else if (c.type == "comment2") { - output.print("/*" + c.value + "*/"); - if (start.nlb) { - output.print("\n"); - output.indent(); - } else { - output.space(); - } - } - }); - } - } - }); - - /* -----[ PARENTHESES ]----- */ - - function PARENS(nodetype, func) { - nodetype.DEFMETHOD("needs_parens", func); - }; - - PARENS(AST_Node, function(){ - return false; - }); - - // a function expression needs parens around it when it's provably - // the first token to appear in a statement. - PARENS(AST_Function, function(output){ - return first_in_statement(output); - }); - - // same goes for an object literal, because otherwise it would be - // interpreted as a block of code. - PARENS(AST_Object, function(output){ - return first_in_statement(output); - }); - - PARENS(AST_Unary, function(output){ - var p = output.parent(); - return p instanceof AST_PropAccess && p.expression === this; - }); - - PARENS(AST_Seq, function(output){ - var p = output.parent(); - return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) - || p instanceof AST_Unary // !(foo, bar, baz) - || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 - || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 - || p instanceof AST_Dot // (1, {foo:2}).foo ==> 2 - || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] - || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 - || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) - * ==> 20 (side effect, set a := 10 and b := 20) */ - ; - }); - - PARENS(AST_Binary, function(output){ - var p = output.parent(); - // (foo && bar)() - if (p instanceof AST_Call && p.expression === this) - return true; - // typeof (foo && bar) - if (p instanceof AST_Unary) - return true; - // (foo && bar)["prop"], (foo && bar).prop - if (p instanceof AST_PropAccess && p.expression === this) - return true; - // this deals with precedence: 3 * (2 + 1) - if (p instanceof AST_Binary) { - var po = p.operator, pp = PRECEDENCE[po]; - var so = this.operator, sp = PRECEDENCE[so]; - if (pp > sp - || (pp == sp - && this === p.right - && !(so == po && - (so == "*" || - so == "&&" || - so == "||")))) { - return true; - } - } - }); - - PARENS(AST_PropAccess, function(output){ - var p = output.parent(); - if (p instanceof AST_New && p.expression === this) { - // i.e. new (foo.bar().baz) - // - // if there's one call into this subtree, then we need - // parens around it too, otherwise the call will be - // interpreted as passing the arguments to the upper New - // expression. - try { - this.walk(new TreeWalker(function(node){ - if (node instanceof AST_Call) throw p; - })); - } catch(ex) { - if (ex !== p) throw ex; - return true; - } - } - }); - - PARENS(AST_Call, function(output){ - var p = output.parent(); - return p instanceof AST_New && p.expression === this; - }); - - PARENS(AST_New, function(output){ - var p = output.parent(); - if (no_constructor_parens(this, output) - && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() - || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) - return true; - }); - - PARENS(AST_Number, function(output){ - var p = output.parent(); - if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this) - return true; - }); - - PARENS(AST_NaN, function(output){ - var p = output.parent(); - if (p instanceof AST_PropAccess && p.expression === this) - return true; - }); - - function assign_and_conditional_paren_rules(output) { - var p = output.parent(); - // !(a = false) → true - if (p instanceof AST_Unary) - return true; - // 1 + (a = 2) + 3 → 6, side effect setting a = 2 - if (p instanceof AST_Binary && !(p instanceof AST_Assign)) - return true; - // (a = func)() —or— new (a = Object)() - if (p instanceof AST_Call && p.expression === this) - return true; - // (a = foo) ? bar : baz - if (p instanceof AST_Conditional && p.condition === this) - return true; - // (a = foo)["prop"] —or— (a = foo).prop - if (p instanceof AST_PropAccess && p.expression === this) - return true; - }; - - PARENS(AST_Assign, assign_and_conditional_paren_rules); - PARENS(AST_Conditional, assign_and_conditional_paren_rules); - - /* -----[ PRINTERS ]----- */ - - DEFPRINT(AST_Directive, function(self, output){ - output.print_string(self.value); - output.semicolon(); - }); - DEFPRINT(AST_Debugger, function(self, output){ - output.print("debugger"); - output.semicolon(); - }); - - /* -----[ statements ]----- */ - - function display_body(body, is_toplevel, output) { - var last = body.length - 1; - body.forEach(function(stmt, i){ - if (!(stmt instanceof AST_EmptyStatement)) { - output.indent(); - stmt.print(output); - if (!(i == last && is_toplevel)) { - output.newline(); - if (is_toplevel) output.newline(); - } - } - }); - }; - - AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){ - force_statement(this.body, output); - }); - - DEFPRINT(AST_Statement, function(self, output){ - self.body.print(output); - output.semicolon(); - }); - DEFPRINT(AST_Toplevel, function(self, output){ - display_body(self.body, true, output); - output.print(""); - }); - DEFPRINT(AST_LabeledStatement, function(self, output){ - self.label.print(output); - output.colon(); - self.body.print(output); - }); - DEFPRINT(AST_SimpleStatement, function(self, output){ - self.body.print(output); - output.semicolon(); - }); - function print_bracketed(body, output) { - if (body.length > 0) output.with_block(function(){ - display_body(body, false, output); - }); - else output.print("{}"); - }; - DEFPRINT(AST_BlockStatement, function(self, output){ - print_bracketed(self.body, output); - }); - DEFPRINT(AST_EmptyStatement, function(self, output){ - output.semicolon(); - }); - DEFPRINT(AST_Do, function(self, output){ - output.print("do"); - output.space(); - self._do_print_body(output); - output.space(); - output.print("while"); - output.space(); - output.with_parens(function(){ - self.condition.print(output); - }); - output.semicolon(); - }); - DEFPRINT(AST_While, function(self, output){ - output.print("while"); - output.space(); - output.with_parens(function(){ - self.condition.print(output); - }); - output.space(); - self._do_print_body(output); - }); - DEFPRINT(AST_For, function(self, output){ - output.print("for"); - output.space(); - output.with_parens(function(){ - if (self.init) { - if (self.init instanceof AST_Definitions) { - self.init.print(output); - } else { - parenthesize_for_noin(self.init, output, true); - } - output.print(";"); - output.space(); - } else { - output.print(";"); - } - if (self.condition) { - self.condition.print(output); - output.print(";"); - output.space(); - } else { - output.print(";"); - } - if (self.step) { - self.step.print(output); - } - }); - output.space(); - self._do_print_body(output); - }); - DEFPRINT(AST_ForIn, function(self, output){ - output.print("for"); - output.space(); - output.with_parens(function(){ - self.init.print(output); - output.space(); - output.print("in"); - output.space(); - self.object.print(output); - }); - output.space(); - self._do_print_body(output); - }); - DEFPRINT(AST_With, function(self, output){ - output.print("with"); - output.space(); - output.with_parens(function(){ - self.expression.print(output); - }); - output.space(); - self._do_print_body(output); - }); - - /* -----[ functions ]----- */ - AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){ - var self = this; - if (!nokeyword) { - output.print("function"); - } - if (self.name) { - output.space(); - self.name.print(output); - } - output.with_parens(function(){ - self.argnames.forEach(function(arg, i){ - if (i) output.comma(); - arg.print(output); - }); - }); - output.space(); - print_bracketed(self.body, output); - }); - DEFPRINT(AST_Lambda, function(self, output){ - self._do_print(output); - }); - - /* -----[ exits ]----- */ - AST_Exit.DEFMETHOD("_do_print", function(output, kind){ - output.print(kind); - if (this.value) { - output.space(); - this.value.print(output); - } - output.semicolon(); - }); - DEFPRINT(AST_Return, function(self, output){ - self._do_print(output, "return"); - }); - DEFPRINT(AST_Throw, function(self, output){ - self._do_print(output, "throw"); - }); - - /* -----[ loop control ]----- */ - AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){ - output.print(kind); - if (this.label) { - output.space(); - this.label.print(output); - } - output.semicolon(); - }); - DEFPRINT(AST_Break, function(self, output){ - self._do_print(output, "break"); - }); - DEFPRINT(AST_Continue, function(self, output){ - self._do_print(output, "continue"); - }); - - /* -----[ if ]----- */ - function make_then(self, output) { - if (output.option("bracketize")) { - make_block(self.body, output); - return; - } - // The squeezer replaces "block"-s that contain only a single - // statement with the statement itself; technically, the AST - // is correct, but this can create problems when we output an - // IF having an ELSE clause where the THEN clause ends in an - // IF *without* an ELSE block (then the outer ELSE would refer - // to the inner IF). This function checks for this case and - // adds the block brackets if needed. - if (!self.body) - return output.force_semicolon(); - if (self.body instanceof AST_Do - && output.option("ie_proof")) { - // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE - // croaks with "syntax error" on code like this: if (foo) - // do ... while(cond); else ... we need block brackets - // around do/while - make_block(self.body, output); - return; - } - var b = self.body; - while (true) { - if (b instanceof AST_If) { - if (!b.alternative) { - make_block(self.body, output); - return; - } - b = b.alternative; - } - else if (b instanceof AST_StatementWithBody) { - b = b.body; - } - else break; - } - force_statement(self.body, output); - }; - DEFPRINT(AST_If, function(self, output){ - output.print("if"); - output.space(); - output.with_parens(function(){ - self.condition.print(output); - }); - output.space(); - if (self.alternative) { - make_then(self, output); - output.space(); - output.print("else"); - output.space(); - force_statement(self.alternative, output); - } else { - self._do_print_body(output); - } - }); - - /* -----[ switch ]----- */ - DEFPRINT(AST_Switch, function(self, output){ - output.print("switch"); - output.space(); - output.with_parens(function(){ - self.expression.print(output); - }); - output.space(); - if (self.body.length > 0) output.with_block(function(){ - self.body.forEach(function(stmt, i){ - if (i) output.newline(); - output.indent(true); - stmt.print(output); - }); - }); - else output.print("{}"); - }); - AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){ - if (this.body.length > 0) { - output.newline(); - this.body.forEach(function(stmt){ - output.indent(); - stmt.print(output); - output.newline(); - }); - } - }); - DEFPRINT(AST_Default, function(self, output){ - output.print("default:"); - self._do_print_body(output); - }); - DEFPRINT(AST_Case, function(self, output){ - output.print("case"); - output.space(); - self.expression.print(output); - output.print(":"); - self._do_print_body(output); - }); - - /* -----[ exceptions ]----- */ - DEFPRINT(AST_Try, function(self, output){ - output.print("try"); - output.space(); - print_bracketed(self.body, output); - if (self.bcatch) { - output.space(); - self.bcatch.print(output); - } - if (self.bfinally) { - output.space(); - self.bfinally.print(output); - } - }); - DEFPRINT(AST_Catch, function(self, output){ - output.print("catch"); - output.space(); - output.with_parens(function(){ - self.argname.print(output); - }); - output.space(); - print_bracketed(self.body, output); - }); - DEFPRINT(AST_Finally, function(self, output){ - output.print("finally"); - output.space(); - print_bracketed(self.body, output); - }); - - /* -----[ var/const ]----- */ - AST_Definitions.DEFMETHOD("_do_print", function(output, kind){ - output.print(kind); - output.space(); - this.definitions.forEach(function(def, i){ - if (i) output.comma(); - def.print(output); - }); - var p = output.parent(); - var in_for = p instanceof AST_For || p instanceof AST_ForIn; - var avoid_semicolon = in_for && p.init === this; - if (!avoid_semicolon) - output.semicolon(); - }); - DEFPRINT(AST_Var, function(self, output){ - self._do_print(output, "var"); - }); - DEFPRINT(AST_Const, function(self, output){ - self._do_print(output, "const"); - }); - - function parenthesize_for_noin(node, output, noin) { - if (!noin) node.print(output); - else try { - // need to take some precautions here: - // https://github.com/mishoo/UglifyJS2/issues/60 - node.walk(new TreeWalker(function(node){ - if (node instanceof AST_Binary && node.operator == "in") - throw output; - })); - node.print(output); - } catch(ex) { - if (ex !== output) throw ex; - node.print(output, true); - } - }; - - DEFPRINT(AST_VarDef, function(self, output){ - self.name.print(output); - if (self.value) { - output.space(); - output.print("="); - output.space(); - var p = output.parent(1); - var noin = p instanceof AST_For || p instanceof AST_ForIn; - parenthesize_for_noin(self.value, output, noin); - } - }); - - /* -----[ other expressions ]----- */ - DEFPRINT(AST_Call, function(self, output){ - self.expression.print(output); - if (self instanceof AST_New && no_constructor_parens(self, output)) - return; - output.with_parens(function(){ - self.args.forEach(function(expr, i){ - if (i) output.comma(); - expr.print(output); - }); - }); - }); - DEFPRINT(AST_New, function(self, output){ - output.print("new"); - output.space(); - AST_Call.prototype._codegen(self, output); - }); - - AST_Seq.DEFMETHOD("_do_print", function(output){ - this.car.print(output); - if (this.cdr) { - output.comma(); - if (output.should_break()) { - output.newline(); - output.indent(); - } - this.cdr.print(output); - } - }); - DEFPRINT(AST_Seq, function(self, output){ - self._do_print(output); - // var p = output.parent(); - // if (p instanceof AST_Statement) { - // output.with_indent(output.next_indent(), function(){ - // self._do_print(output); - // }); - // } else { - // self._do_print(output); - // } - }); - DEFPRINT(AST_Dot, function(self, output){ - var expr = self.expression; - expr.print(output); - if (expr instanceof AST_Number && expr.getValue() >= 0) { - if (!/[xa-f.]/i.test(output.last())) { - output.print("."); - } - } - output.print("."); - // the name after dot would be mapped about here. - output.add_mapping(self.end); - output.print_name(self.property); - }); - DEFPRINT(AST_Sub, function(self, output){ - self.expression.print(output); - output.print("["); - self.property.print(output); - output.print("]"); - }); - DEFPRINT(AST_UnaryPrefix, function(self, output){ - var op = self.operator; - output.print(op); - if (/^[a-z]/i.test(op)) - output.space(); - self.expression.print(output); - }); - DEFPRINT(AST_UnaryPostfix, function(self, output){ - self.expression.print(output); - output.print(self.operator); - }); - DEFPRINT(AST_Binary, function(self, output){ - self.left.print(output); - output.space(); - output.print(self.operator); - output.space(); - self.right.print(output); - }); - DEFPRINT(AST_Conditional, function(self, output){ - self.condition.print(output); - output.space(); - output.print("?"); - output.space(); - self.consequent.print(output); - output.space(); - output.colon(); - self.alternative.print(output); - }); - - /* -----[ literals ]----- */ - DEFPRINT(AST_Array, function(self, output){ - output.with_square(function(){ - var a = self.elements, len = a.length; - if (len > 0) output.space(); - a.forEach(function(exp, i){ - if (i) output.comma(); - exp.print(output); - }); - if (len > 0) output.space(); - }); - }); - DEFPRINT(AST_Object, function(self, output){ - if (self.properties.length > 0) output.with_block(function(){ - self.properties.forEach(function(prop, i){ - if (i) { - output.print(","); - output.newline(); - } - output.indent(); - prop.print(output); - }); - output.newline(); - }); - else output.print("{}"); - }); - DEFPRINT(AST_ObjectKeyVal, function(self, output){ - var key = self.key; - if (output.option("quote_keys")) { - output.print_string(key + ""); - } else if ((typeof key == "number" - || !output.option("beautify") - && +key + "" == key) - && parseFloat(key) >= 0) { - output.print(make_num(key)); - } else if (!is_identifier(key)) { - output.print_string(key); - } else { - output.print_name(key); - } - output.colon(); - self.value.print(output); - }); - DEFPRINT(AST_ObjectSetter, function(self, output){ - output.print("set"); - self.value._do_print(output, true); - }); - DEFPRINT(AST_ObjectGetter, function(self, output){ - output.print("get"); - self.value._do_print(output, true); - }); - DEFPRINT(AST_Symbol, function(self, output){ - var def = self.definition(); - output.print_name(def ? def.mangled_name || def.name : self.name); - }); - DEFPRINT(AST_Undefined, function(self, output){ - output.print("void 0"); - }); - DEFPRINT(AST_Hole, noop); - DEFPRINT(AST_Infinity, function(self, output){ - output.print("1/0"); - }); - DEFPRINT(AST_NaN, function(self, output){ - output.print("0/0"); - }); - DEFPRINT(AST_This, function(self, output){ - output.print("this"); - }); - DEFPRINT(AST_Constant, function(self, output){ - output.print(self.getValue()); - }); - DEFPRINT(AST_String, function(self, output){ - output.print_string(self.getValue()); - }); - DEFPRINT(AST_Number, function(self, output){ - output.print(make_num(self.getValue())); - }); - DEFPRINT(AST_RegExp, function(self, output){ - var str = self.getValue().toString(); - if (output.option("ascii_only")) - str = output.to_ascii(str); - output.print(str); - var p = output.parent(); - if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self) - output.print(" "); - }); - - function force_statement(stat, output) { - if (output.option("bracketize")) { - if (!stat || stat instanceof AST_EmptyStatement) - output.print("{}"); - else if (stat instanceof AST_BlockStatement) - stat.print(output); - else output.with_block(function(){ - output.indent(); - stat.print(output); - output.newline(); - }); - } else { - if (!stat || stat instanceof AST_EmptyStatement) - output.force_semicolon(); - else - stat.print(output); - } - }; - - // return true if the node at the top of the stack (that means the - // innermost node in the current output) is lexically the first in - // a statement. - function first_in_statement(output) { - var a = output.stack(), i = a.length, node = a[--i], p = a[--i]; - while (i > 0) { - if (p instanceof AST_Statement && p.body === node) - return true; - if ((p instanceof AST_Seq && p.car === node ) || - (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) || - (p instanceof AST_Dot && p.expression === node ) || - (p instanceof AST_Sub && p.expression === node ) || - (p instanceof AST_Conditional && p.condition === node ) || - (p instanceof AST_Binary && p.left === node ) || - (p instanceof AST_UnaryPostfix && p.expression === node )) - { - node = p; - p = a[--i]; - } else { - return false; - } - } - }; - - // self should be AST_New. decide if we want to show parens or not. - function no_constructor_parens(self, output) { - return self.args.length == 0 && !output.option("beautify"); - }; - - function best_of(a) { - var best = a[0], len = best.length; - for (var i = 1; i < a.length; ++i) { - if (a[i].length < len) { - best = a[i]; - len = best.length; - } - } - return best; - }; - - function make_num(num) { - var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m; - if (Math.floor(num) === num) { - if (num >= 0) { - a.push("0x" + num.toString(16).toLowerCase(), // probably pointless - "0" + num.toString(8)); // same. - } else { - a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless - "-0" + (-num).toString(8)); // same. - } - if ((m = /^(.*?)(0+)$/.exec(num))) { - a.push(m[1] + "e" + m[2].length); - } - } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) { - a.push(m[2] + "e-" + (m[1].length + m[2].length), - str.substr(str.indexOf("."))); - } - return best_of(a); - }; - - function make_block(stmt, output) { - if (stmt instanceof AST_BlockStatement) { - stmt.print(output); - return; - } - output.with_block(function(){ - output.indent(); - stmt.print(output); - output.newline(); - }); - }; - - /* -----[ source map generators ]----- */ - - function DEFMAP(nodetype, generator) { - nodetype.DEFMETHOD("add_source_map", function(stream){ - generator(this, stream); - }); - }; - - // We could easily add info for ALL nodes, but it seems to me that - // would be quite wasteful, hence this noop in the base class. - DEFMAP(AST_Node, noop); - - function basic_sourcemap_gen(self, output) { - output.add_mapping(self.start); - }; - - // XXX: I'm not exactly sure if we need it for all of these nodes, - // or if we should add even more. - - DEFMAP(AST_Directive, basic_sourcemap_gen); - DEFMAP(AST_Debugger, basic_sourcemap_gen); - DEFMAP(AST_Symbol, basic_sourcemap_gen); - DEFMAP(AST_Jump, basic_sourcemap_gen); - DEFMAP(AST_StatementWithBody, basic_sourcemap_gen); - DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it - DEFMAP(AST_Lambda, basic_sourcemap_gen); - DEFMAP(AST_Switch, basic_sourcemap_gen); - DEFMAP(AST_SwitchBranch, basic_sourcemap_gen); - DEFMAP(AST_BlockStatement, basic_sourcemap_gen); - DEFMAP(AST_Toplevel, noop); - DEFMAP(AST_New, basic_sourcemap_gen); - DEFMAP(AST_Try, basic_sourcemap_gen); - DEFMAP(AST_Catch, basic_sourcemap_gen); - DEFMAP(AST_Finally, basic_sourcemap_gen); - DEFMAP(AST_Definitions, basic_sourcemap_gen); - DEFMAP(AST_Constant, basic_sourcemap_gen); - DEFMAP(AST_ObjectProperty, function(self, output){ - output.add_mapping(self.start, self.key); - }); - -})(); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/parse.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/parse.js deleted file mode 100644 index e561ab676..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/parse.js +++ /dev/null @@ -1,1410 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with'; -var KEYWORDS_ATOM = 'false null true'; -var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile' - + " " + KEYWORDS_ATOM + " " + KEYWORDS; -var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case'; - -KEYWORDS = makePredicate(KEYWORDS); -RESERVED_WORDS = makePredicate(RESERVED_WORDS); -KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); -KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); - -var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")); - -var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; -var RE_OCT_NUMBER = /^0[0-7]+$/; -var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i; - -var OPERATORS = makePredicate([ - "in", - "instanceof", - "typeof", - "new", - "void", - "delete", - "++", - "--", - "+", - "-", - "!", - "~", - "&", - "|", - "^", - "*", - "/", - "%", - ">>", - "<<", - ">>>", - "<", - ">", - "<=", - ">=", - "==", - "===", - "!=", - "!==", - "?", - "=", - "+=", - "-=", - "/=", - "*=", - "%=", - ">>=", - "<<=", - ">>>=", - "|=", - "^=", - "&=", - "&&", - "||" -]); - -var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000")); - -var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:")); - -var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); - -var REGEXP_MODIFIERS = makePredicate(characters("gmsiy")); - -/* -----[ Tokenizer ]----- */ - -// regexps adapted from http://xregexp.com/plugins/#unicode -var UNICODE = { - letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"), - non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), - space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"), - connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]") -}; - -function is_letter(code) { - return (code >= 97 && code <= 122) - || (code >= 65 && code <= 90) - || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code))); -}; - -function is_digit(code) { - return code >= 48 && code <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9 -}; - -function is_alphanumeric_char(code) { - return is_digit(code) || is_letter(code); -}; - -function is_unicode_combining_mark(ch) { - return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch); -}; - -function is_unicode_connector_punctuation(ch) { - return UNICODE.connector_punctuation.test(ch); -}; - -function is_identifier(name) { - return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name); -}; - -function is_identifier_start(code) { - return code == 36 || code == 95 || is_letter(code); -}; - -function is_identifier_char(ch) { - var code = ch.charCodeAt(0); - return is_identifier_start(code) - || is_digit(code) - || code == 8204 // \u200c: zero-width non-joiner - || code == 8205 // \u200d: zero-width joiner (in my ECMA-262 PDF, this is also 200c) - || is_unicode_combining_mark(ch) - || is_unicode_connector_punctuation(ch) - ; -}; - -function is_identifier_string(str){ - var i = str.length; - if (i == 0) return false; - if (is_digit(str.charCodeAt(0))) return false; - while (--i >= 0) { - if (!is_identifier_char(str.charAt(i))) - return false; - } - return true; -}; - -function parse_js_number(num) { - if (RE_HEX_NUMBER.test(num)) { - return parseInt(num.substr(2), 16); - } else if (RE_OCT_NUMBER.test(num)) { - return parseInt(num.substr(1), 8); - } else if (RE_DEC_NUMBER.test(num)) { - return parseFloat(num); - } -}; - -function JS_Parse_Error(message, line, col, pos) { - this.message = message; - this.line = line; - this.col = col; - this.pos = pos; - this.stack = new Error().stack; -}; - -JS_Parse_Error.prototype.toString = function() { - return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack; -}; - -function js_error(message, filename, line, col, pos) { - throw new JS_Parse_Error(message, line, col, pos); -}; - -function is_token(token, type, val) { - return token.type == type && (val == null || token.value == val); -}; - -var EX_EOF = {}; - -function tokenizer($TEXT, filename) { - - var S = { - text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/\uFEFF/g, ''), - filename : filename, - pos : 0, - tokpos : 0, - line : 1, - tokline : 0, - col : 0, - tokcol : 0, - newline_before : false, - regex_allowed : false, - comments_before : [] - }; - - function peek() { return S.text.charAt(S.pos); }; - - function next(signal_eof, in_string) { - var ch = S.text.charAt(S.pos++); - if (signal_eof && !ch) - throw EX_EOF; - if (ch == "\n") { - S.newline_before = S.newline_before || !in_string; - ++S.line; - S.col = 0; - } else { - ++S.col; - } - return ch; - }; - - function find(what, signal_eof) { - var pos = S.text.indexOf(what, S.pos); - if (signal_eof && pos == -1) throw EX_EOF; - return pos; - }; - - function start_token() { - S.tokline = S.line; - S.tokcol = S.col; - S.tokpos = S.pos; - }; - - function token(type, value, is_comment) { - S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX[value]) || - (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) || - (type == "punc" && PUNC_BEFORE_EXPRESSION(value))); - var ret = { - type : type, - value : value, - line : S.tokline, - col : S.tokcol, - pos : S.tokpos, - endpos : S.pos, - nlb : S.newline_before, - file : filename - }; - if (!is_comment) { - ret.comments_before = S.comments_before; - S.comments_before = []; - // make note of any newlines in the comments that came before - for (var i = 0, len = ret.comments_before.length; i < len; i++) { - ret.nlb = ret.nlb || ret.comments_before[i].nlb; - } - } - S.newline_before = false; - return new AST_Token(ret); - }; - - function skip_whitespace() { - while (WHITESPACE_CHARS(peek())) - next(); - }; - - function read_while(pred) { - var ret = "", ch, i = 0; - while ((ch = peek()) && pred(ch, i++)) - ret += next(); - return ret; - }; - - function parse_error(err) { - js_error(err, filename, S.tokline, S.tokcol, S.tokpos); - }; - - function read_num(prefix) { - var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; - var num = read_while(function(ch, i){ - var code = ch.charCodeAt(0); - switch (code) { - case 120: case 88: // xX - return has_x ? false : (has_x = true); - case 101: case 69: // eE - return has_x ? true : has_e ? false : (has_e = after_e = true); - case 45: // - - return after_e || (i == 0 && !prefix); - case 43: // + - return after_e; - case (after_e = false, 46): // . - return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; - } - return is_alphanumeric_char(code); - }); - if (prefix) num = prefix + num; - var valid = parse_js_number(num); - if (!isNaN(valid)) { - return token("num", valid); - } else { - parse_error("Invalid syntax: " + num); - } - }; - - function read_escaped_char(in_string) { - var ch = next(true, in_string); - switch (ch.charCodeAt(0)) { - case 110 : return "\n"; - case 114 : return "\r"; - case 116 : return "\t"; - case 98 : return "\b"; - case 118 : return "\u000b"; // \v - case 102 : return "\f"; - case 48 : return "\0"; - case 120 : return String.fromCharCode(hex_bytes(2)); // \x - case 117 : return String.fromCharCode(hex_bytes(4)); // \u - case 10 : return ""; // newline - default : return ch; - } - }; - - function hex_bytes(n) { - var num = 0; - for (; n > 0; --n) { - var digit = parseInt(next(true), 16); - if (isNaN(digit)) - parse_error("Invalid hex-character pattern in string"); - num = (num << 4) | digit; - } - return num; - }; - - var read_string = with_eof_error("Unterminated string constant", function(){ - var quote = next(), ret = ""; - for (;;) { - var ch = next(true); - if (ch == "\\") { - // read OctalEscapeSequence (XXX: deprecated if "strict mode") - // https://github.com/mishoo/UglifyJS/issues/178 - var octal_len = 0, first = null; - ch = read_while(function(ch){ - if (ch >= "0" && ch <= "7") { - if (!first) { - first = ch; - return ++octal_len; - } - else if (first <= "3" && octal_len <= 2) return ++octal_len; - else if (first >= "4" && octal_len <= 1) return ++octal_len; - } - return false; - }); - if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8)); - else ch = read_escaped_char(true); - } - else if (ch == quote) break; - ret += ch; - } - return token("string", ret); - }); - - function read_line_comment() { - next(); - var i = find("\n"), ret; - if (i == -1) { - ret = S.text.substr(S.pos); - S.pos = S.text.length; - } else { - ret = S.text.substring(S.pos, i); - S.pos = i; - } - return token("comment1", ret, true); - }; - - var read_multiline_comment = with_eof_error("Unterminated multiline comment", function(){ - next(); - var i = find("*/", true); - var text = S.text.substring(S.pos, i); - var a = text.split("\n"), n = a.length; - // update stream position - S.pos = i + 2; - S.line += n - 1; - if (n > 1) S.col = a[n - 1].length; - else S.col += a[n - 1].length; - S.col += 2; - S.newline_before = S.newline_before || text.indexOf("\n") >= 0; - return token("comment2", text, true); - }); - - function read_name() { - var backslash = false, name = "", ch, escaped = false, hex; - while ((ch = peek()) != null) { - if (!backslash) { - if (ch == "\\") escaped = backslash = true, next(); - else if (is_identifier_char(ch)) name += next(); - else break; - } - else { - if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); - ch = read_escaped_char(); - if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); - name += ch; - backslash = false; - } - } - if (KEYWORDS(name) && escaped) { - hex = name.charCodeAt(0).toString(16).toUpperCase(); - name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); - } - return name; - }; - - var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){ - var prev_backslash = false, ch, in_class = false; - while ((ch = next(true))) if (prev_backslash) { - regexp += "\\" + ch; - prev_backslash = false; - } else if (ch == "[") { - in_class = true; - regexp += ch; - } else if (ch == "]" && in_class) { - in_class = false; - regexp += ch; - } else if (ch == "/" && !in_class) { - break; - } else if (ch == "\\") { - prev_backslash = true; - } else { - regexp += ch; - } - var mods = read_name(); - return token("regexp", new RegExp(regexp, mods)); - }); - - function read_operator(prefix) { - function grow(op) { - if (!peek()) return op; - var bigger = op + peek(); - if (OPERATORS(bigger)) { - next(); - return grow(bigger); - } else { - return op; - } - }; - return token("operator", grow(prefix || next())); - }; - - function handle_slash() { - next(); - var regex_allowed = S.regex_allowed; - switch (peek()) { - case "/": - S.comments_before.push(read_line_comment()); - S.regex_allowed = regex_allowed; - return next_token(); - case "*": - S.comments_before.push(read_multiline_comment()); - S.regex_allowed = regex_allowed; - return next_token(); - } - return S.regex_allowed ? read_regexp("") : read_operator("/"); - }; - - function handle_dot() { - next(); - return is_digit(peek().charCodeAt(0)) - ? read_num(".") - : token("punc", "."); - }; - - function read_word() { - var word = read_name(); - return KEYWORDS_ATOM(word) ? token("atom", word) - : !KEYWORDS(word) ? token("name", word) - : OPERATORS(word) ? token("operator", word) - : token("keyword", word); - }; - - function with_eof_error(eof_error, cont) { - return function(x) { - try { - return cont(x); - } catch(ex) { - if (ex === EX_EOF) parse_error(eof_error); - else throw ex; - } - }; - }; - - function next_token(force_regexp) { - if (force_regexp != null) - return read_regexp(force_regexp); - skip_whitespace(); - start_token(); - var ch = peek(); - if (!ch) return token("eof"); - var code = ch.charCodeAt(0); - switch (code) { - case 34: case 39: return read_string(); - case 46: return handle_dot(); - case 47: return handle_slash(); - } - if (is_digit(code)) return read_num(); - if (PUNC_CHARS(ch)) return token("punc", next()); - if (OPERATOR_CHARS(ch)) return read_operator(); - if (code == 92 || is_identifier_start(code)) return read_word(); - parse_error("Unexpected character '" + ch + "'"); - }; - - next_token.context = function(nc) { - if (nc) S = nc; - return S; - }; - - return next_token; - -}; - -/* -----[ Parser (constants) ]----- */ - -var UNARY_PREFIX = makePredicate([ - "typeof", - "void", - "delete", - "--", - "++", - "!", - "~", - "-", - "+" -]); - -var UNARY_POSTFIX = makePredicate([ "--", "++" ]); - -var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); - -var PRECEDENCE = (function(a, ret){ - for (var i = 0, n = 1; i < a.length; ++i, ++n) { - var b = a[i]; - for (var j = 0; j < b.length; ++j) { - ret[b[j]] = n; - } - } - return ret; -})( - [ - ["||"], - ["&&"], - ["|"], - ["^"], - ["&"], - ["==", "===", "!=", "!=="], - ["<", ">", "<=", ">=", "in", "instanceof"], - [">>", "<<", ">>>"], - ["+", "-"], - ["*", "/", "%"] - ], - {} -); - -var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); - -var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); - -/* -----[ Parser ]----- */ - -function parse($TEXT, options) { - - options = defaults(options, { - strict : false, - filename : null, - toplevel : null, - expression : false - }); - - var S = { - input : typeof $TEXT == "string" ? tokenizer($TEXT, options.filename) : $TEXT, - token : null, - prev : null, - peeked : null, - in_function : 0, - in_directives : true, - in_loop : 0, - labels : [] - }; - - S.token = next(); - - function is(type, value) { - return is_token(S.token, type, value); - }; - - function peek() { return S.peeked || (S.peeked = S.input()); }; - - function next() { - S.prev = S.token; - if (S.peeked) { - S.token = S.peeked; - S.peeked = null; - } else { - S.token = S.input(); - } - S.in_directives = S.in_directives && ( - S.token.type == "string" || is("punc", ";") - ); - return S.token; - }; - - function prev() { - return S.prev; - }; - - function croak(msg, line, col, pos) { - var ctx = S.input.context(); - js_error(msg, - ctx.filename, - line != null ? line : ctx.tokline, - col != null ? col : ctx.tokcol, - pos != null ? pos : ctx.tokpos); - }; - - function token_error(token, msg) { - croak(msg, token.line, token.col); - }; - - function unexpected(token) { - if (token == null) - token = S.token; - token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); - }; - - function expect_token(type, val) { - if (is(type, val)) { - return next(); - } - token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); - }; - - function expect(punc) { return expect_token("punc", punc); }; - - function can_insert_semicolon() { - return !options.strict && ( - S.token.nlb || is("eof") || is("punc", "}") - ); - }; - - function semicolon() { - if (is("punc", ";")) next(); - else if (!can_insert_semicolon()) unexpected(); - }; - - function parenthesised() { - expect("("); - var exp = expression(true); - expect(")"); - return exp; - }; - - function embed_tokens(parser) { - return function() { - var start = S.token; - var expr = parser(); - var end = prev(); - expr.start = start; - expr.end = end; - return expr; - }; - }; - - var statement = embed_tokens(function() { - var tmp; - if (is("operator", "/") || is("operator", "/=")) { - S.peeked = null; - S.token = S.input(S.token.value.substr(1)); // force regexp - } - switch (S.token.type) { - case "string": - var dir = S.in_directives, stat = simple_statement(); - // XXXv2: decide how to fix directives - if (dir && stat.body instanceof AST_String && !is("punc", ",")) - return new AST_Directive({ value: stat.body.value }); - return stat; - case "num": - case "regexp": - case "operator": - case "atom": - return simple_statement(); - - case "name": - return is_token(peek(), "punc", ":") - ? labeled_statement() - : simple_statement(); - - case "punc": - switch (S.token.value) { - case "{": - return new AST_BlockStatement({ - start : S.token, - body : block_(), - end : prev() - }); - case "[": - case "(": - return simple_statement(); - case ";": - next(); - return new AST_EmptyStatement(); - default: - unexpected(); - } - - case "keyword": - switch (tmp = S.token.value, next(), tmp) { - case "break": - return break_cont(AST_Break); - - case "continue": - return break_cont(AST_Continue); - - case "debugger": - semicolon(); - return new AST_Debugger(); - - case "do": - return new AST_Do({ - body : in_loop(statement), - condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp) - }); - - case "while": - return new AST_While({ - condition : parenthesised(), - body : in_loop(statement) - }); - - case "for": - return for_(); - - case "function": - return function_(true); - - case "if": - return if_(); - - case "return": - if (S.in_function == 0) - croak("'return' outside of function"); - return new AST_Return({ - value: ( is("punc", ";") - ? (next(), null) - : can_insert_semicolon() - ? null - : (tmp = expression(true), semicolon(), tmp) ) - }); - - case "switch": - return new AST_Switch({ - expression : parenthesised(), - body : in_loop(switch_body_) - }); - - case "throw": - if (S.token.nlb) - croak("Illegal newline after 'throw'"); - return new AST_Throw({ - value: (tmp = expression(true), semicolon(), tmp) - }); - - case "try": - return try_(); - - case "var": - return tmp = var_(), semicolon(), tmp; - - case "const": - return tmp = const_(), semicolon(), tmp; - - case "with": - return new AST_With({ - expression : parenthesised(), - body : statement() - }); - - default: - unexpected(); - } - } - }); - - function labeled_statement() { - var label = as_symbol(AST_Label); - if (find_if(function(l){ return l.name == label.name }, S.labels)) { - // ECMA-262, 12.12: An ECMAScript program is considered - // syntactically incorrect if it contains a - // LabelledStatement that is enclosed by a - // LabelledStatement with the same Identifier as label. - croak("Label " + label.name + " defined twice"); - } - expect(":"); - S.labels.push(label); - var stat = statement(); - S.labels.pop(); - return new AST_LabeledStatement({ body: stat, label: label }); - }; - - function simple_statement(tmp) { - return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); - }; - - function break_cont(type) { - var label = null; - if (!can_insert_semicolon()) { - label = as_symbol(AST_LabelRef, true); - } - if (label != null) { - if (!find_if(function(l){ return l.name == label.name }, S.labels)) - croak("Undefined label " + label.name); - } - else if (S.in_loop == 0) - croak(type.TYPE + " not inside a loop or switch"); - semicolon(); - return new type({ label: label }); - }; - - function for_() { - expect("("); - var init = null; - if (!is("punc", ";")) { - init = is("keyword", "var") - ? (next(), var_(true)) - : expression(true, true); - if (is("operator", "in")) { - if (init instanceof AST_Var && init.definitions.length > 1) - croak("Only one variable declaration allowed in for..in loop"); - next(); - return for_in(init); - } - } - return regular_for(init); - }; - - function regular_for(init) { - expect(";"); - var test = is("punc", ";") ? null : expression(true); - expect(";"); - var step = is("punc", ")") ? null : expression(true); - expect(")"); - return new AST_For({ - init : init, - condition : test, - step : step, - body : in_loop(statement) - }); - }; - - function for_in(init) { - var lhs = init instanceof AST_Var ? init.definitions[0].name : null; - var obj = expression(true); - expect(")"); - return new AST_ForIn({ - init : init, - name : lhs, - object : obj, - body : in_loop(statement) - }); - }; - - var function_ = function(in_statement, ctor) { - var is_accessor = ctor === AST_Accessor; - var name = (is("name") ? as_symbol(in_statement - ? AST_SymbolDefun - : is_accessor - ? AST_SymbolAccessor - : AST_SymbolLambda) - : is_accessor && (is("string") || is("num")) ? as_atom_node() - : null); - if (in_statement && !name) - unexpected(); - expect("("); - if (!ctor) ctor = in_statement ? AST_Defun : AST_Function; - return new ctor({ - name: name, - argnames: (function(first, a){ - while (!is("punc", ")")) { - if (first) first = false; else expect(","); - a.push(as_symbol(AST_SymbolFunarg)); - } - next(); - return a; - })(true, []), - body: (function(loop, labels){ - ++S.in_function; - S.in_directives = true; - S.in_loop = 0; - S.labels = []; - var a = block_(); - --S.in_function; - S.in_loop = loop; - S.labels = labels; - return a; - })(S.in_loop, S.labels) - }); - }; - - function if_() { - var cond = parenthesised(), body = statement(), belse = null; - if (is("keyword", "else")) { - next(); - belse = statement(); - } - return new AST_If({ - condition : cond, - body : body, - alternative : belse - }); - }; - - function block_() { - expect("{"); - var a = []; - while (!is("punc", "}")) { - if (is("eof")) unexpected(); - a.push(statement()); - } - next(); - return a; - }; - - function switch_body_() { - expect("{"); - var a = [], cur = null, branch = null, tmp; - while (!is("punc", "}")) { - if (is("eof")) unexpected(); - if (is("keyword", "case")) { - if (branch) branch.end = prev(); - cur = []; - branch = new AST_Case({ - start : (tmp = S.token, next(), tmp), - expression : expression(true), - body : cur - }); - a.push(branch); - expect(":"); - } - else if (is("keyword", "default")) { - if (branch) branch.end = prev(); - cur = []; - branch = new AST_Default({ - start : (tmp = S.token, next(), expect(":"), tmp), - body : cur - }); - a.push(branch); - } - else { - if (!cur) unexpected(); - cur.push(statement()); - } - } - if (branch) branch.end = prev(); - next(); - return a; - }; - - function try_() { - var body = block_(), bcatch = null, bfinally = null; - if (is("keyword", "catch")) { - var start = S.token; - next(); - expect("("); - var name = as_symbol(AST_SymbolCatch); - expect(")"); - bcatch = new AST_Catch({ - start : start, - argname : name, - body : block_(), - end : prev() - }); - } - if (is("keyword", "finally")) { - var start = S.token; - next(); - bfinally = new AST_Finally({ - start : start, - body : block_(), - end : prev() - }); - } - if (!bcatch && !bfinally) - croak("Missing catch/finally blocks"); - return new AST_Try({ - body : body, - bcatch : bcatch, - bfinally : bfinally - }); - }; - - function vardefs(no_in, in_const) { - var a = []; - for (;;) { - a.push(new AST_VarDef({ - start : S.token, - name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar), - value : is("operator", "=") ? (next(), expression(false, no_in)) : null, - end : prev() - })); - if (!is("punc", ",")) - break; - next(); - } - return a; - }; - - var var_ = function(no_in) { - return new AST_Var({ - start : prev(), - definitions : vardefs(no_in, false), - end : prev() - }); - }; - - var const_ = function() { - return new AST_Const({ - start : prev(), - definitions : vardefs(false, true), - end : prev() - }); - }; - - var new_ = function() { - var start = S.token; - expect_token("operator", "new"); - var newexp = expr_atom(false), args; - if (is("punc", "(")) { - next(); - args = expr_list(")"); - } else { - args = []; - } - return subscripts(new AST_New({ - start : start, - expression : newexp, - args : args, - end : prev() - }), true); - }; - - function as_atom_node() { - var tok = S.token, ret; - switch (tok.type) { - case "name": - return as_symbol(AST_SymbolRef); - case "num": - ret = new AST_Number({ start: tok, end: tok, value: tok.value }); - break; - case "string": - ret = new AST_String({ start: tok, end: tok, value: tok.value }); - break; - case "regexp": - ret = new AST_RegExp({ start: tok, end: tok, value: tok.value }); - break; - case "atom": - switch (tok.value) { - case "false": - ret = new AST_False({ start: tok, end: tok }); - break; - case "true": - ret = new AST_True({ start: tok, end: tok }); - break; - case "null": - ret = new AST_Null({ start: tok, end: tok }); - break; - } - break; - } - next(); - return ret; - }; - - var expr_atom = function(allow_calls) { - if (is("operator", "new")) { - return new_(); - } - var start = S.token; - if (is("punc")) { - switch (start.value) { - case "(": - next(); - var ex = expression(true); - ex.start = start; - ex.end = S.token; - expect(")"); - return subscripts(ex, allow_calls); - case "[": - return subscripts(array_(), allow_calls); - case "{": - return subscripts(object_(), allow_calls); - } - unexpected(); - } - if (is("keyword", "function")) { - next(); - var func = function_(false); - func.start = start; - func.end = prev(); - return subscripts(func, allow_calls); - } - if (ATOMIC_START_TOKEN[S.token.type]) { - return subscripts(as_atom_node(), allow_calls); - } - unexpected(); - }; - - function expr_list(closing, allow_trailing_comma, allow_empty) { - var first = true, a = []; - while (!is("punc", closing)) { - if (first) first = false; else expect(","); - if (allow_trailing_comma && is("punc", closing)) break; - if (is("punc", ",") && allow_empty) { - a.push(new AST_Hole({ start: S.token, end: S.token })); - } else { - a.push(expression(false)); - } - } - next(); - return a; - }; - - var array_ = embed_tokens(function() { - expect("["); - return new AST_Array({ - elements: expr_list("]", !options.strict, true) - }); - }); - - var object_ = embed_tokens(function() { - expect("{"); - var first = true, a = []; - while (!is("punc", "}")) { - if (first) first = false; else expect(","); - if (!options.strict && is("punc", "}")) - // allow trailing comma - break; - var start = S.token; - var type = start.type; - var name = as_property_name(); - if (type == "name" && !is("punc", ":")) { - if (name == "get") { - a.push(new AST_ObjectGetter({ - start : start, - key : name, - value : function_(false, AST_Accessor), - end : prev() - })); - continue; - } - if (name == "set") { - a.push(new AST_ObjectSetter({ - start : start, - key : name, - value : function_(false, AST_Accessor), - end : prev() - })); - continue; - } - } - expect(":"); - a.push(new AST_ObjectKeyVal({ - start : start, - key : name, - value : expression(false), - end : prev() - })); - } - next(); - return new AST_Object({ properties: a }); - }); - - function as_property_name() { - var tmp = S.token; - next(); - switch (tmp.type) { - case "num": - case "string": - case "name": - case "operator": - case "keyword": - case "atom": - return tmp.value; - default: - unexpected(); - } - }; - - function as_name() { - var tmp = S.token; - next(); - switch (tmp.type) { - case "name": - case "operator": - case "keyword": - case "atom": - return tmp.value; - default: - unexpected(); - } - }; - - function as_symbol(type, noerror) { - if (!is("name")) { - if (!noerror) croak("Name expected"); - return null; - } - var name = S.token.value; - var sym = new (name == "this" ? AST_This : type)({ - name : String(S.token.value), - start : S.token, - end : S.token - }); - next(); - return sym; - }; - - var subscripts = function(expr, allow_calls) { - var start = expr.start; - if (is("punc", ".")) { - next(); - return subscripts(new AST_Dot({ - start : start, - expression : expr, - property : as_name(), - end : prev() - }), allow_calls); - } - if (is("punc", "[")) { - next(); - var prop = expression(true); - expect("]"); - return subscripts(new AST_Sub({ - start : start, - expression : expr, - property : prop, - end : prev() - }), allow_calls); - } - if (allow_calls && is("punc", "(")) { - next(); - return subscripts(new AST_Call({ - start : start, - expression : expr, - args : expr_list(")"), - end : prev() - }), true); - } - return expr; - }; - - var maybe_unary = function(allow_calls) { - var start = S.token; - if (is("operator") && UNARY_PREFIX(start.value)) { - next(); - var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls)); - ex.start = start; - ex.end = prev(); - return ex; - } - var val = expr_atom(allow_calls); - while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) { - val = make_unary(AST_UnaryPostfix, S.token.value, val); - val.start = start; - val.end = S.token; - next(); - } - return val; - }; - - function make_unary(ctor, op, expr) { - if ((op == "++" || op == "--") && !is_assignable(expr)) - croak("Invalid use of " + op + " operator"); - return new ctor({ operator: op, expression: expr }); - }; - - var expr_op = function(left, min_prec, no_in) { - var op = is("operator") ? S.token.value : null; - if (op == "in" && no_in) op = null; - var prec = op != null ? PRECEDENCE[op] : null; - if (prec != null && prec > min_prec) { - next(); - var right = expr_op(maybe_unary(true), prec, no_in); - return expr_op(new AST_Binary({ - start : left.start, - left : left, - operator : op, - right : right, - end : right.end - }), min_prec, no_in); - } - return left; - }; - - function expr_ops(no_in) { - return expr_op(maybe_unary(true), 0, no_in); - }; - - var maybe_conditional = function(no_in) { - var start = S.token; - var expr = expr_ops(no_in); - if (is("operator", "?")) { - next(); - var yes = expression(false); - expect(":"); - return new AST_Conditional({ - start : start, - condition : expr, - consequent : yes, - alternative : expression(false, no_in), - end : peek() - }); - } - return expr; - }; - - function is_assignable(expr) { - if (!options.strict) return true; - if (expr instanceof AST_This) return false; - return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol); - }; - - var maybe_assign = function(no_in) { - var start = S.token; - var left = maybe_conditional(no_in), val = S.token.value; - if (is("operator") && ASSIGNMENT(val)) { - if (is_assignable(left)) { - next(); - return new AST_Assign({ - start : start, - left : left, - operator : val, - right : maybe_assign(no_in), - end : prev() - }); - } - croak("Invalid assignment"); - } - return left; - }; - - var expression = function(commas, no_in) { - var start = S.token; - var expr = maybe_assign(no_in); - if (commas && is("punc", ",")) { - next(); - return new AST_Seq({ - start : start, - car : expr, - cdr : expression(true, no_in), - end : peek() - }); - } - return expr; - }; - - function in_loop(cont) { - ++S.in_loop; - var ret = cont(); - --S.in_loop; - return ret; - }; - - if (options.expression) { - return expression(true); - } - - return (function(){ - var start = S.token; - var body = []; - while (!is("eof")) - body.push(statement()); - var end = prev(); - var toplevel = options.toplevel; - if (toplevel) { - toplevel.body = toplevel.body.concat(body); - toplevel.end = end; - } else { - toplevel = new AST_Toplevel({ start: start, body: body, end: end }); - } - return toplevel; - })(); - -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/scope.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/scope.js deleted file mode 100644 index d15cec754..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/scope.js +++ /dev/null @@ -1,581 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -function SymbolDef(scope, index, orig) { - this.name = orig.name; - this.orig = [ orig ]; - this.scope = scope; - this.references = []; - this.global = false; - this.mangled_name = null; - this.undeclared = false; - this.constant = false; - this.index = index; -}; - -SymbolDef.prototype = { - unmangleable: function(options) { - return (this.global && !(options && options.toplevel)) - || this.undeclared - || (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with)); - }, - mangle: function(options) { - if (!this.mangled_name && !this.unmangleable(options)) { - var s = this.scope; - if (this.orig[0] instanceof AST_SymbolLambda && !options.screw_ie8) - s = s.parent_scope; - this.mangled_name = s.next_mangled(options); - } - } -}; - -AST_Toplevel.DEFMETHOD("figure_out_scope", function(){ - // This does what ast_add_scope did in UglifyJS v1. - // - // Part of it could be done at parse time, but it would complicate - // the parser (and it's already kinda complex). It's also worth - // having it separated because we might need to call it multiple - // times on the same tree. - - // pass 1: setup scope chaining and handle definitions - var self = this; - var scope = self.parent_scope = null; - var labels = new Dictionary(); - var nesting = 0; - var tw = new TreeWalker(function(node, descend){ - if (node instanceof AST_Scope) { - node.init_scope_vars(nesting); - var save_scope = node.parent_scope = scope; - var save_labels = labels; - ++nesting; - scope = node; - labels = new Dictionary(); - descend(); - labels = save_labels; - scope = save_scope; - --nesting; - return true; // don't descend again in TreeWalker - } - if (node instanceof AST_Directive) { - node.scope = scope; - push_uniq(scope.directives, node.value); - return true; - } - if (node instanceof AST_With) { - for (var s = scope; s; s = s.parent_scope) - s.uses_with = true; - return; - } - if (node instanceof AST_LabeledStatement) { - var l = node.label; - if (labels.has(l.name)) - throw new Error(string_template("Label {name} defined twice", l)); - labels.set(l.name, l); - descend(); - labels.del(l.name); - return true; // no descend again - } - if (node instanceof AST_Symbol) { - node.scope = scope; - } - if (node instanceof AST_Label) { - node.thedef = node; - node.init_scope_vars(); - } - if (node instanceof AST_SymbolLambda) { - scope.def_function(node); - } - else if (node instanceof AST_SymbolDefun) { - // Careful here, the scope where this should be defined is - // the parent scope. The reason is that we enter a new - // scope when we encounter the AST_Defun node (which is - // instanceof AST_Scope) but we get to the symbol a bit - // later. - (node.scope = scope.parent_scope).def_function(node); - } - else if (node instanceof AST_SymbolVar - || node instanceof AST_SymbolConst) { - var def = scope.def_variable(node); - def.constant = node instanceof AST_SymbolConst; - def.init = tw.parent().value; - } - else if (node instanceof AST_SymbolCatch) { - // XXX: this is wrong according to ECMA-262 (12.4). the - // `catch` argument name should be visible only inside the - // catch block. For a quick fix AST_Catch should inherit - // from AST_Scope. Keeping it this way because of IE, - // which doesn't obey the standard. (it introduces the - // identifier in the enclosing scope) - scope.def_variable(node); - } - if (node instanceof AST_LabelRef) { - var sym = labels.get(node.name); - if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { - name: node.name, - line: node.start.line, - col: node.start.col - })); - node.thedef = sym; - } - }); - self.walk(tw); - - // pass 2: find back references and eval - var func = null; - var globals = self.globals = new Dictionary(); - var tw = new TreeWalker(function(node, descend){ - if (node instanceof AST_Lambda) { - var prev_func = func; - func = node; - descend(); - func = prev_func; - return true; - } - if (node instanceof AST_LabelRef) { - node.reference(); - return true; - } - if (node instanceof AST_SymbolRef) { - var name = node.name; - var sym = node.scope.find_variable(name); - if (!sym) { - var g; - if (globals.has(name)) { - g = globals.get(name); - } else { - g = new SymbolDef(self, globals.size(), node); - g.undeclared = true; - g.global = true; - globals.set(name, g); - } - node.thedef = g; - if (name == "eval" && tw.parent() instanceof AST_Call) { - for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) - s.uses_eval = true; - } - if (name == "arguments") { - func.uses_arguments = true; - } - } else { - node.thedef = sym; - } - node.reference(); - return true; - } - }); - self.walk(tw); -}); - -AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){ - this.directives = []; // contains the directives defined in this scope, i.e. "use strict" - this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) - this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) - this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement - this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` - this.parent_scope = null; // the parent scope - this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes - this.cname = -1; // the current index for mangling functions/variables - this.nesting = nesting; // the nesting level of this scope (0 means toplevel) -}); - -AST_Scope.DEFMETHOD("strict", function(){ - return this.has_directive("use strict"); -}); - -AST_Lambda.DEFMETHOD("init_scope_vars", function(){ - AST_Scope.prototype.init_scope_vars.apply(this, arguments); - this.uses_arguments = false; -}); - -AST_SymbolRef.DEFMETHOD("reference", function() { - var def = this.definition(); - def.references.push(this); - var s = this.scope; - while (s) { - push_uniq(s.enclosed, def); - if (s === def.scope) break; - s = s.parent_scope; - } - this.frame = this.scope.nesting - def.scope.nesting; -}); - -AST_Label.DEFMETHOD("init_scope_vars", function(){ - this.references = []; -}); - -AST_LabelRef.DEFMETHOD("reference", function(){ - this.thedef.references.push(this); -}); - -AST_Scope.DEFMETHOD("find_variable", function(name){ - if (name instanceof AST_Symbol) name = name.name; - return this.variables.get(name) - || (this.parent_scope && this.parent_scope.find_variable(name)); -}); - -AST_Scope.DEFMETHOD("has_directive", function(value){ - return this.parent_scope && this.parent_scope.has_directive(value) - || (this.directives.indexOf(value) >= 0 ? this : null); -}); - -AST_Scope.DEFMETHOD("def_function", function(symbol){ - this.functions.set(symbol.name, this.def_variable(symbol)); -}); - -AST_Scope.DEFMETHOD("def_variable", function(symbol){ - var def; - if (!this.variables.has(symbol.name)) { - def = new SymbolDef(this, this.variables.size(), symbol); - this.variables.set(symbol.name, def); - def.global = !this.parent_scope; - } else { - def = this.variables.get(symbol.name); - def.orig.push(symbol); - } - return symbol.thedef = def; -}); - -AST_Scope.DEFMETHOD("next_mangled", function(options){ - var ext = this.enclosed; - out: while (true) { - var m = base54(++this.cname); - if (!is_identifier(m)) continue; // skip over "do" - // we must ensure that the mangled name does not shadow a name - // from some parent scope that is referenced in this or in - // inner scopes. - for (var i = ext.length; --i >= 0;) { - var sym = ext[i]; - var name = sym.mangled_name || (sym.unmangleable(options) && sym.name); - if (m == name) continue out; - } - return m; - } -}); - -AST_Scope.DEFMETHOD("references", function(sym){ - if (sym instanceof AST_Symbol) sym = sym.definition(); - return this.enclosed.indexOf(sym) < 0 ? null : sym; -}); - -AST_Symbol.DEFMETHOD("unmangleable", function(options){ - return this.definition().unmangleable(options); -}); - -// property accessors are not mangleable -AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){ - return true; -}); - -// labels are always mangleable -AST_Label.DEFMETHOD("unmangleable", function(){ - return false; -}); - -AST_Symbol.DEFMETHOD("unreferenced", function(){ - return this.definition().references.length == 0 - && !(this.scope.uses_eval || this.scope.uses_with); -}); - -AST_Symbol.DEFMETHOD("undeclared", function(){ - return this.definition().undeclared; -}); - -AST_LabelRef.DEFMETHOD("undeclared", function(){ - return false; -}); - -AST_Label.DEFMETHOD("undeclared", function(){ - return false; -}); - -AST_Symbol.DEFMETHOD("definition", function(){ - return this.thedef; -}); - -AST_Symbol.DEFMETHOD("global", function(){ - return this.definition().global; -}); - -AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){ - return defaults(options, { - except : [], - eval : false, - sort : false, - toplevel : false, - screw_ie8 : false - }); -}); - -AST_Toplevel.DEFMETHOD("mangle_names", function(options){ - options = this._default_mangler_options(options); - // We only need to mangle declaration nodes. Special logic wired - // into the code generator will display the mangled name if it's - // present (and for AST_SymbolRef-s it'll use the mangled name of - // the AST_SymbolDeclaration that it points to). - var lname = -1; - var to_mangle = []; - var tw = new TreeWalker(function(node, descend){ - if (node instanceof AST_LabeledStatement) { - // lname is incremented when we get to the AST_Label - var save_nesting = lname; - descend(); - lname = save_nesting; - return true; // don't descend again in TreeWalker - } - if (node instanceof AST_Scope) { - var p = tw.parent(), a = []; - node.variables.each(function(symbol){ - if (options.except.indexOf(symbol.name) < 0) { - a.push(symbol); - } - }); - if (options.sort) a.sort(function(a, b){ - return b.references.length - a.references.length; - }); - to_mangle.push.apply(to_mangle, a); - return; - } - if (node instanceof AST_Label) { - var name; - do name = base54(++lname); while (!is_identifier(name)); - node.mangled_name = name; - return true; - } - }); - this.walk(tw); - to_mangle.forEach(function(def){ def.mangle(options) }); -}); - -AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){ - options = this._default_mangler_options(options); - var tw = new TreeWalker(function(node){ - if (node instanceof AST_Constant) - base54.consider(node.print_to_string()); - else if (node instanceof AST_Return) - base54.consider("return"); - else if (node instanceof AST_Throw) - base54.consider("throw"); - else if (node instanceof AST_Continue) - base54.consider("continue"); - else if (node instanceof AST_Break) - base54.consider("break"); - else if (node instanceof AST_Debugger) - base54.consider("debugger"); - else if (node instanceof AST_Directive) - base54.consider(node.value); - else if (node instanceof AST_While) - base54.consider("while"); - else if (node instanceof AST_Do) - base54.consider("do while"); - else if (node instanceof AST_If) { - base54.consider("if"); - if (node.alternative) base54.consider("else"); - } - else if (node instanceof AST_Var) - base54.consider("var"); - else if (node instanceof AST_Const) - base54.consider("const"); - else if (node instanceof AST_Lambda) - base54.consider("function"); - else if (node instanceof AST_For) - base54.consider("for"); - else if (node instanceof AST_ForIn) - base54.consider("for in"); - else if (node instanceof AST_Switch) - base54.consider("switch"); - else if (node instanceof AST_Case) - base54.consider("case"); - else if (node instanceof AST_Default) - base54.consider("default"); - else if (node instanceof AST_With) - base54.consider("with"); - else if (node instanceof AST_ObjectSetter) - base54.consider("set" + node.key); - else if (node instanceof AST_ObjectGetter) - base54.consider("get" + node.key); - else if (node instanceof AST_ObjectKeyVal) - base54.consider(node.key); - else if (node instanceof AST_New) - base54.consider("new"); - else if (node instanceof AST_This) - base54.consider("this"); - else if (node instanceof AST_Try) - base54.consider("try"); - else if (node instanceof AST_Catch) - base54.consider("catch"); - else if (node instanceof AST_Finally) - base54.consider("finally"); - else if (node instanceof AST_Symbol && node.unmangleable(options)) - base54.consider(node.name); - else if (node instanceof AST_Unary || node instanceof AST_Binary) - base54.consider(node.operator); - else if (node instanceof AST_Dot) - base54.consider(node.property); - }); - this.walk(tw); - base54.sort(); -}); - -var base54 = (function() { - var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; - var chars, frequency; - function reset() { - frequency = Object.create(null); - chars = string.split("").map(function(ch){ return ch.charCodeAt(0) }); - chars.forEach(function(ch){ frequency[ch] = 0 }); - } - base54.consider = function(str){ - for (var i = str.length; --i >= 0;) { - var code = str.charCodeAt(i); - if (code in frequency) ++frequency[code]; - } - }; - base54.sort = function() { - chars = mergeSort(chars, function(a, b){ - if (is_digit(a) && !is_digit(b)) return 1; - if (is_digit(b) && !is_digit(a)) return -1; - return frequency[b] - frequency[a]; - }); - }; - base54.reset = reset; - reset(); - base54.get = function(){ return chars }; - base54.freq = function(){ return frequency }; - function base54(num) { - var ret = "", base = 54; - do { - ret += String.fromCharCode(chars[num % base]); - num = Math.floor(num / base); - base = 64; - } while (num > 0); - return ret; - }; - return base54; -})(); - -AST_Toplevel.DEFMETHOD("scope_warnings", function(options){ - options = defaults(options, { - undeclared : false, // this makes a lot of noise - unreferenced : true, - assign_to_global : true, - func_arguments : true, - nested_defuns : true, - eval : true - }); - var tw = new TreeWalker(function(node){ - if (options.undeclared - && node instanceof AST_SymbolRef - && node.undeclared()) - { - // XXX: this also warns about JS standard names, - // i.e. Object, Array, parseInt etc. Should add a list of - // exceptions. - AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", { - name: node.name, - file: node.start.file, - line: node.start.line, - col: node.start.col - }); - } - if (options.assign_to_global) - { - var sym = null; - if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) - sym = node.left; - else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef) - sym = node.init; - if (sym - && (sym.undeclared() - || (sym.global() && sym.scope !== sym.definition().scope))) { - AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", { - msg: sym.undeclared() ? "Accidental global?" : "Assignment to global", - name: sym.name, - file: sym.start.file, - line: sym.start.line, - col: sym.start.col - }); - } - } - if (options.eval - && node instanceof AST_SymbolRef - && node.undeclared() - && node.name == "eval") { - AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start); - } - if (options.unreferenced - && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label) - && node.unreferenced()) { - AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", { - type: node instanceof AST_Label ? "Label" : "Symbol", - name: node.name, - file: node.start.file, - line: node.start.line, - col: node.start.col - }); - } - if (options.func_arguments - && node instanceof AST_Lambda - && node.uses_arguments) { - AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", { - name: node.name ? node.name.name : "anonymous", - file: node.start.file, - line: node.start.line, - col: node.start.col - }); - } - if (options.nested_defuns - && node instanceof AST_Defun - && !(tw.parent() instanceof AST_Scope)) { - AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", { - name: node.name.name, - type: tw.parent().TYPE, - file: node.start.file, - line: node.start.line, - col: node.start.col - }); - } - }); - this.walk(tw); -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/sourcemap.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/sourcemap.js deleted file mode 100644 index 342990812..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/sourcemap.js +++ /dev/null @@ -1,81 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -// a small wrapper around fitzgen's source-map library -function SourceMap(options) { - options = defaults(options, { - file : null, - root : null, - orig : null, - }); - var generator = new MOZ_SourceMap.SourceMapGenerator({ - file : options.file, - sourceRoot : options.root - }); - var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig); - function add(source, gen_line, gen_col, orig_line, orig_col, name) { - if (orig_map) { - var info = orig_map.originalPositionFor({ - line: orig_line, - column: orig_col - }); - source = info.source; - orig_line = info.line; - orig_col = info.column; - name = info.name; - } - generator.addMapping({ - generated : { line: gen_line, column: gen_col }, - original : { line: orig_line, column: orig_col }, - source : source, - name : name - }); - }; - return { - add : add, - get : function() { return generator }, - toString : function() { return generator.toString() } - }; -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/transform.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/transform.js deleted file mode 100644 index 7a61e5f3c..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/transform.js +++ /dev/null @@ -1,217 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -// Tree transformer helpers. - -function TreeTransformer(before, after) { - TreeWalker.call(this); - this.before = before; - this.after = after; -} -TreeTransformer.prototype = new TreeWalker; - -(function(undefined){ - - function _(node, descend) { - node.DEFMETHOD("transform", function(tw, in_list){ - var x, y; - tw.push(this); - if (tw.before) x = tw.before(this, descend, in_list); - if (x === undefined) { - if (!tw.after) { - x = this; - descend(x, tw); - } else { - tw.stack[tw.stack.length - 1] = x = this.clone(); - descend(x, tw); - y = tw.after(x, in_list); - if (y !== undefined) x = y; - } - } - tw.pop(); - return x; - }); - }; - - function do_list(list, tw) { - return MAP(list, function(node){ - return node.transform(tw, true); - }); - }; - - _(AST_Node, noop); - - _(AST_LabeledStatement, function(self, tw){ - self.label = self.label.transform(tw); - self.body = self.body.transform(tw); - }); - - _(AST_SimpleStatement, function(self, tw){ - self.body = self.body.transform(tw); - }); - - _(AST_Block, function(self, tw){ - self.body = do_list(self.body, tw); - }); - - _(AST_DWLoop, function(self, tw){ - self.condition = self.condition.transform(tw); - self.body = self.body.transform(tw); - }); - - _(AST_For, function(self, tw){ - if (self.init) self.init = self.init.transform(tw); - if (self.condition) self.condition = self.condition.transform(tw); - if (self.step) self.step = self.step.transform(tw); - self.body = self.body.transform(tw); - }); - - _(AST_ForIn, function(self, tw){ - self.init = self.init.transform(tw); - self.object = self.object.transform(tw); - self.body = self.body.transform(tw); - }); - - _(AST_With, function(self, tw){ - self.expression = self.expression.transform(tw); - self.body = self.body.transform(tw); - }); - - _(AST_Exit, function(self, tw){ - if (self.value) self.value = self.value.transform(tw); - }); - - _(AST_LoopControl, function(self, tw){ - if (self.label) self.label = self.label.transform(tw); - }); - - _(AST_If, function(self, tw){ - self.condition = self.condition.transform(tw); - self.body = self.body.transform(tw); - if (self.alternative) self.alternative = self.alternative.transform(tw); - }); - - _(AST_Switch, function(self, tw){ - self.expression = self.expression.transform(tw); - self.body = do_list(self.body, tw); - }); - - _(AST_Case, function(self, tw){ - self.expression = self.expression.transform(tw); - self.body = do_list(self.body, tw); - }); - - _(AST_Try, function(self, tw){ - self.body = do_list(self.body, tw); - if (self.bcatch) self.bcatch = self.bcatch.transform(tw); - if (self.bfinally) self.bfinally = self.bfinally.transform(tw); - }); - - _(AST_Catch, function(self, tw){ - self.argname = self.argname.transform(tw); - self.body = do_list(self.body, tw); - }); - - _(AST_Definitions, function(self, tw){ - self.definitions = do_list(self.definitions, tw); - }); - - _(AST_VarDef, function(self, tw){ - if (self.value) self.value = self.value.transform(tw); - }); - - _(AST_Lambda, function(self, tw){ - if (self.name) self.name = self.name.transform(tw); - self.argnames = do_list(self.argnames, tw); - self.body = do_list(self.body, tw); - }); - - _(AST_Call, function(self, tw){ - self.expression = self.expression.transform(tw); - self.args = do_list(self.args, tw); - }); - - _(AST_Seq, function(self, tw){ - self.car = self.car.transform(tw); - self.cdr = self.cdr.transform(tw); - }); - - _(AST_Dot, function(self, tw){ - self.expression = self.expression.transform(tw); - }); - - _(AST_Sub, function(self, tw){ - self.expression = self.expression.transform(tw); - self.property = self.property.transform(tw); - }); - - _(AST_Unary, function(self, tw){ - self.expression = self.expression.transform(tw); - }); - - _(AST_Binary, function(self, tw){ - self.left = self.left.transform(tw); - self.right = self.right.transform(tw); - }); - - _(AST_Conditional, function(self, tw){ - self.condition = self.condition.transform(tw); - self.consequent = self.consequent.transform(tw); - self.alternative = self.alternative.transform(tw); - }); - - _(AST_Array, function(self, tw){ - self.elements = do_list(self.elements, tw); - }); - - _(AST_Object, function(self, tw){ - self.properties = do_list(self.properties, tw); - }); - - _(AST_ObjectProperty, function(self, tw){ - self.value = self.value.transform(tw); - }); - -})(); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/utils.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/utils.js deleted file mode 100644 index 73964a09b..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/lib/utils.js +++ /dev/null @@ -1,295 +0,0 @@ -/*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - https://github.com/mishoo/UglifyJS2 - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2012 (c) Mihai Bazon - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - * Redistributions of source code must retain the above - copyright notice, this list of conditions and the following - disclaimer. - - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following - disclaimer in the documentation and/or other materials - provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR - TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. - - ***********************************************************************/ - -"use strict"; - -function array_to_hash(a) { - var ret = Object.create(null); - for (var i = 0; i < a.length; ++i) - ret[a[i]] = true; - return ret; -}; - -function slice(a, start) { - return Array.prototype.slice.call(a, start || 0); -}; - -function characters(str) { - return str.split(""); -}; - -function member(name, array) { - for (var i = array.length; --i >= 0;) - if (array[i] == name) - return true; - return false; -}; - -function find_if(func, array) { - for (var i = 0, n = array.length; i < n; ++i) { - if (func(array[i])) - return array[i]; - } -}; - -function repeat_string(str, i) { - if (i <= 0) return ""; - if (i == 1) return str; - var d = repeat_string(str, i >> 1); - d += d; - if (i & 1) d += str; - return d; -}; - -function DefaultsError(msg, defs) { - this.msg = msg; - this.defs = defs; -}; - -function defaults(args, defs, croak) { - if (args === true) - args = {}; - var ret = args || {}; - if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i)) - throw new DefaultsError("`" + i + "` is not a supported option", defs); - for (var i in defs) if (defs.hasOwnProperty(i)) { - ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i]; - } - return ret; -}; - -function merge(obj, ext) { - for (var i in ext) if (ext.hasOwnProperty(i)) { - obj[i] = ext[i]; - } - return obj; -}; - -function noop() {}; - -var MAP = (function(){ - function MAP(a, f, backwards) { - var ret = [], top = [], i; - function doit() { - var val = f(a[i], i); - var is_last = val instanceof Last; - if (is_last) val = val.v; - if (val instanceof AtTop) { - val = val.v; - if (val instanceof Splice) { - top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); - } else { - top.push(val); - } - } - else if (val !== skip) { - if (val instanceof Splice) { - ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); - } else { - ret.push(val); - } - } - return is_last; - }; - if (a instanceof Array) { - if (backwards) { - for (i = a.length; --i >= 0;) if (doit()) break; - ret.reverse(); - top.reverse(); - } else { - for (i = 0; i < a.length; ++i) if (doit()) break; - } - } - else { - for (i in a) if (a.hasOwnProperty(i)) if (doit()) break; - } - return top.concat(ret); - }; - MAP.at_top = function(val) { return new AtTop(val) }; - MAP.splice = function(val) { return new Splice(val) }; - MAP.last = function(val) { return new Last(val) }; - var skip = MAP.skip = {}; - function AtTop(val) { this.v = val }; - function Splice(val) { this.v = val }; - function Last(val) { this.v = val }; - return MAP; -})(); - -function push_uniq(array, el) { - if (array.indexOf(el) < 0) - array.push(el); -}; - -function string_template(text, props) { - return text.replace(/\{(.+?)\}/g, function(str, p){ - return props[p]; - }); -}; - -function remove(array, el) { - for (var i = array.length; --i >= 0;) { - if (array[i] === el) array.splice(i, 1); - } -}; - -function mergeSort(array, cmp) { - if (array.length < 2) return array.slice(); - function merge(a, b) { - var r = [], ai = 0, bi = 0, i = 0; - while (ai < a.length && bi < b.length) { - cmp(a[ai], b[bi]) <= 0 - ? r[i++] = a[ai++] - : r[i++] = b[bi++]; - } - if (ai < a.length) r.push.apply(r, a.slice(ai)); - if (bi < b.length) r.push.apply(r, b.slice(bi)); - return r; - }; - function _ms(a) { - if (a.length <= 1) - return a; - var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); - left = _ms(left); - right = _ms(right); - return merge(left, right); - }; - return _ms(array); -}; - -function set_difference(a, b) { - return a.filter(function(el){ - return b.indexOf(el) < 0; - }); -}; - -function set_intersection(a, b) { - return a.filter(function(el){ - return b.indexOf(el) >= 0; - }); -}; - -// this function is taken from Acorn [1], written by Marijn Haverbeke -// [1] https://github.com/marijnh/acorn -function makePredicate(words) { - if (!(words instanceof Array)) words = words.split(" "); - var f = "", cats = []; - out: for (var i = 0; i < words.length; ++i) { - for (var j = 0; j < cats.length; ++j) - if (cats[j][0].length == words[i].length) { - cats[j].push(words[i]); - continue out; - } - cats.push([words[i]]); - } - function compareTo(arr) { - if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; - f += "switch(str){"; - for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; - f += "return true}return false;"; - } - // When there are more than three length categories, an outer - // switch first dispatches on the lengths, to save on comparisons. - if (cats.length > 3) { - cats.sort(function(a, b) {return b.length - a.length;}); - f += "switch(str.length){"; - for (var i = 0; i < cats.length; ++i) { - var cat = cats[i]; - f += "case " + cat[0].length + ":"; - compareTo(cat); - } - f += "}"; - // Otherwise, simply generate a flat `switch` statement. - } else { - compareTo(words); - } - return new Function("str", f); -}; - -function all(array, predicate) { - for (var i = array.length; --i >= 0;) - if (!predicate(array[i])) - return false; - return true; -}; - -function Dictionary() { - this._values = Object.create(null); - this._size = 0; -}; -Dictionary.prototype = { - set: function(key, val) { - if (!this.has(key)) ++this._size; - this._values["$" + key] = val; - return this; - }, - add: function(key, val) { - if (this.has(key)) { - this.get(key).push(val); - } else { - this.set(key, [ val ]); - } - return this; - }, - get: function(key) { return this._values["$" + key] }, - del: function(key) { - if (this.has(key)) { - --this._size; - delete this._values["$" + key]; - } - return this; - }, - has: function(key) { return ("$" + key) in this._values }, - each: function(f) { - for (var i in this._values) - f(this._values[i], i.substr(1)); - }, - size: function() { - return this._size; - }, - map: function(f) { - var ret = []; - for (var i in this._values) - ret.push(f(this._values[i], i.substr(1))); - return ret; - } -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/.npmignore b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/.npmignore deleted file mode 100644 index 3dddf3f67..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -dist/* -node_modules/* diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/.travis.yml b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/.travis.yml deleted file mode 100644 index ddc9c4f98..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.8 - - "0.10" \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/CHANGELOG.md b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/CHANGELOG.md deleted file mode 100644 index 98b90d52b..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/CHANGELOG.md +++ /dev/null @@ -1,112 +0,0 @@ -# Change Log - -## 0.1.31 - -* Delay parsing the mappings in SourceMapConsumer until queried for a source - location. - -* Support Sass source maps (which at the time of writing deviate from the spec - in small ways) in SourceMapConsumer. - -## 0.1.30 - -* Do not join source root with a source, when the source is a data URI. - -* Extend the test runner to allow running single specific test files at a time. - -* Performance improvements in `SourceNode.prototype.walk` and - `SourceMapConsumer.prototype.eachMapping`. - -* Source map browser builds will now work inside Workers. - -* Better error messages when attempting to add an invalid mapping to a - `SourceMapGenerator`. - -## 0.1.29 - -* Allow duplicate entries in the `names` and `sources` arrays of source maps - (usually from TypeScript) we are parsing. Fixes github isse 72. - -## 0.1.28 - -* Skip duplicate mappings when creating source maps from SourceNode; github - issue 75. - -## 0.1.27 - -* Don't throw an error when the `file` property is missing in SourceMapConsumer, - we don't use it anyway. - -## 0.1.26 - -* Fix SourceNode.fromStringWithSourceMap for empty maps. Fixes github issue 70. - -## 0.1.25 - -* Make compatible with browserify - -## 0.1.24 - -* Fix issue with absolute paths and `file://` URIs. See - https://bugzilla.mozilla.org/show_bug.cgi?id=885597 - -## 0.1.23 - -* Fix issue with absolute paths and sourcesContent, github issue 64. - -## 0.1.22 - -* Ignore duplicate mappings in SourceMapGenerator. Fixes github issue 21. - -## 0.1.21 - -* Fixed handling of sources that start with a slash so that they are relative to - the source root's host. - -## 0.1.20 - -* Fixed github issue #43: absolute URLs aren't joined with the source root - anymore. - -## 0.1.19 - -* Using Travis CI to run tests. - -## 0.1.18 - -* Fixed a bug in the handling of sourceRoot. - -## 0.1.17 - -* Added SourceNode.fromStringWithSourceMap. - -## 0.1.16 - -* Added missing documentation. - -* Fixed the generating of empty mappings in SourceNode. - -## 0.1.15 - -* Added SourceMapGenerator.applySourceMap. - -## 0.1.14 - -* The sourceRoot is now handled consistently. - -## 0.1.13 - -* Added SourceMapGenerator.fromSourceMap. - -## 0.1.12 - -* SourceNode now generates empty mappings too. - -## 0.1.11 - -* Added name support to SourceNode. - -## 0.1.10 - -* Added sourcesContent support to the customer and generator. - diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/LICENSE b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/LICENSE deleted file mode 100644 index ed1b7cf27..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ - -Copyright (c) 2009-2011, Mozilla Foundation and contributors -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the names of the Mozilla Foundation nor the names of project - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/Makefile.dryice.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/Makefile.dryice.js deleted file mode 100644 index d6fc26a79..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/Makefile.dryice.js +++ /dev/null @@ -1,166 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -var path = require('path'); -var fs = require('fs'); -var copy = require('dryice').copy; - -function removeAmdefine(src) { - src = String(src).replace( - /if\s*\(typeof\s*define\s*!==\s*'function'\)\s*{\s*var\s*define\s*=\s*require\('amdefine'\)\(module,\s*require\);\s*}\s*/g, - ''); - src = src.replace( - /\b(define\(.*)('amdefine',?)/gm, - '$1'); - return src; -} -removeAmdefine.onRead = true; - -function makeNonRelative(src) { - return src - .replace(/require\('.\//g, 'require(\'source-map/') - .replace(/\.\.\/\.\.\/lib\//g, ''); -} -makeNonRelative.onRead = true; - -function buildBrowser() { - console.log('\nCreating dist/source-map.js'); - - var project = copy.createCommonJsProject({ - roots: [ path.join(__dirname, 'lib') ] - }); - - copy({ - source: [ - 'build/mini-require.js', - { - project: project, - require: [ 'source-map/source-map-generator', - 'source-map/source-map-consumer', - 'source-map/source-node'] - }, - 'build/suffix-browser.js' - ], - filter: [ - copy.filter.moduleDefines, - removeAmdefine - ], - dest: 'dist/source-map.js' - }); -} - -function buildBrowserMin() { - console.log('\nCreating dist/source-map.min.js'); - - copy({ - source: 'dist/source-map.js', - filter: copy.filter.uglifyjs, - dest: 'dist/source-map.min.js' - }); -} - -function buildFirefox() { - console.log('\nCreating dist/SourceMap.jsm'); - - var project = copy.createCommonJsProject({ - roots: [ path.join(__dirname, 'lib') ] - }); - - copy({ - source: [ - 'build/prefix-source-map.jsm', - { - project: project, - require: [ 'source-map/source-map-consumer', - 'source-map/source-map-generator', - 'source-map/source-node' ] - }, - 'build/suffix-source-map.jsm' - ], - filter: [ - copy.filter.moduleDefines, - removeAmdefine, - makeNonRelative - ], - dest: 'dist/SourceMap.jsm' - }); - - // Create dist/test/Utils.jsm - console.log('\nCreating dist/test/Utils.jsm'); - - project = copy.createCommonJsProject({ - roots: [ __dirname, path.join(__dirname, 'lib') ] - }); - - copy({ - source: [ - 'build/prefix-utils.jsm', - 'build/assert-shim.js', - { - project: project, - require: [ 'test/source-map/util' ] - }, - 'build/suffix-utils.jsm' - ], - filter: [ - copy.filter.moduleDefines, - removeAmdefine, - makeNonRelative - ], - dest: 'dist/test/Utils.jsm' - }); - - function isTestFile(f) { - return /^test\-.*?\.js/.test(f); - } - - var testFiles = fs.readdirSync(path.join(__dirname, 'test', 'source-map')).filter(isTestFile); - - testFiles.forEach(function (testFile) { - console.log('\nCreating', path.join('dist', 'test', testFile.replace(/\-/g, '_'))); - - copy({ - source: [ - 'build/test-prefix.js', - path.join('test', 'source-map', testFile), - 'build/test-suffix.js' - ], - filter: [ - removeAmdefine, - makeNonRelative, - function (input, source) { - return input.replace('define(', - 'define("' - + path.join('test', 'source-map', testFile.replace(/\.js$/, '')) - + '", ["require", "exports", "module"], '); - }, - function (input, source) { - return input.replace('{THIS_MODULE}', function () { - return "test/source-map/" + testFile.replace(/\.js$/, ''); - }); - } - ], - dest: path.join('dist', 'test', testFile.replace(/\-/g, '_')) - }); - }); -} - -function ensureDir(name) { - var dirExists = false; - try { - dirExists = fs.statSync(name).isDirectory(); - } catch (err) {} - - if (!dirExists) { - fs.mkdirSync(name, 0777); - } -} - -ensureDir("dist"); -ensureDir("dist/test"); -buildFirefox(); -buildBrowser(); -buildBrowserMin(); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/README.md b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/README.md deleted file mode 100644 index c20437bc6..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/README.md +++ /dev/null @@ -1,434 +0,0 @@ -# Source Map - -This is a library to generate and consume the source map format -[described here][format]. - -This library is written in the Asynchronous Module Definition format, and works -in the following environments: - -* Modern Browsers supporting ECMAScript 5 (either after the build, or with an - AMD loader such as RequireJS) - -* Inside Firefox (as a JSM file, after the build) - -* With NodeJS versions 0.8.X and higher - -## Node - - $ npm install source-map - -## Building from Source (for everywhere else) - -Install Node and then run - - $ git clone https://fitzgen@github.com/mozilla/source-map.git - $ cd source-map - $ npm link . - -Next, run - - $ node Makefile.dryice.js - -This should spew a bunch of stuff to stdout, and create the following files: - -* `dist/source-map.js` - The unminified browser version. - -* `dist/source-map.min.js` - The minified browser version. - -* `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox source. - -## Examples - -### Consuming a source map - - var rawSourceMap = { - version: 3, - file: 'min.js', - names: ['bar', 'baz', 'n'], - sources: ['one.js', 'two.js'], - sourceRoot: 'http://example.com/www/js/', - mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' - }; - - var smc = new SourceMapConsumer(rawSourceMap); - - console.log(smc.sources); - // [ 'http://example.com/www/js/one.js', - // 'http://example.com/www/js/two.js' ] - - console.log(smc.originalPositionFor({ - line: 2, - column: 28 - })); - // { source: 'http://example.com/www/js/two.js', - // line: 2, - // column: 10, - // name: 'n' } - - console.log(smc.generatedPositionFor({ - source: 'http://example.com/www/js/two.js', - line: 2, - column: 10 - })); - // { line: 2, column: 28 } - - smc.eachMapping(function (m) { - // ... - }); - -### Generating a source map - -In depth guide: -[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) - -#### With SourceNode (high level API) - - function compile(ast) { - switch (ast.type) { - case 'BinaryExpression': - return new SourceNode( - ast.location.line, - ast.location.column, - ast.location.source, - [compile(ast.left), " + ", compile(ast.right)] - ); - case 'Literal': - return new SourceNode( - ast.location.line, - ast.location.column, - ast.location.source, - String(ast.value) - ); - // ... - default: - throw new Error("Bad AST"); - } - } - - var ast = parse("40 + 2", "add.js"); - console.log(compile(ast).toStringWithSourceMap({ - file: 'add.js' - })); - // { code: '40 + 2', - // map: [object SourceMapGenerator] } - -#### With SourceMapGenerator (low level API) - - var map = new SourceMapGenerator({ - file: "source-mapped.js" - }); - - map.addMapping({ - generated: { - line: 10, - column: 35 - }, - source: "foo.js", - original: { - line: 33, - column: 2 - }, - name: "christopher" - }); - - console.log(map.toString()); - // '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' - -## API - -Get a reference to the module: - - // NodeJS - var sourceMap = require('source-map'); - - // Browser builds - var sourceMap = window.sourceMap; - - // Inside Firefox - let sourceMap = {}; - Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap); - -### SourceMapConsumer - -A SourceMapConsumer instance represents a parsed source map which we can query -for information about the original file positions by giving it a file position -in the generated source. - -#### new SourceMapConsumer(rawSourceMap) - -The only parameter is the raw source map (either as a string which can be -`JSON.parse`'d, or an object). According to the spec, source maps have the -following attributes: - -* `version`: Which version of the source map spec this map is following. - -* `sources`: An array of URLs to the original source files. - -* `names`: An array of identifiers which can be referrenced by individual - mappings. - -* `sourceRoot`: Optional. The URL root from which all sources are relative. - -* `sourcesContent`: Optional. An array of contents of the original source files. - -* `mappings`: A string of base64 VLQs which contain the actual mappings. - -* `file`: The generated filename this source map is associated with. - -#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) - -Returns the original source, line, and column information for the generated -source's line and column positions provided. The only argument is an object with -the following properties: - -* `line`: The line number in the generated source. - -* `column`: The column number in the generated source. - -and an object is returned with the following properties: - -* `source`: The original source file, or null if this information is not - available. - -* `line`: The line number in the original source, or null if this information is - not available. - -* `column`: The column number in the original source, or null or null if this - information is not available. - -* `name`: The original identifier, or null if this information is not available. - -#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) - -Returns the generated line and column information for the original source, -line, and column positions provided. The only argument is an object with -the following properties: - -* `source`: The filename of the original source. - -* `line`: The line number in the original source. - -* `column`: The column number in the original source. - -and an object is returned with the following properties: - -* `line`: The line number in the generated source, or null. - -* `column`: The column number in the generated source, or null. - -#### SourceMapConsumer.prototype.sourceContentFor(source) - -Returns the original source content for the source provided. The only -argument is the URL of the original source file. - -#### SourceMapConsumer.prototype.eachMapping(callback, context, order) - -Iterate over each mapping between an original source/line/column and a -generated line/column in this source map. - -* `callback`: The function that is called with each mapping. Mappings have the - form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, - name }` - -* `context`: Optional. If specified, this object will be the value of `this` - every time that `callback` is called. - -* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or - `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over - the mappings sorted by the generated file's line/column order or the - original's source/line/column order, respectively. Defaults to - `SourceMapConsumer.GENERATED_ORDER`. - -### SourceMapGenerator - -An instance of the SourceMapGenerator represents a source map which is being -built incrementally. - -#### new SourceMapGenerator(startOfSourceMap) - -To create a new one, you must pass an object with the following properties: - -* `file`: The filename of the generated source that this source map is - associated with. - -* `sourceRoot`: An optional root for all relative URLs in this source map. - -#### SourceMapGenerator.fromSourceMap(sourceMapConsumer) - -Creates a new SourceMapGenerator based on a SourceMapConsumer - -* `sourceMapConsumer` The SourceMap. - -#### SourceMapGenerator.prototype.addMapping(mapping) - -Add a single mapping from original source line and column to the generated -source's line and column for this source map being created. The mapping object -should have the following properties: - -* `generated`: An object with the generated line and column positions. - -* `original`: An object with the original line and column positions. - -* `source`: The original source file (relative to the sourceRoot). - -* `name`: An optional original token name for this mapping. - -#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) - -Set the source content for an original source file. - -* `sourceFile` the URL of the original source file. - -* `sourceContent` the content of the source file. - -#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile]) - -Applies a SourceMap for a source file to the SourceMap. -Each mapping to the supplied source file is rewritten using the -supplied SourceMap. Note: The resolution for the resulting mappings -is the minimium of this map and the supplied map. - -* `sourceMapConsumer`: The SourceMap to be applied. - -* `sourceFile`: Optional. The filename of the source file. - If omitted, sourceMapConsumer.file will be used. - -#### SourceMapGenerator.prototype.toString() - -Renders the source map being generated to a string. - -### SourceNode - -SourceNodes provide a way to abstract over interpolating and/or concatenating -snippets of generated JavaScript source code, while maintaining the line and -column information associated between those snippets and the original source -code. This is useful as the final intermediate representation a compiler might -use before outputting the generated JS and source map. - -#### new SourceNode(line, column, source[, chunk[, name]]) - -* `line`: The original line number associated with this source node, or null if - it isn't associated with an original line. - -* `column`: The original column number associated with this source node, or null - if it isn't associated with an original column. - -* `source`: The original source's filename. - -* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see - below. - -* `name`: Optional. The original identifier. - -#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer) - -Creates a SourceNode from generated code and a SourceMapConsumer. - -* `code`: The generated code - -* `sourceMapConsumer` The SourceMap for the generated code - -#### SourceNode.prototype.add(chunk) - -Add a chunk of generated JS to this source node. - -* `chunk`: A string snippet of generated JS code, another instance of - `SourceNode`, or an array where each member is one of those things. - -#### SourceNode.prototype.prepend(chunk) - -Prepend a chunk of generated JS to this source node. - -* `chunk`: A string snippet of generated JS code, another instance of - `SourceNode`, or an array where each member is one of those things. - -#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) - -Set the source content for a source file. This will be added to the -`SourceMap` in the `sourcesContent` field. - -* `sourceFile`: The filename of the source file - -* `sourceContent`: The content of the source file - -#### SourceNode.prototype.walk(fn) - -Walk over the tree of JS snippets in this node and its children. The walking -function is called once for each snippet of JS and is passed that snippet and -the its original associated source's line/column location. - -* `fn`: The traversal function. - -#### SourceNode.prototype.walkSourceContents(fn) - -Walk over the tree of SourceNodes. The walking function is called for each -source file content and is passed the filename and source content. - -* `fn`: The traversal function. - -#### SourceNode.prototype.join(sep) - -Like `Array.prototype.join` except for SourceNodes. Inserts the separator -between each of this source node's children. - -* `sep`: The separator. - -#### SourceNode.prototype.replaceRight(pattern, replacement) - -Call `String.prototype.replace` on the very right-most source snippet. Useful -for trimming whitespace from the end of a source node, etc. - -* `pattern`: The pattern to replace. - -* `replacement`: The thing to replace the pattern with. - -#### SourceNode.prototype.toString() - -Return the string representation of this source node. Walks over the tree and -concatenates all the various snippets together to one string. - -### SourceNode.prototype.toStringWithSourceMap(startOfSourceMap) - -Returns the string representation of this tree of source nodes, plus a -SourceMapGenerator which contains all the mappings between the generated and -original sources. - -The arguments are the same as those to `new SourceMapGenerator`. - -## Tests - -[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map) - -Install NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`. - -To add new tests, create a new file named `test/test-.js` -and export your test functions with names that start with "test", for example - - exports["test doing the foo bar"] = function (assert, util) { - ... - }; - -The new test will be located automatically when you run the suite. - -The `util` argument is the test utility module located at `test/source-map/util`. - -The `assert` argument is a cut down version of node's assert module. You have -access to the following assertion functions: - -* `doesNotThrow` - -* `equal` - -* `ok` - -* `strictEqual` - -* `throws` - -(The reason for the restricted set of test functions is because we need the -tests to run inside Firefox's test suite as well and so the assert module is -shimmed in that environment. See `build/assert-shim.js`.) - -[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit -[feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap -[Dryice]: https://github.com/mozilla/dryice diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/assert-shim.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/assert-shim.js deleted file mode 100644 index daa1a623c..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/assert-shim.js +++ /dev/null @@ -1,56 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -define('test/source-map/assert', ['exports'], function (exports) { - - let do_throw = function (msg) { - throw new Error(msg); - }; - - exports.init = function (throw_fn) { - do_throw = throw_fn; - }; - - exports.doesNotThrow = function (fn) { - try { - fn(); - } - catch (e) { - do_throw(e.message); - } - }; - - exports.equal = function (actual, expected, msg) { - msg = msg || String(actual) + ' != ' + String(expected); - if (actual != expected) { - do_throw(msg); - } - }; - - exports.ok = function (val, msg) { - msg = msg || String(val) + ' is falsey'; - if (!Boolean(val)) { - do_throw(msg); - } - }; - - exports.strictEqual = function (actual, expected, msg) { - msg = msg || String(actual) + ' !== ' + String(expected); - if (actual !== expected) { - do_throw(msg); - } - }; - - exports.throws = function (fn) { - try { - fn(); - do_throw('Expected an error to be thrown, but it wasn\'t.'); - } - catch (e) { - } - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/mini-require.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/mini-require.js deleted file mode 100644 index 0daf45377..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/mini-require.js +++ /dev/null @@ -1,152 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -/** - * Define a module along with a payload. - * @param {string} moduleName Name for the payload - * @param {ignored} deps Ignored. For compatibility with CommonJS AMD Spec - * @param {function} payload Function with (require, exports, module) params - */ -function define(moduleName, deps, payload) { - if (typeof moduleName != "string") { - throw new TypeError('Expected string, got: ' + moduleName); - } - - if (arguments.length == 2) { - payload = deps; - } - - if (moduleName in define.modules) { - throw new Error("Module already defined: " + moduleName); - } - define.modules[moduleName] = payload; -}; - -/** - * The global store of un-instantiated modules - */ -define.modules = {}; - - -/** - * We invoke require() in the context of a Domain so we can have multiple - * sets of modules running separate from each other. - * This contrasts with JSMs which are singletons, Domains allows us to - * optionally load a CommonJS module twice with separate data each time. - * Perhaps you want 2 command lines with a different set of commands in each, - * for example. - */ -function Domain() { - this.modules = {}; - this._currentModule = null; -} - -(function () { - - /** - * Lookup module names and resolve them by calling the definition function if - * needed. - * There are 2 ways to call this, either with an array of dependencies and a - * callback to call when the dependencies are found (which can happen - * asynchronously in an in-page context) or with a single string an no callback - * where the dependency is resolved synchronously and returned. - * The API is designed to be compatible with the CommonJS AMD spec and - * RequireJS. - * @param {string[]|string} deps A name, or names for the payload - * @param {function|undefined} callback Function to call when the dependencies - * are resolved - * @return {undefined|object} The module required or undefined for - * array/callback method - */ - Domain.prototype.require = function(deps, callback) { - if (Array.isArray(deps)) { - var params = deps.map(function(dep) { - return this.lookup(dep); - }, this); - if (callback) { - callback.apply(null, params); - } - return undefined; - } - else { - return this.lookup(deps); - } - }; - - function normalize(path) { - var bits = path.split('/'); - var i = 1; - while (i < bits.length) { - if (bits[i] === '..') { - bits.splice(i-1, 1); - } else if (bits[i] === '.') { - bits.splice(i, 1); - } else { - i++; - } - } - return bits.join('/'); - } - - function join(a, b) { - a = a.trim(); - b = b.trim(); - if (/^\//.test(b)) { - return b; - } else { - return a.replace(/\/*$/, '/') + b; - } - } - - function dirname(path) { - var bits = path.split('/'); - bits.pop(); - return bits.join('/'); - } - - /** - * Lookup module names and resolve them by calling the definition function if - * needed. - * @param {string} moduleName A name for the payload to lookup - * @return {object} The module specified by aModuleName or null if not found. - */ - Domain.prototype.lookup = function(moduleName) { - if (/^\./.test(moduleName)) { - moduleName = normalize(join(dirname(this._currentModule), moduleName)); - } - - if (moduleName in this.modules) { - var module = this.modules[moduleName]; - return module; - } - - if (!(moduleName in define.modules)) { - throw new Error("Module not defined: " + moduleName); - } - - var module = define.modules[moduleName]; - - if (typeof module == "function") { - var exports = {}; - var previousModule = this._currentModule; - this._currentModule = moduleName; - module(this.require.bind(this), exports, { id: moduleName, uri: "" }); - this._currentModule = previousModule; - module = exports; - } - - // cache the resulting module object for next time - this.modules[moduleName] = module; - - return module; - }; - -}()); - -define.Domain = Domain; -define.globalDomain = new Domain(); -var require = define.globalDomain.require.bind(define.globalDomain); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/prefix-source-map.jsm b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/prefix-source-map.jsm deleted file mode 100644 index ee2539d81..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/prefix-source-map.jsm +++ /dev/null @@ -1,20 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -/* - * WARNING! - * - * Do not edit this file directly, it is built from the sources at - * https://github.com/mozilla/source-map/ - */ - -/////////////////////////////////////////////////////////////////////////////// - - -this.EXPORTED_SYMBOLS = [ "SourceMapConsumer", "SourceMapGenerator", "SourceNode" ]; - -Components.utils.import('resource://gre/modules/devtools/Require.jsm'); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/prefix-utils.jsm b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/prefix-utils.jsm deleted file mode 100644 index 80341d452..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/prefix-utils.jsm +++ /dev/null @@ -1,18 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ - -/* - * WARNING! - * - * Do not edit this file directly, it is built from the sources at - * https://github.com/mozilla/source-map/ - */ - -Components.utils.import('resource://gre/modules/devtools/Require.jsm'); -Components.utils.import('resource://gre/modules/devtools/SourceMap.jsm'); - -this.EXPORTED_SYMBOLS = [ "define", "runSourceMapTests" ]; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-browser.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-browser.js deleted file mode 100644 index fb29ff5fd..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-browser.js +++ /dev/null @@ -1,8 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/////////////////////////////////////////////////////////////////////////////// - -this.sourceMap = { - SourceMapConsumer: require('source-map/source-map-consumer').SourceMapConsumer, - SourceMapGenerator: require('source-map/source-map-generator').SourceMapGenerator, - SourceNode: require('source-map/source-node').SourceNode -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-source-map.jsm b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-source-map.jsm deleted file mode 100644 index cf3c2d8d3..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-source-map.jsm +++ /dev/null @@ -1,6 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/////////////////////////////////////////////////////////////////////////////// - -this.SourceMapConsumer = require('source-map/source-map-consumer').SourceMapConsumer; -this.SourceMapGenerator = require('source-map/source-map-generator').SourceMapGenerator; -this.SourceNode = require('source-map/source-node').SourceNode; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-utils.jsm b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-utils.jsm deleted file mode 100644 index b31b84cb6..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/suffix-utils.jsm +++ /dev/null @@ -1,21 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -function runSourceMapTests(modName, do_throw) { - let mod = require(modName); - let assert = require('test/source-map/assert'); - let util = require('test/source-map/util'); - - assert.init(do_throw); - - for (let k in mod) { - if (/^test/.test(k)) { - mod[k](assert, util); - } - } - -} -this.runSourceMapTests = runSourceMapTests; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/test-prefix.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/test-prefix.js deleted file mode 100644 index 1b13f300e..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/test-prefix.js +++ /dev/null @@ -1,8 +0,0 @@ -/* - * WARNING! - * - * Do not edit this file directly, it is built from the sources at - * https://github.com/mozilla/source-map/ - */ - -Components.utils.import('resource://test/Utils.jsm'); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/test-suffix.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/test-suffix.js deleted file mode 100644 index bec2de3f2..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/build/test-suffix.js +++ /dev/null @@ -1,3 +0,0 @@ -function run_test() { - runSourceMapTests('{THIS_MODULE}', do_throw); -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map.js deleted file mode 100644 index 121ad2416..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map.js +++ /dev/null @@ -1,8 +0,0 @@ -/* - * Copyright 2009-2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE.txt or: - * http://opensource.org/licenses/BSD-3-Clause - */ -exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator; -exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer; -exports.SourceNode = require('./source-map/source-node').SourceNode; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/array-set.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/array-set.js deleted file mode 100644 index 40f9a18b1..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/array-set.js +++ /dev/null @@ -1,97 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var util = require('./util'); - - /** - * A data structure which is a combination of an array and a set. Adding a new - * member is O(1), testing for membership is O(1), and finding the index of an - * element is O(1). Removing elements from the set is not supported. Only - * strings are supported for membership. - */ - function ArraySet() { - this._array = []; - this._set = {}; - } - - /** - * Static method for creating ArraySet instances from an existing array. - */ - ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { - var set = new ArraySet(); - for (var i = 0, len = aArray.length; i < len; i++) { - set.add(aArray[i], aAllowDuplicates); - } - return set; - }; - - /** - * Add the given string to this set. - * - * @param String aStr - */ - ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { - var isDuplicate = this.has(aStr); - var idx = this._array.length; - if (!isDuplicate || aAllowDuplicates) { - this._array.push(aStr); - } - if (!isDuplicate) { - this._set[util.toSetString(aStr)] = idx; - } - }; - - /** - * Is the given string a member of this set? - * - * @param String aStr - */ - ArraySet.prototype.has = function ArraySet_has(aStr) { - return Object.prototype.hasOwnProperty.call(this._set, - util.toSetString(aStr)); - }; - - /** - * What is the index of the given string in the array? - * - * @param String aStr - */ - ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { - if (this.has(aStr)) { - return this._set[util.toSetString(aStr)]; - } - throw new Error('"' + aStr + '" is not in the set.'); - }; - - /** - * What is the element at the given index? - * - * @param Number aIdx - */ - ArraySet.prototype.at = function ArraySet_at(aIdx) { - if (aIdx >= 0 && aIdx < this._array.length) { - return this._array[aIdx]; - } - throw new Error('No element indexed by ' + aIdx); - }; - - /** - * Returns the array representation of this set (which has the proper indices - * indicated by indexOf). Note that this is a copy of the internal array used - * for storing the members so that no one can mess with internal state. - */ - ArraySet.prototype.toArray = function ArraySet_toArray() { - return this._array.slice(); - }; - - exports.ArraySet = ArraySet; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64-vlq.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64-vlq.js deleted file mode 100644 index 1b67bb375..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64-vlq.js +++ /dev/null @@ -1,144 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - * - * Based on the Base 64 VLQ implementation in Closure Compiler: - * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java - * - * Copyright 2011 The Closure Compiler Authors. All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are - * met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * * Neither the name of Google Inc. nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var base64 = require('./base64'); - - // A single base 64 digit can contain 6 bits of data. For the base 64 variable - // length quantities we use in the source map spec, the first bit is the sign, - // the next four bits are the actual value, and the 6th bit is the - // continuation bit. The continuation bit tells us whether there are more - // digits in this value following this digit. - // - // Continuation - // | Sign - // | | - // V V - // 101011 - - var VLQ_BASE_SHIFT = 5; - - // binary: 100000 - var VLQ_BASE = 1 << VLQ_BASE_SHIFT; - - // binary: 011111 - var VLQ_BASE_MASK = VLQ_BASE - 1; - - // binary: 100000 - var VLQ_CONTINUATION_BIT = VLQ_BASE; - - /** - * Converts from a two-complement value to a value where the sign bit is - * is placed in the least significant bit. For example, as decimals: - * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) - * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) - */ - function toVLQSigned(aValue) { - return aValue < 0 - ? ((-aValue) << 1) + 1 - : (aValue << 1) + 0; - } - - /** - * Converts to a two-complement value from a value where the sign bit is - * is placed in the least significant bit. For example, as decimals: - * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 - * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 - */ - function fromVLQSigned(aValue) { - var isNegative = (aValue & 1) === 1; - var shifted = aValue >> 1; - return isNegative - ? -shifted - : shifted; - } - - /** - * Returns the base 64 VLQ encoded value. - */ - exports.encode = function base64VLQ_encode(aValue) { - var encoded = ""; - var digit; - - var vlq = toVLQSigned(aValue); - - do { - digit = vlq & VLQ_BASE_MASK; - vlq >>>= VLQ_BASE_SHIFT; - if (vlq > 0) { - // There are still more digits in this value, so we must make sure the - // continuation bit is marked. - digit |= VLQ_CONTINUATION_BIT; - } - encoded += base64.encode(digit); - } while (vlq > 0); - - return encoded; - }; - - /** - * Decodes the next base 64 VLQ value from the given string and returns the - * value and the rest of the string. - */ - exports.decode = function base64VLQ_decode(aStr) { - var i = 0; - var strLen = aStr.length; - var result = 0; - var shift = 0; - var continuation, digit; - - do { - if (i >= strLen) { - throw new Error("Expected more digits in base 64 VLQ value."); - } - digit = base64.decode(aStr.charAt(i++)); - continuation = !!(digit & VLQ_CONTINUATION_BIT); - digit &= VLQ_BASE_MASK; - result = result + (digit << shift); - shift += VLQ_BASE_SHIFT; - } while (continuation); - - return { - value: fromVLQSigned(result), - rest: aStr.slice(i) - }; - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64.js deleted file mode 100644 index 863cc4650..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/base64.js +++ /dev/null @@ -1,42 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var charToIntMap = {}; - var intToCharMap = {}; - - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - .split('') - .forEach(function (ch, index) { - charToIntMap[ch] = index; - intToCharMap[index] = ch; - }); - - /** - * Encode an integer in the range of 0 to 63 to a single base 64 digit. - */ - exports.encode = function base64_encode(aNumber) { - if (aNumber in intToCharMap) { - return intToCharMap[aNumber]; - } - throw new TypeError("Must be between 0 and 63: " + aNumber); - }; - - /** - * Decode a single base 64 digit to an integer. - */ - exports.decode = function base64_decode(aChar) { - if (aChar in charToIntMap) { - return charToIntMap[aChar]; - } - throw new TypeError("Not a valid base 64 digit: " + aChar); - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/binary-search.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/binary-search.js deleted file mode 100644 index ff347c68b..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/binary-search.js +++ /dev/null @@ -1,81 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - /** - * Recursive implementation of binary search. - * - * @param aLow Indices here and lower do not contain the needle. - * @param aHigh Indices here and higher do not contain the needle. - * @param aNeedle The element being searched for. - * @param aHaystack The non-empty array being searched. - * @param aCompare Function which takes two elements and returns -1, 0, or 1. - */ - function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { - // This function terminates when one of the following is true: - // - // 1. We find the exact element we are looking for. - // - // 2. We did not find the exact element, but we can return the next - // closest element that is less than that element. - // - // 3. We did not find the exact element, and there is no next-closest - // element which is less than the one we are searching for, so we - // return null. - var mid = Math.floor((aHigh - aLow) / 2) + aLow; - var cmp = aCompare(aNeedle, aHaystack[mid], true); - if (cmp === 0) { - // Found the element we are looking for. - return aHaystack[mid]; - } - else if (cmp > 0) { - // aHaystack[mid] is greater than our needle. - if (aHigh - mid > 1) { - // The element is in the upper half. - return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); - } - // We did not find an exact match, return the next closest one - // (termination case 2). - return aHaystack[mid]; - } - else { - // aHaystack[mid] is less than our needle. - if (mid - aLow > 1) { - // The element is in the lower half. - return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); - } - // The exact needle element was not found in this haystack. Determine if - // we are in termination case (2) or (3) and return the appropriate thing. - return aLow < 0 - ? null - : aHaystack[aLow]; - } - } - - /** - * This is an implementation of binary search which will always try and return - * the next lowest value checked if there is no exact hit. This is because - * mappings between original and generated line/col pairs are single points, - * and there is an implicit region between each of them, so a miss just means - * that you aren't on the very start of a region. - * - * @param aNeedle The element you are looking for. - * @param aHaystack The array that is being searched. - * @param aCompare A function which takes the needle and an element in the - * array and returns -1, 0, or 1 depending on whether the needle is less - * than, equal to, or greater than the element, respectively. - */ - exports.search = function search(aNeedle, aHaystack, aCompare) { - return aHaystack.length > 0 - ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) - : null; - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-consumer.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-consumer.js deleted file mode 100644 index a3b9dc086..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-consumer.js +++ /dev/null @@ -1,477 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var util = require('./util'); - var binarySearch = require('./binary-search'); - var ArraySet = require('./array-set').ArraySet; - var base64VLQ = require('./base64-vlq'); - - /** - * A SourceMapConsumer instance represents a parsed source map which we can - * query for information about the original file positions by giving it a file - * position in the generated source. - * - * The only parameter is the raw source map (either as a JSON string, or - * already parsed to an object). According to the spec, source maps have the - * following attributes: - * - * - version: Which version of the source map spec this map is following. - * - sources: An array of URLs to the original source files. - * - names: An array of identifiers which can be referrenced by individual mappings. - * - sourceRoot: Optional. The URL root from which all sources are relative. - * - sourcesContent: Optional. An array of contents of the original source files. - * - mappings: A string of base64 VLQs which contain the actual mappings. - * - file: The generated file this source map is associated with. - * - * Here is an example source map, taken from the source map spec[0]: - * - * { - * version : 3, - * file: "out.js", - * sourceRoot : "", - * sources: ["foo.js", "bar.js"], - * names: ["src", "maps", "are", "fun"], - * mappings: "AA,AB;;ABCDE;" - * } - * - * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# - */ - function SourceMapConsumer(aSourceMap) { - var sourceMap = aSourceMap; - if (typeof aSourceMap === 'string') { - sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); - } - - var version = util.getArg(sourceMap, 'version'); - var sources = util.getArg(sourceMap, 'sources'); - // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which - // requires the array) to play nice here. - var names = util.getArg(sourceMap, 'names', []); - var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); - var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); - var mappings = util.getArg(sourceMap, 'mappings'); - var file = util.getArg(sourceMap, 'file', null); - - // Once again, Sass deviates from the spec and supplies the version as a - // string rather than a number, so we use loose equality checking here. - if (version != this._version) { - throw new Error('Unsupported version: ' + version); - } - - // Pass `true` below to allow duplicate names and sources. While source maps - // are intended to be compressed and deduplicated, the TypeScript compiler - // sometimes generates source maps with duplicates in them. See Github issue - // #72 and bugzil.la/889492. - this._names = ArraySet.fromArray(names, true); - this._sources = ArraySet.fromArray(sources, true); - - this.sourceRoot = sourceRoot; - this.sourcesContent = sourcesContent; - this._mappings = mappings; - this.file = file; - } - - /** - * Create a SourceMapConsumer from a SourceMapGenerator. - * - * @param SourceMapGenerator aSourceMap - * The source map that will be consumed. - * @returns SourceMapConsumer - */ - SourceMapConsumer.fromSourceMap = - function SourceMapConsumer_fromSourceMap(aSourceMap) { - var smc = Object.create(SourceMapConsumer.prototype); - - smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); - smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); - smc.sourceRoot = aSourceMap._sourceRoot; - smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), - smc.sourceRoot); - smc.file = aSourceMap._file; - - smc.__generatedMappings = aSourceMap._mappings.slice() - .sort(util.compareByGeneratedPositions); - smc.__originalMappings = aSourceMap._mappings.slice() - .sort(util.compareByOriginalPositions); - - return smc; - }; - - /** - * The version of the source mapping spec that we are consuming. - */ - SourceMapConsumer.prototype._version = 3; - - /** - * The list of original sources. - */ - Object.defineProperty(SourceMapConsumer.prototype, 'sources', { - get: function () { - return this._sources.toArray().map(function (s) { - return this.sourceRoot ? util.join(this.sourceRoot, s) : s; - }, this); - } - }); - - // `__generatedMappings` and `__originalMappings` are arrays that hold the - // parsed mapping coordinates from the source map's "mappings" attribute. They - // are lazily instantiated, accessed via the `_generatedMappings` and - // `_originalMappings` getters respectively, and we only parse the mappings - // and create these arrays once queried for a source location. We jump through - // these hoops because there can be many thousands of mappings, and parsing - // them is expensive, so we only want to do it if we must. - // - // Each object in the arrays is of the form: - // - // { - // generatedLine: The line number in the generated code, - // generatedColumn: The column number in the generated code, - // source: The path to the original source file that generated this - // chunk of code, - // originalLine: The line number in the original source that - // corresponds to this chunk of generated code, - // originalColumn: The column number in the original source that - // corresponds to this chunk of generated code, - // name: The name of the original symbol which generated this chunk of - // code. - // } - // - // All properties except for `generatedLine` and `generatedColumn` can be - // `null`. - // - // `_generatedMappings` is ordered by the generated positions. - // - // `_originalMappings` is ordered by the original positions. - - SourceMapConsumer.prototype.__generatedMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { - get: function () { - if (!this.__generatedMappings) { - this.__generatedMappings = []; - this.__originalMappings = []; - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__generatedMappings; - } - }); - - SourceMapConsumer.prototype.__originalMappings = null; - Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { - get: function () { - if (!this.__originalMappings) { - this.__generatedMappings = []; - this.__originalMappings = []; - this._parseMappings(this._mappings, this.sourceRoot); - } - - return this.__originalMappings; - } - }); - - /** - * Parse the mappings in a string in to a data structure which we can easily - * query (the ordered arrays in the `this.__generatedMappings` and - * `this.__originalMappings` properties). - */ - SourceMapConsumer.prototype._parseMappings = - function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { - var generatedLine = 1; - var previousGeneratedColumn = 0; - var previousOriginalLine = 0; - var previousOriginalColumn = 0; - var previousSource = 0; - var previousName = 0; - var mappingSeparator = /^[,;]/; - var str = aStr; - var mapping; - var temp; - - while (str.length > 0) { - if (str.charAt(0) === ';') { - generatedLine++; - str = str.slice(1); - previousGeneratedColumn = 0; - } - else if (str.charAt(0) === ',') { - str = str.slice(1); - } - else { - mapping = {}; - mapping.generatedLine = generatedLine; - - // Generated column. - temp = base64VLQ.decode(str); - mapping.generatedColumn = previousGeneratedColumn + temp.value; - previousGeneratedColumn = mapping.generatedColumn; - str = temp.rest; - - if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { - // Original source. - temp = base64VLQ.decode(str); - mapping.source = this._sources.at(previousSource + temp.value); - previousSource += temp.value; - str = temp.rest; - if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { - throw new Error('Found a source, but no line and column'); - } - - // Original line. - temp = base64VLQ.decode(str); - mapping.originalLine = previousOriginalLine + temp.value; - previousOriginalLine = mapping.originalLine; - // Lines are stored 0-based - mapping.originalLine += 1; - str = temp.rest; - if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { - throw new Error('Found a source and line, but no column'); - } - - // Original column. - temp = base64VLQ.decode(str); - mapping.originalColumn = previousOriginalColumn + temp.value; - previousOriginalColumn = mapping.originalColumn; - str = temp.rest; - - if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { - // Original name. - temp = base64VLQ.decode(str); - mapping.name = this._names.at(previousName + temp.value); - previousName += temp.value; - str = temp.rest; - } - } - - this.__generatedMappings.push(mapping); - if (typeof mapping.originalLine === 'number') { - this.__originalMappings.push(mapping); - } - } - } - - this.__originalMappings.sort(util.compareByOriginalPositions); - }; - - /** - * Find the mapping that best matches the hypothetical "needle" mapping that - * we are searching for in the given "haystack" of mappings. - */ - SourceMapConsumer.prototype._findMapping = - function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, - aColumnName, aComparator) { - // To return the position we are searching for, we must first find the - // mapping for the given position and then return the opposite position it - // points to. Because the mappings are sorted, we can use binary search to - // find the best mapping. - - if (aNeedle[aLineName] <= 0) { - throw new TypeError('Line must be greater than or equal to 1, got ' - + aNeedle[aLineName]); - } - if (aNeedle[aColumnName] < 0) { - throw new TypeError('Column must be greater than or equal to 0, got ' - + aNeedle[aColumnName]); - } - - return binarySearch.search(aNeedle, aMappings, aComparator); - }; - - /** - * Returns the original source, line, and column information for the generated - * source's line and column positions provided. The only argument is an object - * with the following properties: - * - * - line: The line number in the generated source. - * - column: The column number in the generated source. - * - * and an object is returned with the following properties: - * - * - source: The original source file, or null. - * - line: The line number in the original source, or null. - * - column: The column number in the original source, or null. - * - name: The original identifier, or null. - */ - SourceMapConsumer.prototype.originalPositionFor = - function SourceMapConsumer_originalPositionFor(aArgs) { - var needle = { - generatedLine: util.getArg(aArgs, 'line'), - generatedColumn: util.getArg(aArgs, 'column') - }; - - var mapping = this._findMapping(needle, - this._generatedMappings, - "generatedLine", - "generatedColumn", - util.compareByGeneratedPositions); - - if (mapping) { - var source = util.getArg(mapping, 'source', null); - if (source && this.sourceRoot) { - source = util.join(this.sourceRoot, source); - } - return { - source: source, - line: util.getArg(mapping, 'originalLine', null), - column: util.getArg(mapping, 'originalColumn', null), - name: util.getArg(mapping, 'name', null) - }; - } - - return { - source: null, - line: null, - column: null, - name: null - }; - }; - - /** - * Returns the original source content. The only argument is the url of the - * original source file. Returns null if no original source content is - * availible. - */ - SourceMapConsumer.prototype.sourceContentFor = - function SourceMapConsumer_sourceContentFor(aSource) { - if (!this.sourcesContent) { - return null; - } - - if (this.sourceRoot) { - aSource = util.relative(this.sourceRoot, aSource); - } - - if (this._sources.has(aSource)) { - return this.sourcesContent[this._sources.indexOf(aSource)]; - } - - var url; - if (this.sourceRoot - && (url = util.urlParse(this.sourceRoot))) { - // XXX: file:// URIs and absolute paths lead to unexpected behavior for - // many users. We can help them out when they expect file:// URIs to - // behave like it would if they were running a local HTTP server. See - // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. - var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); - if (url.scheme == "file" - && this._sources.has(fileUriAbsPath)) { - return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] - } - - if ((!url.path || url.path == "/") - && this._sources.has("/" + aSource)) { - return this.sourcesContent[this._sources.indexOf("/" + aSource)]; - } - } - - throw new Error('"' + aSource + '" is not in the SourceMap.'); - }; - - /** - * Returns the generated line and column information for the original source, - * line, and column positions provided. The only argument is an object with - * the following properties: - * - * - source: The filename of the original source. - * - line: The line number in the original source. - * - column: The column number in the original source. - * - * and an object is returned with the following properties: - * - * - line: The line number in the generated source, or null. - * - column: The column number in the generated source, or null. - */ - SourceMapConsumer.prototype.generatedPositionFor = - function SourceMapConsumer_generatedPositionFor(aArgs) { - var needle = { - source: util.getArg(aArgs, 'source'), - originalLine: util.getArg(aArgs, 'line'), - originalColumn: util.getArg(aArgs, 'column') - }; - - if (this.sourceRoot) { - needle.source = util.relative(this.sourceRoot, needle.source); - } - - var mapping = this._findMapping(needle, - this._originalMappings, - "originalLine", - "originalColumn", - util.compareByOriginalPositions); - - if (mapping) { - return { - line: util.getArg(mapping, 'generatedLine', null), - column: util.getArg(mapping, 'generatedColumn', null) - }; - } - - return { - line: null, - column: null - }; - }; - - SourceMapConsumer.GENERATED_ORDER = 1; - SourceMapConsumer.ORIGINAL_ORDER = 2; - - /** - * Iterate over each mapping between an original source/line/column and a - * generated line/column in this source map. - * - * @param Function aCallback - * The function that is called with each mapping. - * @param Object aContext - * Optional. If specified, this object will be the value of `this` every - * time that `aCallback` is called. - * @param aOrder - * Either `SourceMapConsumer.GENERATED_ORDER` or - * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to - * iterate over the mappings sorted by the generated file's line/column - * order or the original's source/line/column order, respectively. Defaults to - * `SourceMapConsumer.GENERATED_ORDER`. - */ - SourceMapConsumer.prototype.eachMapping = - function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { - var context = aContext || null; - var order = aOrder || SourceMapConsumer.GENERATED_ORDER; - - var mappings; - switch (order) { - case SourceMapConsumer.GENERATED_ORDER: - mappings = this._generatedMappings; - break; - case SourceMapConsumer.ORIGINAL_ORDER: - mappings = this._originalMappings; - break; - default: - throw new Error("Unknown order of iteration."); - } - - var sourceRoot = this.sourceRoot; - mappings.map(function (mapping) { - var source = mapping.source; - if (source && sourceRoot) { - source = util.join(sourceRoot, source); - } - return { - source: source, - generatedLine: mapping.generatedLine, - generatedColumn: mapping.generatedColumn, - originalLine: mapping.originalLine, - originalColumn: mapping.originalColumn, - name: mapping.name - }; - }).forEach(aCallback, context); - }; - - exports.SourceMapConsumer = SourceMapConsumer; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js deleted file mode 100644 index 48ead7ddc..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-map-generator.js +++ /dev/null @@ -1,380 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var base64VLQ = require('./base64-vlq'); - var util = require('./util'); - var ArraySet = require('./array-set').ArraySet; - - /** - * An instance of the SourceMapGenerator represents a source map which is - * being built incrementally. To create a new one, you must pass an object - * with the following properties: - * - * - file: The filename of the generated source. - * - sourceRoot: An optional root for all URLs in this source map. - */ - function SourceMapGenerator(aArgs) { - this._file = util.getArg(aArgs, 'file'); - this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); - this._sources = new ArraySet(); - this._names = new ArraySet(); - this._mappings = []; - this._sourcesContents = null; - } - - SourceMapGenerator.prototype._version = 3; - - /** - * Creates a new SourceMapGenerator based on a SourceMapConsumer - * - * @param aSourceMapConsumer The SourceMap. - */ - SourceMapGenerator.fromSourceMap = - function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { - var sourceRoot = aSourceMapConsumer.sourceRoot; - var generator = new SourceMapGenerator({ - file: aSourceMapConsumer.file, - sourceRoot: sourceRoot - }); - aSourceMapConsumer.eachMapping(function (mapping) { - var newMapping = { - generated: { - line: mapping.generatedLine, - column: mapping.generatedColumn - } - }; - - if (mapping.source) { - newMapping.source = mapping.source; - if (sourceRoot) { - newMapping.source = util.relative(sourceRoot, newMapping.source); - } - - newMapping.original = { - line: mapping.originalLine, - column: mapping.originalColumn - }; - - if (mapping.name) { - newMapping.name = mapping.name; - } - } - - generator.addMapping(newMapping); - }); - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content) { - generator.setSourceContent(sourceFile, content); - } - }); - return generator; - }; - - /** - * Add a single mapping from original source line and column to the generated - * source's line and column for this source map being created. The mapping - * object should have the following properties: - * - * - generated: An object with the generated line and column positions. - * - original: An object with the original line and column positions. - * - source: The original source file (relative to the sourceRoot). - * - name: An optional original token name for this mapping. - */ - SourceMapGenerator.prototype.addMapping = - function SourceMapGenerator_addMapping(aArgs) { - var generated = util.getArg(aArgs, 'generated'); - var original = util.getArg(aArgs, 'original', null); - var source = util.getArg(aArgs, 'source', null); - var name = util.getArg(aArgs, 'name', null); - - this._validateMapping(generated, original, source, name); - - if (source && !this._sources.has(source)) { - this._sources.add(source); - } - - if (name && !this._names.has(name)) { - this._names.add(name); - } - - this._mappings.push({ - generatedLine: generated.line, - generatedColumn: generated.column, - originalLine: original != null && original.line, - originalColumn: original != null && original.column, - source: source, - name: name - }); - }; - - /** - * Set the source content for a source file. - */ - SourceMapGenerator.prototype.setSourceContent = - function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { - var source = aSourceFile; - if (this._sourceRoot) { - source = util.relative(this._sourceRoot, source); - } - - if (aSourceContent !== null) { - // Add the source content to the _sourcesContents map. - // Create a new _sourcesContents map if the property is null. - if (!this._sourcesContents) { - this._sourcesContents = {}; - } - this._sourcesContents[util.toSetString(source)] = aSourceContent; - } else { - // Remove the source file from the _sourcesContents map. - // If the _sourcesContents map is empty, set the property to null. - delete this._sourcesContents[util.toSetString(source)]; - if (Object.keys(this._sourcesContents).length === 0) { - this._sourcesContents = null; - } - } - }; - - /** - * Applies the mappings of a sub-source-map for a specific source file to the - * source map being generated. Each mapping to the supplied source file is - * rewritten using the supplied source map. Note: The resolution for the - * resulting mappings is the minimium of this map and the supplied map. - * - * @param aSourceMapConsumer The source map to be applied. - * @param aSourceFile Optional. The filename of the source file. - * If omitted, SourceMapConsumer's file property will be used. - */ - SourceMapGenerator.prototype.applySourceMap = - function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { - // If aSourceFile is omitted, we will use the file property of the SourceMap - if (!aSourceFile) { - aSourceFile = aSourceMapConsumer.file; - } - var sourceRoot = this._sourceRoot; - // Make "aSourceFile" relative if an absolute Url is passed. - if (sourceRoot) { - aSourceFile = util.relative(sourceRoot, aSourceFile); - } - // Applying the SourceMap can add and remove items from the sources and - // the names array. - var newSources = new ArraySet(); - var newNames = new ArraySet(); - - // Find mappings for the "aSourceFile" - this._mappings.forEach(function (mapping) { - if (mapping.source === aSourceFile && mapping.originalLine) { - // Check if it can be mapped by the source map, then update the mapping. - var original = aSourceMapConsumer.originalPositionFor({ - line: mapping.originalLine, - column: mapping.originalColumn - }); - if (original.source !== null) { - // Copy mapping - if (sourceRoot) { - mapping.source = util.relative(sourceRoot, original.source); - } else { - mapping.source = original.source; - } - mapping.originalLine = original.line; - mapping.originalColumn = original.column; - if (original.name !== null && mapping.name !== null) { - // Only use the identifier name if it's an identifier - // in both SourceMaps - mapping.name = original.name; - } - } - } - - var source = mapping.source; - if (source && !newSources.has(source)) { - newSources.add(source); - } - - var name = mapping.name; - if (name && !newNames.has(name)) { - newNames.add(name); - } - - }, this); - this._sources = newSources; - this._names = newNames; - - // Copy sourcesContents of applied map. - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content) { - if (sourceRoot) { - sourceFile = util.relative(sourceRoot, sourceFile); - } - this.setSourceContent(sourceFile, content); - } - }, this); - }; - - /** - * A mapping can have one of the three levels of data: - * - * 1. Just the generated position. - * 2. The Generated position, original position, and original source. - * 3. Generated and original position, original source, as well as a name - * token. - * - * To maintain consistency, we validate that any new mapping being added falls - * in to one of these categories. - */ - SourceMapGenerator.prototype._validateMapping = - function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, - aName) { - if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aGenerated.line > 0 && aGenerated.column >= 0 - && !aOriginal && !aSource && !aName) { - // Case 1. - return; - } - else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated - && aOriginal && 'line' in aOriginal && 'column' in aOriginal - && aGenerated.line > 0 && aGenerated.column >= 0 - && aOriginal.line > 0 && aOriginal.column >= 0 - && aSource) { - // Cases 2 and 3. - return; - } - else { - throw new Error('Invalid mapping: ' + JSON.stringify({ - generated: aGenerated, - source: aSource, - orginal: aOriginal, - name: aName - })); - } - }; - - /** - * Serialize the accumulated mappings in to the stream of base 64 VLQs - * specified by the source map format. - */ - SourceMapGenerator.prototype._serializeMappings = - function SourceMapGenerator_serializeMappings() { - var previousGeneratedColumn = 0; - var previousGeneratedLine = 1; - var previousOriginalColumn = 0; - var previousOriginalLine = 0; - var previousName = 0; - var previousSource = 0; - var result = ''; - var mapping; - - // The mappings must be guaranteed to be in sorted order before we start - // serializing them or else the generated line numbers (which are defined - // via the ';' separators) will be all messed up. Note: it might be more - // performant to maintain the sorting as we insert them, rather than as we - // serialize them, but the big O is the same either way. - this._mappings.sort(util.compareByGeneratedPositions); - - for (var i = 0, len = this._mappings.length; i < len; i++) { - mapping = this._mappings[i]; - - if (mapping.generatedLine !== previousGeneratedLine) { - previousGeneratedColumn = 0; - while (mapping.generatedLine !== previousGeneratedLine) { - result += ';'; - previousGeneratedLine++; - } - } - else { - if (i > 0) { - if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { - continue; - } - result += ','; - } - } - - result += base64VLQ.encode(mapping.generatedColumn - - previousGeneratedColumn); - previousGeneratedColumn = mapping.generatedColumn; - - if (mapping.source) { - result += base64VLQ.encode(this._sources.indexOf(mapping.source) - - previousSource); - previousSource = this._sources.indexOf(mapping.source); - - // lines are stored 0-based in SourceMap spec version 3 - result += base64VLQ.encode(mapping.originalLine - 1 - - previousOriginalLine); - previousOriginalLine = mapping.originalLine - 1; - - result += base64VLQ.encode(mapping.originalColumn - - previousOriginalColumn); - previousOriginalColumn = mapping.originalColumn; - - if (mapping.name) { - result += base64VLQ.encode(this._names.indexOf(mapping.name) - - previousName); - previousName = this._names.indexOf(mapping.name); - } - } - } - - return result; - }; - - SourceMapGenerator.prototype._generateSourcesContent = - function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { - return aSources.map(function (source) { - if (!this._sourcesContents) { - return null; - } - if (aSourceRoot) { - source = util.relative(aSourceRoot, source); - } - var key = util.toSetString(source); - return Object.prototype.hasOwnProperty.call(this._sourcesContents, - key) - ? this._sourcesContents[key] - : null; - }, this); - }; - - /** - * Externalize the source map. - */ - SourceMapGenerator.prototype.toJSON = - function SourceMapGenerator_toJSON() { - var map = { - version: this._version, - file: this._file, - sources: this._sources.toArray(), - names: this._names.toArray(), - mappings: this._serializeMappings() - }; - if (this._sourceRoot) { - map.sourceRoot = this._sourceRoot; - } - if (this._sourcesContents) { - map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); - } - - return map; - }; - - /** - * Render the source map being generated to a string. - */ - SourceMapGenerator.prototype.toString = - function SourceMapGenerator_toString() { - return JSON.stringify(this); - }; - - exports.SourceMapGenerator = SourceMapGenerator; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-node.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-node.js deleted file mode 100644 index 626cb6574..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/source-node.js +++ /dev/null @@ -1,371 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; - var util = require('./util'); - - /** - * SourceNodes provide a way to abstract over interpolating/concatenating - * snippets of generated JavaScript source code while maintaining the line and - * column information associated with the original source code. - * - * @param aLine The original line number. - * @param aColumn The original column number. - * @param aSource The original source's filename. - * @param aChunks Optional. An array of strings which are snippets of - * generated JS, or other SourceNodes. - * @param aName The original identifier. - */ - function SourceNode(aLine, aColumn, aSource, aChunks, aName) { - this.children = []; - this.sourceContents = {}; - this.line = aLine === undefined ? null : aLine; - this.column = aColumn === undefined ? null : aColumn; - this.source = aSource === undefined ? null : aSource; - this.name = aName === undefined ? null : aName; - if (aChunks != null) this.add(aChunks); - } - - /** - * Creates a SourceNode from generated code and a SourceMapConsumer. - * - * @param aGeneratedCode The generated code - * @param aSourceMapConsumer The SourceMap for the generated code - */ - SourceNode.fromStringWithSourceMap = - function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { - // The SourceNode we want to fill with the generated code - // and the SourceMap - var node = new SourceNode(); - - // The generated code - // Processed fragments are removed from this array. - var remainingLines = aGeneratedCode.split('\n'); - - // We need to remember the position of "remainingLines" - var lastGeneratedLine = 1, lastGeneratedColumn = 0; - - // The generate SourceNodes we need a code range. - // To extract it current and last mapping is used. - // Here we store the last mapping. - var lastMapping = null; - - aSourceMapConsumer.eachMapping(function (mapping) { - if (lastMapping === null) { - // We add the generated code until the first mapping - // to the SourceNode without any mapping. - // Each line is added as separate string. - while (lastGeneratedLine < mapping.generatedLine) { - node.add(remainingLines.shift() + "\n"); - lastGeneratedLine++; - } - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[0]; - node.add(nextLine.substr(0, mapping.generatedColumn)); - remainingLines[0] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - } else { - // We add the code from "lastMapping" to "mapping": - // First check if there is a new line in between. - if (lastGeneratedLine < mapping.generatedLine) { - var code = ""; - // Associate full lines with "lastMapping" - do { - code += remainingLines.shift() + "\n"; - lastGeneratedLine++; - lastGeneratedColumn = 0; - } while (lastGeneratedLine < mapping.generatedLine); - // When we reached the correct line, we add code until we - // reach the correct column too. - if (lastGeneratedColumn < mapping.generatedColumn) { - var nextLine = remainingLines[0]; - code += nextLine.substr(0, mapping.generatedColumn); - remainingLines[0] = nextLine.substr(mapping.generatedColumn); - lastGeneratedColumn = mapping.generatedColumn; - } - // Create the SourceNode. - addMappingWithCode(lastMapping, code); - } else { - // There is no new line in between. - // Associate the code between "lastGeneratedColumn" and - // "mapping.generatedColumn" with "lastMapping" - var nextLine = remainingLines[0]; - var code = nextLine.substr(0, mapping.generatedColumn - - lastGeneratedColumn); - remainingLines[0] = nextLine.substr(mapping.generatedColumn - - lastGeneratedColumn); - lastGeneratedColumn = mapping.generatedColumn; - addMappingWithCode(lastMapping, code); - } - } - lastMapping = mapping; - }, this); - // We have processed all mappings. - // Associate the remaining code in the current line with "lastMapping" - // and add the remaining lines without any mapping - addMappingWithCode(lastMapping, remainingLines.join("\n")); - - // Copy sourcesContent into SourceNode - aSourceMapConsumer.sources.forEach(function (sourceFile) { - var content = aSourceMapConsumer.sourceContentFor(sourceFile); - if (content) { - node.setSourceContent(sourceFile, content); - } - }); - - return node; - - function addMappingWithCode(mapping, code) { - if (mapping === null || mapping.source === undefined) { - node.add(code); - } else { - node.add(new SourceNode(mapping.originalLine, - mapping.originalColumn, - mapping.source, - code, - mapping.name)); - } - } - }; - - /** - * Add a chunk of generated JS to this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode.prototype.add = function SourceNode_add(aChunk) { - if (Array.isArray(aChunk)) { - aChunk.forEach(function (chunk) { - this.add(chunk); - }, this); - } - else if (aChunk instanceof SourceNode || typeof aChunk === "string") { - if (aChunk) { - this.children.push(aChunk); - } - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Add a chunk of generated JS to the beginning of this source node. - * - * @param aChunk A string snippet of generated JS code, another instance of - * SourceNode, or an array where each member is one of those things. - */ - SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { - if (Array.isArray(aChunk)) { - for (var i = aChunk.length-1; i >= 0; i--) { - this.prepend(aChunk[i]); - } - } - else if (aChunk instanceof SourceNode || typeof aChunk === "string") { - this.children.unshift(aChunk); - } - else { - throw new TypeError( - "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk - ); - } - return this; - }; - - /** - * Walk over the tree of JS snippets in this node and its children. The - * walking function is called once for each snippet of JS and is passed that - * snippet and the its original associated source's line/column location. - * - * @param aFn The traversal function. - */ - SourceNode.prototype.walk = function SourceNode_walk(aFn) { - var chunk; - for (var i = 0, len = this.children.length; i < len; i++) { - chunk = this.children[i]; - if (chunk instanceof SourceNode) { - chunk.walk(aFn); - } - else { - if (chunk !== '') { - aFn(chunk, { source: this.source, - line: this.line, - column: this.column, - name: this.name }); - } - } - } - }; - - /** - * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between - * each of `this.children`. - * - * @param aSep The separator. - */ - SourceNode.prototype.join = function SourceNode_join(aSep) { - var newChildren; - var i; - var len = this.children.length; - if (len > 0) { - newChildren = []; - for (i = 0; i < len-1; i++) { - newChildren.push(this.children[i]); - newChildren.push(aSep); - } - newChildren.push(this.children[i]); - this.children = newChildren; - } - return this; - }; - - /** - * Call String.prototype.replace on the very right-most source snippet. Useful - * for trimming whitespace from the end of a source node, etc. - * - * @param aPattern The pattern to replace. - * @param aReplacement The thing to replace the pattern with. - */ - SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { - var lastChild = this.children[this.children.length - 1]; - if (lastChild instanceof SourceNode) { - lastChild.replaceRight(aPattern, aReplacement); - } - else if (typeof lastChild === 'string') { - this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); - } - else { - this.children.push(''.replace(aPattern, aReplacement)); - } - return this; - }; - - /** - * Set the source content for a source file. This will be added to the SourceMapGenerator - * in the sourcesContent field. - * - * @param aSourceFile The filename of the source file - * @param aSourceContent The content of the source file - */ - SourceNode.prototype.setSourceContent = - function SourceNode_setSourceContent(aSourceFile, aSourceContent) { - this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; - }; - - /** - * Walk over the tree of SourceNodes. The walking function is called for each - * source file content and is passed the filename and source content. - * - * @param aFn The traversal function. - */ - SourceNode.prototype.walkSourceContents = - function SourceNode_walkSourceContents(aFn) { - for (var i = 0, len = this.children.length; i < len; i++) { - if (this.children[i] instanceof SourceNode) { - this.children[i].walkSourceContents(aFn); - } - } - - var sources = Object.keys(this.sourceContents); - for (var i = 0, len = sources.length; i < len; i++) { - aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); - } - }; - - /** - * Return the string representation of this source node. Walks over the tree - * and concatenates all the various snippets together to one string. - */ - SourceNode.prototype.toString = function SourceNode_toString() { - var str = ""; - this.walk(function (chunk) { - str += chunk; - }); - return str; - }; - - /** - * Returns the string representation of this source node along with a source - * map. - */ - SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { - var generated = { - code: "", - line: 1, - column: 0 - }; - var map = new SourceMapGenerator(aArgs); - var sourceMappingActive = false; - var lastOriginalSource = null; - var lastOriginalLine = null; - var lastOriginalColumn = null; - var lastOriginalName = null; - this.walk(function (chunk, original) { - generated.code += chunk; - if (original.source !== null - && original.line !== null - && original.column !== null) { - if(lastOriginalSource !== original.source - || lastOriginalLine !== original.line - || lastOriginalColumn !== original.column - || lastOriginalName !== original.name) { - map.addMapping({ - source: original.source, - original: { - line: original.line, - column: original.column - }, - generated: { - line: generated.line, - column: generated.column - }, - name: original.name - }); - } - lastOriginalSource = original.source; - lastOriginalLine = original.line; - lastOriginalColumn = original.column; - lastOriginalName = original.name; - sourceMappingActive = true; - } else if (sourceMappingActive) { - map.addMapping({ - generated: { - line: generated.line, - column: generated.column - } - }); - lastOriginalSource = null; - sourceMappingActive = false; - } - chunk.split('').forEach(function (ch) { - if (ch === '\n') { - generated.line++; - generated.column = 0; - } else { - generated.column++; - } - }); - }); - this.walkSourceContents(function (sourceFile, sourceContent) { - map.setSourceContent(sourceFile, sourceContent); - }); - - return { code: generated.code, map: map }; - }; - - exports.SourceNode = SourceNode; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/util.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/util.js deleted file mode 100644 index 87946d3f7..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/lib/source-map/util.js +++ /dev/null @@ -1,205 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - /** - * This is a helper function for getting values from parameter/options - * objects. - * - * @param args The object we are extracting values from - * @param name The name of the property we are getting. - * @param defaultValue An optional value to return if the property is missing - * from the object. If this is not specified and the property is missing, an - * error will be thrown. - */ - function getArg(aArgs, aName, aDefaultValue) { - if (aName in aArgs) { - return aArgs[aName]; - } else if (arguments.length === 3) { - return aDefaultValue; - } else { - throw new Error('"' + aName + '" is a required argument.'); - } - } - exports.getArg = getArg; - - var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/; - var dataUrlRegexp = /^data:.+\,.+/; - - function urlParse(aUrl) { - var match = aUrl.match(urlRegexp); - if (!match) { - return null; - } - return { - scheme: match[1], - auth: match[3], - host: match[4], - port: match[6], - path: match[7] - }; - } - exports.urlParse = urlParse; - - function urlGenerate(aParsedUrl) { - var url = aParsedUrl.scheme + "://"; - if (aParsedUrl.auth) { - url += aParsedUrl.auth + "@" - } - if (aParsedUrl.host) { - url += aParsedUrl.host; - } - if (aParsedUrl.port) { - url += ":" + aParsedUrl.port - } - if (aParsedUrl.path) { - url += aParsedUrl.path; - } - return url; - } - exports.urlGenerate = urlGenerate; - - function join(aRoot, aPath) { - var url; - - if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { - return aPath; - } - - if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { - url.path = aPath; - return urlGenerate(url); - } - - return aRoot.replace(/\/$/, '') + '/' + aPath; - } - exports.join = join; - - /** - * Because behavior goes wacky when you set `__proto__` on objects, we - * have to prefix all the strings in our set with an arbitrary character. - * - * See https://github.com/mozilla/source-map/pull/31 and - * https://github.com/mozilla/source-map/issues/30 - * - * @param String aStr - */ - function toSetString(aStr) { - return '$' + aStr; - } - exports.toSetString = toSetString; - - function fromSetString(aStr) { - return aStr.substr(1); - } - exports.fromSetString = fromSetString; - - function relative(aRoot, aPath) { - aRoot = aRoot.replace(/\/$/, ''); - - var url = urlParse(aRoot); - if (aPath.charAt(0) == "/" && url && url.path == "/") { - return aPath.slice(1); - } - - return aPath.indexOf(aRoot + '/') === 0 - ? aPath.substr(aRoot.length + 1) - : aPath; - } - exports.relative = relative; - - function strcmp(aStr1, aStr2) { - var s1 = aStr1 || ""; - var s2 = aStr2 || ""; - return (s1 > s2) - (s1 < s2); - } - - /** - * Comparator between two mappings where the original positions are compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same original source/line/column, but different generated - * line and column the same. Useful when searching for a mapping with a - * stubbed out mapping. - */ - function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { - var cmp; - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp || onlyCompareOriginal) { - return cmp; - } - - cmp = strcmp(mappingA.name, mappingB.name); - if (cmp) { - return cmp; - } - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp) { - return cmp; - } - - return mappingA.generatedColumn - mappingB.generatedColumn; - }; - exports.compareByOriginalPositions = compareByOriginalPositions; - - /** - * Comparator between two mappings where the generated positions are - * compared. - * - * Optionally pass in `true` as `onlyCompareGenerated` to consider two - * mappings with the same generated line and column, but different - * source/name/original line and column the same. Useful when searching for a - * mapping with a stubbed out mapping. - */ - function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { - var cmp; - - cmp = mappingA.generatedLine - mappingB.generatedLine; - if (cmp) { - return cmp; - } - - cmp = mappingA.generatedColumn - mappingB.generatedColumn; - if (cmp || onlyCompareGenerated) { - return cmp; - } - - cmp = strcmp(mappingA.source, mappingB.source); - if (cmp) { - return cmp; - } - - cmp = mappingA.originalLine - mappingB.originalLine; - if (cmp) { - return cmp; - } - - cmp = mappingA.originalColumn - mappingB.originalColumn; - if (cmp) { - return cmp; - } - - return strcmp(mappingA.name, mappingB.name); - }; - exports.compareByGeneratedPositions = compareByGeneratedPositions; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/LICENSE b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/LICENSE deleted file mode 100644 index f33d665de..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/LICENSE +++ /dev/null @@ -1,58 +0,0 @@ -amdefine is released under two licenses: new BSD, and MIT. You may pick the -license that best suits your development needs. The text of both licenses are -provided below. - - -The "New" BSD License: ----------------------- - -Copyright (c) 2011, The Dojo Foundation -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the Dojo Foundation nor the names of its contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - - -MIT License ------------ - -Copyright (c) 2011, The Dojo Foundation - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/README.md b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/README.md deleted file mode 100644 index c6995c072..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/README.md +++ /dev/null @@ -1,171 +0,0 @@ -# amdefine - -A module that can be used to implement AMD's define() in Node. This allows you -to code to the AMD API and have the module work in node programs without -requiring those other programs to use AMD. - -## Usage - -**1)** Update your package.json to indicate amdefine as a dependency: - -```javascript - "dependencies": { - "amdefine": ">=0.1.0" - } -``` - -Then run `npm install` to get amdefine into your project. - -**2)** At the top of each module that uses define(), place this code: - -```javascript -if (typeof define !== 'function') { var define = require('amdefine')(module) } -``` - -**Only use these snippets** when loading amdefine. If you preserve the basic structure, -with the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer). - -You can add spaces, line breaks and even require amdefine with a local path, but -keep the rest of the structure to get the stripping behavior. - -As you may know, because `if` statements in JavaScript don't have their own scope, the var -declaration in the above snippet is made whether the `if` expression is truthy or not. If -RequireJS is loaded then the declaration is superfluous because `define` is already already -declared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var` -declarations of the same variable in the same scope gracefully. - -If you want to deliver amdefine.js with your code rather than specifying it as a dependency -with npm, then just download the latest release and refer to it using a relative path: - -[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js) - -### amdefine/intercept - -Consider this very experimental. - -Instead of pasting the piece of text for the amdefine setup of a `define` -variable in each module you create or consume, you can use `amdefine/intercept` -instead. It will automatically insert the above snippet in each .js file loaded -by Node. - -**Warning**: you should only use this if you are creating an application that -is consuming AMD style defined()'d modules that are distributed via npm and want -to run that code in Node. - -For library code where you are not sure if it will be used by others in Node or -in the browser, then explicitly depending on amdefine and placing the code -snippet above is suggested path, instead of using `amdefine/intercept`. The -intercept module affects all .js files loaded in the Node app, and it is -inconsiderate to modify global state like that unless you are also controlling -the top level app. - -#### Why distribute AMD-style nodes via npm? - -npm has a lot of weaknesses for front-end use (installed layout is not great, -should have better support for the `baseUrl + moduleID + '.js' style of loading, -single file JS installs), but some people want a JS package manager and are -willing to live with those constraints. If that is you, but still want to author -in AMD style modules to get dynamic require([]), better direct source usage and -powerful loader plugin support in the browser, then this tool can help. - -#### amdefine/intercept usage - -Just require it in your top level app module (for example index.js, server.js): - -```javascript -require('amdefine/intercept'); -``` - -The module does not return a value, so no need to assign the result to a local -variable. - -Then just require() code as you normally would with Node's require(). Any .js -loaded after the intercept require will have the amdefine check injected in -the .js source as it is loaded. It does not modify the source on disk, just -prepends some content to the text of the module as it is loaded by Node. - -#### How amdefine/intercept works - -It overrides the `Module._extensions['.js']` in Node to automatically prepend -the amdefine snippet above. So, it will affect any .js file loaded by your -app. - -## define() usage - -It is best if you use the anonymous forms of define() in your module: - -```javascript -define(function (require) { - var dependency = require('dependency'); -}); -``` - -or - -```javascript -define(['dependency'], function (dependency) { - -}); -``` - -## RequireJS optimizer integration.
    - -Version 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html) -will have support for stripping the `if (typeof define !== 'function')` check -mentioned above, so you can include this snippet for code that runs in the -browser, but avoid taking the cost of the if() statement once the code is -optimized for deployment. - -## Node 0.4 Support - -If you want to support Node 0.4, then add `require` as the second parameter to amdefine: - -```javascript -//Only if you want Node 0.4. If using 0.5 or later, use the above snippet. -if (typeof define !== 'function') { var define = require('amdefine')(module, require) } -``` - -## Limitations - -### Synchronous vs Asynchronous - -amdefine creates a define() function that is callable by your code. It will -execute and trace dependencies and call the factory function *synchronously*, -to keep the behavior in line with Node's synchronous dependency tracing. - -The exception: calling AMD's callback-style require() from inside a factory -function. The require callback is called on process.nextTick(): - -```javascript -define(function (require) { - require(['a'], function(a) { - //'a' is loaded synchronously, but - //this callback is called on process.nextTick(). - }); -}); -``` - -### Loader Plugins - -Loader plugins are supported as long as they call their load() callbacks -synchronously. So ones that do network requests will not work. However plugins -like [text](http://requirejs.org/docs/api.html#text) can load text files locally. - -The plugin API's `load.fromText()` is **not supported** in amdefine, so this means -transpiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs) -will not work. This may be fixable, but it is a bit complex, and I do not have -enough node-fu to figure it out yet. See the source for amdefine.js if you want -to get an idea of the issues involved. - -## Tests - -To run the tests, cd to **tests** and run: - -``` -node all.js -node all-intercept.js -``` - -## License - -New BSD and MIT. Check the LICENSE file for all the details. diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/amdefine.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/amdefine.js deleted file mode 100644 index 53bf5a686..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/amdefine.js +++ /dev/null @@ -1,299 +0,0 @@ -/** vim: et:ts=4:sw=4:sts=4 - * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. - * Available via the MIT or new BSD license. - * see: http://github.com/jrburke/amdefine for details - */ - -/*jslint node: true */ -/*global module, process */ -'use strict'; - -/** - * Creates a define for node. - * @param {Object} module the "module" object that is defined by Node for the - * current module. - * @param {Function} [requireFn]. Node's require function for the current module. - * It only needs to be passed in Node versions before 0.5, when module.require - * did not exist. - * @returns {Function} a define function that is usable for the current node - * module. - */ -function amdefine(module, requireFn) { - 'use strict'; - var defineCache = {}, - loaderCache = {}, - alreadyCalled = false, - path = require('path'), - makeRequire, stringRequire; - - /** - * Trims the . and .. from an array of path segments. - * It will keep a leading path segment if a .. will become - * the first path segment, to help with module name lookups, - * which act like paths, but can be remapped. But the end result, - * all paths that use this function should look normalized. - * NOTE: this method MODIFIES the input array. - * @param {Array} ary the array of path segments. - */ - function trimDots(ary) { - var i, part; - for (i = 0; ary[i]; i+= 1) { - part = ary[i]; - if (part === '.') { - ary.splice(i, 1); - i -= 1; - } else if (part === '..') { - if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { - //End of the line. Keep at least one non-dot - //path segment at the front so it can be mapped - //correctly to disk. Otherwise, there is likely - //no path mapping for a path starting with '..'. - //This can still fail, but catches the most reasonable - //uses of .. - break; - } else if (i > 0) { - ary.splice(i - 1, 2); - i -= 2; - } - } - } - } - - function normalize(name, baseName) { - var baseParts; - - //Adjust any relative paths. - if (name && name.charAt(0) === '.') { - //If have a base name, try to normalize against it, - //otherwise, assume it is a top-level require that will - //be relative to baseUrl in the end. - if (baseName) { - baseParts = baseName.split('/'); - baseParts = baseParts.slice(0, baseParts.length - 1); - baseParts = baseParts.concat(name.split('/')); - trimDots(baseParts); - name = baseParts.join('/'); - } - } - - return name; - } - - /** - * Create the normalize() function passed to a loader plugin's - * normalize method. - */ - function makeNormalize(relName) { - return function (name) { - return normalize(name, relName); - }; - } - - function makeLoad(id) { - function load(value) { - loaderCache[id] = value; - } - - load.fromText = function (id, text) { - //This one is difficult because the text can/probably uses - //define, and any relative paths and requires should be relative - //to that id was it would be found on disk. But this would require - //bootstrapping a module/require fairly deeply from node core. - //Not sure how best to go about that yet. - throw new Error('amdefine does not implement load.fromText'); - }; - - return load; - } - - makeRequire = function (systemRequire, exports, module, relId) { - function amdRequire(deps, callback) { - if (typeof deps === 'string') { - //Synchronous, single module require('') - return stringRequire(systemRequire, exports, module, deps, relId); - } else { - //Array of dependencies with a callback. - - //Convert the dependencies to modules. - deps = deps.map(function (depName) { - return stringRequire(systemRequire, exports, module, depName, relId); - }); - - //Wait for next tick to call back the require call. - process.nextTick(function () { - callback.apply(null, deps); - }); - } - } - - amdRequire.toUrl = function (filePath) { - if (filePath.indexOf('.') === 0) { - return normalize(filePath, path.dirname(module.filename)); - } else { - return filePath; - } - }; - - return amdRequire; - }; - - //Favor explicit value, passed in if the module wants to support Node 0.4. - requireFn = requireFn || function req() { - return module.require.apply(module, arguments); - }; - - function runFactory(id, deps, factory) { - var r, e, m, result; - - if (id) { - e = loaderCache[id] = {}; - m = { - id: id, - uri: __filename, - exports: e - }; - r = makeRequire(requireFn, e, m, id); - } else { - //Only support one define call per file - if (alreadyCalled) { - throw new Error('amdefine with no module ID cannot be called more than once per file.'); - } - alreadyCalled = true; - - //Use the real variables from node - //Use module.exports for exports, since - //the exports in here is amdefine exports. - e = module.exports; - m = module; - r = makeRequire(requireFn, e, m, module.id); - } - - //If there are dependencies, they are strings, so need - //to convert them to dependency values. - if (deps) { - deps = deps.map(function (depName) { - return r(depName); - }); - } - - //Call the factory with the right dependencies. - if (typeof factory === 'function') { - result = factory.apply(m.exports, deps); - } else { - result = factory; - } - - if (result !== undefined) { - m.exports = result; - if (id) { - loaderCache[id] = m.exports; - } - } - } - - stringRequire = function (systemRequire, exports, module, id, relId) { - //Split the ID by a ! so that - var index = id.indexOf('!'), - originalId = id, - prefix, plugin; - - if (index === -1) { - id = normalize(id, relId); - - //Straight module lookup. If it is one of the special dependencies, - //deal with it, otherwise, delegate to node. - if (id === 'require') { - return makeRequire(systemRequire, exports, module, relId); - } else if (id === 'exports') { - return exports; - } else if (id === 'module') { - return module; - } else if (loaderCache.hasOwnProperty(id)) { - return loaderCache[id]; - } else if (defineCache[id]) { - runFactory.apply(null, defineCache[id]); - return loaderCache[id]; - } else { - if(systemRequire) { - return systemRequire(originalId); - } else { - throw new Error('No module with ID: ' + id); - } - } - } else { - //There is a plugin in play. - prefix = id.substring(0, index); - id = id.substring(index + 1, id.length); - - plugin = stringRequire(systemRequire, exports, module, prefix, relId); - - if (plugin.normalize) { - id = plugin.normalize(id, makeNormalize(relId)); - } else { - //Normalize the ID normally. - id = normalize(id, relId); - } - - if (loaderCache[id]) { - return loaderCache[id]; - } else { - plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); - - return loaderCache[id]; - } - } - }; - - //Create a define function specific to the module asking for amdefine. - function define(id, deps, factory) { - if (Array.isArray(id)) { - factory = deps; - deps = id; - id = undefined; - } else if (typeof id !== 'string') { - factory = id; - id = deps = undefined; - } - - if (deps && !Array.isArray(deps)) { - factory = deps; - deps = undefined; - } - - if (!deps) { - deps = ['require', 'exports', 'module']; - } - - //Set up properties for this module. If an ID, then use - //internal cache. If no ID, then use the external variables - //for this node module. - if (id) { - //Put the module in deep freeze until there is a - //require call for it. - defineCache[id] = [id, deps, factory]; - } else { - runFactory(id, deps, factory); - } - } - - //define.require, which has access to all the values in the - //cache. Useful for AMD modules that all have IDs in the file, - //but need to finally export a value to node based on one of those - //IDs. - define.require = function (id) { - if (loaderCache[id]) { - return loaderCache[id]; - } - - if (defineCache[id]) { - runFactory.apply(null, defineCache[id]); - return loaderCache[id]; - } - }; - - define.amd = {}; - - return define; -} - -module.exports = amdefine; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/intercept.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/intercept.js deleted file mode 100644 index 771a98301..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/intercept.js +++ /dev/null @@ -1,36 +0,0 @@ -/*jshint node: true */ -var inserted, - Module = require('module'), - fs = require('fs'), - existingExtFn = Module._extensions['.js'], - amdefineRegExp = /amdefine\.js/; - -inserted = "if (typeof define !== 'function') {var define = require('amdefine')(module)}"; - -//From the node/lib/module.js source: -function stripBOM(content) { - // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - // because the buffer-to-string conversion in `fs.readFileSync()` - // translates it to FEFF, the UTF-16 BOM. - if (content.charCodeAt(0) === 0xFEFF) { - content = content.slice(1); - } - return content; -} - -//Also adapted from the node/lib/module.js source: -function intercept(module, filename) { - var content = stripBOM(fs.readFileSync(filename, 'utf8')); - - if (!amdefineRegExp.test(module.id)) { - content = inserted + content; - } - - module._compile(content, filename); -} - -intercept._id = 'amdefine/intercept'; - -if (!existingExtFn._id || existingExtFn._id !== intercept._id) { - Module._extensions['.js'] = intercept; -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/package.json b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/package.json deleted file mode 100644 index 8caf15c5a..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/node_modules/amdefine/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "amdefine", - "description": "Provide AMD's define() API for declaring modules in the AMD format", - "version": "0.1.0", - "homepage": "http://github.com/jrburke/amdefine", - "author": { - "name": "James Burke", - "email": "jrburke@gmail.com", - "url": "http://github.com/jrburke" - }, - "licenses": [ - { - "type": "BSD", - "url": "https://github.com/jrburke/amdefine/blob/master/LICENSE" - }, - { - "type": "MIT", - "url": "https://github.com/jrburke/amdefine/blob/master/LICENSE" - } - ], - "repository": { - "type": "git", - "url": "https://github.com/jrburke/amdefine.git" - }, - "main": "./amdefine.js", - "engines": { - "node": ">=0.4.2" - }, - "readme": "# amdefine\n\nA module that can be used to implement AMD's define() in Node. This allows you\nto code to the AMD API and have the module work in node programs without\nrequiring those other programs to use AMD.\n\n## Usage\n\n**1)** Update your package.json to indicate amdefine as a dependency:\n\n```javascript\n \"dependencies\": {\n \"amdefine\": \">=0.1.0\"\n }\n```\n\nThen run `npm install` to get amdefine into your project.\n\n**2)** At the top of each module that uses define(), place this code:\n\n```javascript\nif (typeof define !== 'function') { var define = require('amdefine')(module) }\n```\n\n**Only use these snippets** when loading amdefine. If you preserve the basic structure,\nwith the braces, it will be stripped out when using the [RequireJS optimizer](#optimizer).\n\nYou can add spaces, line breaks and even require amdefine with a local path, but\nkeep the rest of the structure to get the stripping behavior.\n\nAs you may know, because `if` statements in JavaScript don't have their own scope, the var\ndeclaration in the above snippet is made whether the `if` expression is truthy or not. If\nRequireJS is loaded then the declaration is superfluous because `define` is already already\ndeclared in the same scope in RequireJS. Fortunately JavaScript handles multiple `var`\ndeclarations of the same variable in the same scope gracefully.\n\nIf you want to deliver amdefine.js with your code rather than specifying it as a dependency\nwith npm, then just download the latest release and refer to it using a relative path:\n\n[Latest Version](https://github.com/jrburke/amdefine/raw/latest/amdefine.js)\n\n### amdefine/intercept\n\nConsider this very experimental.\n\nInstead of pasting the piece of text for the amdefine setup of a `define`\nvariable in each module you create or consume, you can use `amdefine/intercept`\ninstead. It will automatically insert the above snippet in each .js file loaded\nby Node.\n\n**Warning**: you should only use this if you are creating an application that\nis consuming AMD style defined()'d modules that are distributed via npm and want\nto run that code in Node.\n\nFor library code where you are not sure if it will be used by others in Node or\nin the browser, then explicitly depending on amdefine and placing the code\nsnippet above is suggested path, instead of using `amdefine/intercept`. The\nintercept module affects all .js files loaded in the Node app, and it is\ninconsiderate to modify global state like that unless you are also controlling\nthe top level app.\n\n#### Why distribute AMD-style nodes via npm?\n\nnpm has a lot of weaknesses for front-end use (installed layout is not great,\nshould have better support for the `baseUrl + moduleID + '.js' style of loading,\nsingle file JS installs), but some people want a JS package manager and are\nwilling to live with those constraints. If that is you, but still want to author\nin AMD style modules to get dynamic require([]), better direct source usage and\npowerful loader plugin support in the browser, then this tool can help.\n\n#### amdefine/intercept usage\n\nJust require it in your top level app module (for example index.js, server.js):\n\n```javascript\nrequire('amdefine/intercept');\n```\n\nThe module does not return a value, so no need to assign the result to a local\nvariable.\n\nThen just require() code as you normally would with Node's require(). Any .js\nloaded after the intercept require will have the amdefine check injected in\nthe .js source as it is loaded. It does not modify the source on disk, just\nprepends some content to the text of the module as it is loaded by Node.\n\n#### How amdefine/intercept works\n\nIt overrides the `Module._extensions['.js']` in Node to automatically prepend\nthe amdefine snippet above. So, it will affect any .js file loaded by your\napp.\n\n## define() usage\n\nIt is best if you use the anonymous forms of define() in your module:\n\n```javascript\ndefine(function (require) {\n var dependency = require('dependency');\n});\n```\n\nor\n\n```javascript\ndefine(['dependency'], function (dependency) {\n\n});\n```\n\n## RequireJS optimizer integration. \n\nVersion 1.0.3 of the [RequireJS optimizer](http://requirejs.org/docs/optimization.html)\nwill have support for stripping the `if (typeof define !== 'function')` check\nmentioned above, so you can include this snippet for code that runs in the\nbrowser, but avoid taking the cost of the if() statement once the code is\noptimized for deployment.\n\n## Node 0.4 Support\n\nIf you want to support Node 0.4, then add `require` as the second parameter to amdefine:\n\n```javascript\n//Only if you want Node 0.4. If using 0.5 or later, use the above snippet.\nif (typeof define !== 'function') { var define = require('amdefine')(module, require) }\n```\n\n## Limitations\n\n### Synchronous vs Asynchronous\n\namdefine creates a define() function that is callable by your code. It will\nexecute and trace dependencies and call the factory function *synchronously*,\nto keep the behavior in line with Node's synchronous dependency tracing.\n\nThe exception: calling AMD's callback-style require() from inside a factory\nfunction. The require callback is called on process.nextTick():\n\n```javascript\ndefine(function (require) {\n require(['a'], function(a) {\n //'a' is loaded synchronously, but\n //this callback is called on process.nextTick().\n });\n});\n```\n\n### Loader Plugins\n\nLoader plugins are supported as long as they call their load() callbacks\nsynchronously. So ones that do network requests will not work. However plugins\nlike [text](http://requirejs.org/docs/api.html#text) can load text files locally.\n\nThe plugin API's `load.fromText()` is **not supported** in amdefine, so this means\ntranspiler plugins like the [CoffeeScript loader plugin](https://github.com/jrburke/require-cs)\nwill not work. This may be fixable, but it is a bit complex, and I do not have\nenough node-fu to figure it out yet. See the source for amdefine.js if you want\nto get an idea of the issues involved.\n\n## Tests\n\nTo run the tests, cd to **tests** and run:\n\n```\nnode all.js\nnode all-intercept.js\n```\n\n## License\n\nNew BSD and MIT. Check the LICENSE file for all the details.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/jrburke/amdefine/issues" - }, - "_id": "amdefine@0.1.0", - "_from": "amdefine@>=0.0.4" -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/package.json b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/package.json deleted file mode 100644 index f59e82017..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/package.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "name": "source-map", - "description": "Generates and consumes source maps", - "version": "0.1.31", - "homepage": "https://github.com/mozilla/source-map", - "author": { - "name": "Nick Fitzgerald", - "email": "nfitzgerald@mozilla.com" - }, - "contributors": [ - { - "name": "Tobias Koppers", - "email": "tobias.koppers@googlemail.com" - }, - { - "name": "Duncan Beevers", - "email": "duncan@dweebd.com" - }, - { - "name": "Stephen Crane", - "email": "scrane@mozilla.com" - }, - { - "name": "Ryan Seddon", - "email": "seddon.ryan@gmail.com" - }, - { - "name": "Miles Elam", - "email": "miles.elam@deem.com" - }, - { - "name": "Mihai Bazon", - "email": "mihai.bazon@gmail.com" - }, - { - "name": "Michael Ficarra", - "email": "github.public.email@michael.ficarra.me" - }, - { - "name": "Todd Wolfson", - "email": "todd@twolfson.com" - }, - { - "name": "Alexander Solovyov", - "email": "alexander@solovyov.net" - }, - { - "name": "Felix Gnass", - "email": "fgnass@gmail.com" - }, - { - "name": "Conrad Irwin", - "email": "conrad.irwin@gmail.com" - }, - { - "name": "usrbincc", - "email": "usrbincc@yahoo.com" - }, - { - "name": "David Glasser", - "email": "glasser@davidglasser.net" - }, - { - "name": "Chase Douglas", - "email": "chase@newrelic.com" - }, - { - "name": "Evan Wallace", - "email": "evan.exe@gmail.com" - }, - { - "name": "Heather Arthur", - "email": "fayearthur@gmail.com" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/mozilla/source-map.git" - }, - "directories": { - "lib": "./lib" - }, - "main": "./lib/source-map.js", - "engines": { - "node": ">=0.8.0" - }, - "licenses": [ - { - "type": "BSD", - "url": "http://opensource.org/licenses/BSD-3-Clause" - } - ], - "dependencies": { - "amdefine": ">=0.0.4" - }, - "devDependencies": { - "dryice": ">=0.4.8" - }, - "scripts": { - "test": "node test/run-tests.js", - "build": "node Makefile.dryice.js" - }, - "readme": "# Source Map\n\nThis is a library to generate and consume the source map format\n[described here][format].\n\nThis library is written in the Asynchronous Module Definition format, and works\nin the following environments:\n\n* Modern Browsers supporting ECMAScript 5 (either after the build, or with an\n AMD loader such as RequireJS)\n\n* Inside Firefox (as a JSM file, after the build)\n\n* With NodeJS versions 0.8.X and higher\n\n## Node\n\n $ npm install source-map\n\n## Building from Source (for everywhere else)\n\nInstall Node and then run\n\n $ git clone https://fitzgen@github.com/mozilla/source-map.git\n $ cd source-map\n $ npm link .\n\nNext, run\n\n $ node Makefile.dryice.js\n\nThis should spew a bunch of stuff to stdout, and create the following files:\n\n* `dist/source-map.js` - The unminified browser version.\n\n* `dist/source-map.min.js` - The minified browser version.\n\n* `dist/SourceMap.jsm` - The JavaScript Module for inclusion in Firefox source.\n\n## Examples\n\n### Consuming a source map\n\n var rawSourceMap = {\n version: 3,\n file: 'min.js',\n names: ['bar', 'baz', 'n'],\n sources: ['one.js', 'two.js'],\n sourceRoot: 'http://example.com/www/js/',\n mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA'\n };\n\n var smc = new SourceMapConsumer(rawSourceMap);\n\n console.log(smc.sources);\n // [ 'http://example.com/www/js/one.js',\n // 'http://example.com/www/js/two.js' ]\n\n console.log(smc.originalPositionFor({\n line: 2,\n column: 28\n }));\n // { source: 'http://example.com/www/js/two.js',\n // line: 2,\n // column: 10,\n // name: 'n' }\n\n console.log(smc.generatedPositionFor({\n source: 'http://example.com/www/js/two.js',\n line: 2,\n column: 10\n }));\n // { line: 2, column: 28 }\n\n smc.eachMapping(function (m) {\n // ...\n });\n\n### Generating a source map\n\nIn depth guide:\n[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/)\n\n#### With SourceNode (high level API)\n\n function compile(ast) {\n switch (ast.type) {\n case 'BinaryExpression':\n return new SourceNode(\n ast.location.line,\n ast.location.column,\n ast.location.source,\n [compile(ast.left), \" + \", compile(ast.right)]\n );\n case 'Literal':\n return new SourceNode(\n ast.location.line,\n ast.location.column,\n ast.location.source,\n String(ast.value)\n );\n // ...\n default:\n throw new Error(\"Bad AST\");\n }\n }\n\n var ast = parse(\"40 + 2\", \"add.js\");\n console.log(compile(ast).toStringWithSourceMap({\n file: 'add.js'\n }));\n // { code: '40 + 2',\n // map: [object SourceMapGenerator] }\n\n#### With SourceMapGenerator (low level API)\n\n var map = new SourceMapGenerator({\n file: \"source-mapped.js\"\n });\n\n map.addMapping({\n generated: {\n line: 10,\n column: 35\n },\n source: \"foo.js\",\n original: {\n line: 33,\n column: 2\n },\n name: \"christopher\"\n });\n\n console.log(map.toString());\n // '{\"version\":3,\"file\":\"source-mapped.js\",\"sources\":[\"foo.js\"],\"names\":[\"christopher\"],\"mappings\":\";;;;;;;;;mCAgCEA\"}'\n\n## API\n\nGet a reference to the module:\n\n // NodeJS\n var sourceMap = require('source-map');\n\n // Browser builds\n var sourceMap = window.sourceMap;\n\n // Inside Firefox\n let sourceMap = {};\n Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap);\n\n### SourceMapConsumer\n\nA SourceMapConsumer instance represents a parsed source map which we can query\nfor information about the original file positions by giving it a file position\nin the generated source.\n\n#### new SourceMapConsumer(rawSourceMap)\n\nThe only parameter is the raw source map (either as a string which can be\n`JSON.parse`'d, or an object). According to the spec, source maps have the\nfollowing attributes:\n\n* `version`: Which version of the source map spec this map is following.\n\n* `sources`: An array of URLs to the original source files.\n\n* `names`: An array of identifiers which can be referrenced by individual\n mappings.\n\n* `sourceRoot`: Optional. The URL root from which all sources are relative.\n\n* `sourcesContent`: Optional. An array of contents of the original source files.\n\n* `mappings`: A string of base64 VLQs which contain the actual mappings.\n\n* `file`: The generated filename this source map is associated with.\n\n#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition)\n\nReturns the original source, line, and column information for the generated\nsource's line and column positions provided. The only argument is an object with\nthe following properties:\n\n* `line`: The line number in the generated source.\n\n* `column`: The column number in the generated source.\n\nand an object is returned with the following properties:\n\n* `source`: The original source file, or null if this information is not\n available.\n\n* `line`: The line number in the original source, or null if this information is\n not available.\n\n* `column`: The column number in the original source, or null or null if this\n information is not available.\n\n* `name`: The original identifier, or null if this information is not available.\n\n#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition)\n\nReturns the generated line and column information for the original source,\nline, and column positions provided. The only argument is an object with\nthe following properties:\n\n* `source`: The filename of the original source.\n\n* `line`: The line number in the original source.\n\n* `column`: The column number in the original source.\n\nand an object is returned with the following properties:\n\n* `line`: The line number in the generated source, or null.\n\n* `column`: The column number in the generated source, or null.\n\n#### SourceMapConsumer.prototype.sourceContentFor(source)\n\nReturns the original source content for the source provided. The only\nargument is the URL of the original source file.\n\n#### SourceMapConsumer.prototype.eachMapping(callback, context, order)\n\nIterate over each mapping between an original source/line/column and a\ngenerated line/column in this source map.\n\n* `callback`: The function that is called with each mapping. Mappings have the\n form `{ source, generatedLine, generatedColumn, originalLine, originalColumn,\n name }`\n\n* `context`: Optional. If specified, this object will be the value of `this`\n every time that `callback` is called.\n\n* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or\n `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over\n the mappings sorted by the generated file's line/column order or the\n original's source/line/column order, respectively. Defaults to\n `SourceMapConsumer.GENERATED_ORDER`.\n\n### SourceMapGenerator\n\nAn instance of the SourceMapGenerator represents a source map which is being\nbuilt incrementally.\n\n#### new SourceMapGenerator(startOfSourceMap)\n\nTo create a new one, you must pass an object with the following properties:\n\n* `file`: The filename of the generated source that this source map is\n associated with.\n\n* `sourceRoot`: An optional root for all relative URLs in this source map.\n\n#### SourceMapGenerator.fromSourceMap(sourceMapConsumer)\n\nCreates a new SourceMapGenerator based on a SourceMapConsumer\n\n* `sourceMapConsumer` The SourceMap.\n\n#### SourceMapGenerator.prototype.addMapping(mapping)\n\nAdd a single mapping from original source line and column to the generated\nsource's line and column for this source map being created. The mapping object\nshould have the following properties:\n\n* `generated`: An object with the generated line and column positions.\n\n* `original`: An object with the original line and column positions.\n\n* `source`: The original source file (relative to the sourceRoot).\n\n* `name`: An optional original token name for this mapping.\n\n#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)\n\nSet the source content for an original source file.\n\n* `sourceFile` the URL of the original source file.\n\n* `sourceContent` the content of the source file.\n\n#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile])\n\nApplies a SourceMap for a source file to the SourceMap.\nEach mapping to the supplied source file is rewritten using the\nsupplied SourceMap. Note: The resolution for the resulting mappings\nis the minimium of this map and the supplied map.\n\n* `sourceMapConsumer`: The SourceMap to be applied.\n\n* `sourceFile`: Optional. The filename of the source file.\n If omitted, sourceMapConsumer.file will be used.\n\n#### SourceMapGenerator.prototype.toString()\n\nRenders the source map being generated to a string.\n\n### SourceNode\n\nSourceNodes provide a way to abstract over interpolating and/or concatenating\nsnippets of generated JavaScript source code, while maintaining the line and\ncolumn information associated between those snippets and the original source\ncode. This is useful as the final intermediate representation a compiler might\nuse before outputting the generated JS and source map.\n\n#### new SourceNode(line, column, source[, chunk[, name]])\n\n* `line`: The original line number associated with this source node, or null if\n it isn't associated with an original line.\n\n* `column`: The original column number associated with this source node, or null\n if it isn't associated with an original column.\n\n* `source`: The original source's filename.\n\n* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see\n below.\n\n* `name`: Optional. The original identifier.\n\n#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer)\n\nCreates a SourceNode from generated code and a SourceMapConsumer.\n\n* `code`: The generated code\n\n* `sourceMapConsumer` The SourceMap for the generated code\n\n#### SourceNode.prototype.add(chunk)\n\nAdd a chunk of generated JS to this source node.\n\n* `chunk`: A string snippet of generated JS code, another instance of\n `SourceNode`, or an array where each member is one of those things.\n\n#### SourceNode.prototype.prepend(chunk)\n\nPrepend a chunk of generated JS to this source node.\n\n* `chunk`: A string snippet of generated JS code, another instance of\n `SourceNode`, or an array where each member is one of those things.\n\n#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent)\n\nSet the source content for a source file. This will be added to the\n`SourceMap` in the `sourcesContent` field.\n\n* `sourceFile`: The filename of the source file\n\n* `sourceContent`: The content of the source file\n\n#### SourceNode.prototype.walk(fn)\n\nWalk over the tree of JS snippets in this node and its children. The walking\nfunction is called once for each snippet of JS and is passed that snippet and\nthe its original associated source's line/column location.\n\n* `fn`: The traversal function.\n\n#### SourceNode.prototype.walkSourceContents(fn)\n\nWalk over the tree of SourceNodes. The walking function is called for each\nsource file content and is passed the filename and source content.\n\n* `fn`: The traversal function.\n\n#### SourceNode.prototype.join(sep)\n\nLike `Array.prototype.join` except for SourceNodes. Inserts the separator\nbetween each of this source node's children.\n\n* `sep`: The separator.\n\n#### SourceNode.prototype.replaceRight(pattern, replacement)\n\nCall `String.prototype.replace` on the very right-most source snippet. Useful\nfor trimming whitespace from the end of a source node, etc.\n\n* `pattern`: The pattern to replace.\n\n* `replacement`: The thing to replace the pattern with.\n\n#### SourceNode.prototype.toString()\n\nReturn the string representation of this source node. Walks over the tree and\nconcatenates all the various snippets together to one string.\n\n### SourceNode.prototype.toStringWithSourceMap(startOfSourceMap)\n\nReturns the string representation of this tree of source nodes, plus a\nSourceMapGenerator which contains all the mappings between the generated and\noriginal sources.\n\nThe arguments are the same as those to `new SourceMapGenerator`.\n\n## Tests\n\n[![Build Status](https://travis-ci.org/mozilla/source-map.png?branch=master)](https://travis-ci.org/mozilla/source-map)\n\nInstall NodeJS version 0.8.0 or greater, then run `node test/run-tests.js`.\n\nTo add new tests, create a new file named `test/test-.js`\nand export your test functions with names that start with \"test\", for example\n\n exports[\"test doing the foo bar\"] = function (assert, util) {\n ...\n };\n\nThe new test will be located automatically when you run the suite.\n\nThe `util` argument is the test utility module located at `test/source-map/util`.\n\nThe `assert` argument is a cut down version of node's assert module. You have\naccess to the following assertion functions:\n\n* `doesNotThrow`\n\n* `equal`\n\n* `ok`\n\n* `strictEqual`\n\n* `throws`\n\n(The reason for the restricted set of test functions is because we need the\ntests to run inside Firefox's test suite as well and so the assert module is\nshimmed in that environment. See `build/assert-shim.js`.)\n\n[format]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit\n[feature]: https://wiki.mozilla.org/DevTools/Features/SourceMap\n[Dryice]: https://github.com/mozilla/dryice\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/mozilla/source-map/issues" - }, - "_id": "source-map@0.1.31", - "_from": "source-map@~0.1.7" -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/run-tests.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/run-tests.js deleted file mode 100644 index 626c53f70..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/run-tests.js +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env node -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -var assert = require('assert'); -var fs = require('fs'); -var path = require('path'); -var util = require('./source-map/util'); - -function run(tests) { - var failures = []; - var total = 0; - var passed = 0; - - for (var i = 0; i < tests.length; i++) { - for (var k in tests[i].testCase) { - if (/^test/.test(k)) { - total++; - try { - tests[i].testCase[k](assert, util); - passed++; - } - catch (e) { - console.log('FAILED ' + tests[i].name + ': ' + k + '!'); - console.log(e.stack); - } - } - } - } - - console.log(""); - console.log(passed + ' / ' + total + ' tests passed.'); - console.log(""); - - failures.forEach(function (f) { - }); - - return failures.length; -} - -var code; - -process.stdout.on('close', function () { - process.exit(code); -}); - -function isTestFile(f) { - var testToRun = process.argv[2]; - return testToRun - ? path.basename(testToRun) === f - : /^test\-.*?\.js/.test(f); -} - -function toModule(f) { - return './source-map/' + f.replace(/\.js$/, ''); -} - -var requires = fs.readdirSync(path.join(__dirname, 'source-map')) - .filter(isTestFile) - .map(toModule); - -code = run(requires.map(require).map(function (mod, i) { - return { - name: requires[i], - testCase: mod - }; -})); -process.exit(code); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-api.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-api.js deleted file mode 100644 index 3801233c0..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-api.js +++ /dev/null @@ -1,26 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2012 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var sourceMap; - try { - sourceMap = require('../../lib/source-map'); - } catch (e) { - sourceMap = {}; - Components.utils.import('resource:///modules/devtools/SourceMap.jsm', sourceMap); - } - - exports['test that the api is properly exposed in the top level'] = function (assert, util) { - assert.equal(typeof sourceMap.SourceMapGenerator, "function"); - assert.equal(typeof sourceMap.SourceMapConsumer, "function"); - assert.equal(typeof sourceMap.SourceNode, "function"); - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-array-set.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-array-set.js deleted file mode 100644 index b5797edd5..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-array-set.js +++ /dev/null @@ -1,104 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var ArraySet = require('../../lib/source-map/array-set').ArraySet; - - function makeTestSet() { - var set = new ArraySet(); - for (var i = 0; i < 100; i++) { - set.add(String(i)); - } - return set; - } - - exports['test .has() membership'] = function (assert, util) { - var set = makeTestSet(); - for (var i = 0; i < 100; i++) { - assert.ok(set.has(String(i))); - } - }; - - exports['test .indexOf() elements'] = function (assert, util) { - var set = makeTestSet(); - for (var i = 0; i < 100; i++) { - assert.strictEqual(set.indexOf(String(i)), i); - } - }; - - exports['test .at() indexing'] = function (assert, util) { - var set = makeTestSet(); - for (var i = 0; i < 100; i++) { - assert.strictEqual(set.at(i), String(i)); - } - }; - - exports['test creating from an array'] = function (assert, util) { - var set = ArraySet.fromArray(['foo', 'bar', 'baz', 'quux', 'hasOwnProperty']); - - assert.ok(set.has('foo')); - assert.ok(set.has('bar')); - assert.ok(set.has('baz')); - assert.ok(set.has('quux')); - assert.ok(set.has('hasOwnProperty')); - - assert.strictEqual(set.indexOf('foo'), 0); - assert.strictEqual(set.indexOf('bar'), 1); - assert.strictEqual(set.indexOf('baz'), 2); - assert.strictEqual(set.indexOf('quux'), 3); - - assert.strictEqual(set.at(0), 'foo'); - assert.strictEqual(set.at(1), 'bar'); - assert.strictEqual(set.at(2), 'baz'); - assert.strictEqual(set.at(3), 'quux'); - }; - - exports['test that you can add __proto__; see github issue #30'] = function (assert, util) { - var set = new ArraySet(); - set.add('__proto__'); - assert.ok(set.has('__proto__')); - assert.strictEqual(set.at(0), '__proto__'); - assert.strictEqual(set.indexOf('__proto__'), 0); - }; - - exports['test .fromArray() with duplicates'] = function (assert, util) { - var set = ArraySet.fromArray(['foo', 'foo']); - assert.ok(set.has('foo')); - assert.strictEqual(set.at(0), 'foo'); - assert.strictEqual(set.indexOf('foo'), 0); - assert.strictEqual(set.toArray().length, 1); - - set = ArraySet.fromArray(['foo', 'foo'], true); - assert.ok(set.has('foo')); - assert.strictEqual(set.at(0), 'foo'); - assert.strictEqual(set.at(1), 'foo'); - assert.strictEqual(set.indexOf('foo'), 0); - assert.strictEqual(set.toArray().length, 2); - }; - - exports['test .add() with duplicates'] = function (assert, util) { - var set = new ArraySet(); - set.add('foo'); - - set.add('foo'); - assert.ok(set.has('foo')); - assert.strictEqual(set.at(0), 'foo'); - assert.strictEqual(set.indexOf('foo'), 0); - assert.strictEqual(set.toArray().length, 1); - - set.add('foo', true); - assert.ok(set.has('foo')); - assert.strictEqual(set.at(0), 'foo'); - assert.strictEqual(set.at(1), 'foo'); - assert.strictEqual(set.indexOf('foo'), 0); - assert.strictEqual(set.toArray().length, 2); - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64-vlq.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64-vlq.js deleted file mode 100644 index 653a874e9..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64-vlq.js +++ /dev/null @@ -1,24 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var base64VLQ = require('../../lib/source-map/base64-vlq'); - - exports['test normal encoding and decoding'] = function (assert, util) { - var result; - for (var i = -255; i < 256; i++) { - result = base64VLQ.decode(base64VLQ.encode(i)); - assert.ok(result); - assert.equal(result.value, i); - assert.equal(result.rest, ""); - } - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64.js deleted file mode 100644 index ff3a24456..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-base64.js +++ /dev/null @@ -1,35 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var base64 = require('../../lib/source-map/base64'); - - exports['test out of range encoding'] = function (assert, util) { - assert.throws(function () { - base64.encode(-1); - }); - assert.throws(function () { - base64.encode(64); - }); - }; - - exports['test out of range decoding'] = function (assert, util) { - assert.throws(function () { - base64.decode('='); - }); - }; - - exports['test normal encoding and decoding'] = function (assert, util) { - for (var i = 0; i < 64; i++) { - assert.equal(base64.decode(base64.encode(i)), i); - } - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-binary-search.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-binary-search.js deleted file mode 100644 index ee306830d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-binary-search.js +++ /dev/null @@ -1,54 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var binarySearch = require('../../lib/source-map/binary-search'); - - function numberCompare(a, b) { - return a - b; - } - - exports['test too high'] = function (assert, util) { - var needle = 30; - var haystack = [2,4,6,8,10,12,14,16,18,20]; - - assert.doesNotThrow(function () { - binarySearch.search(needle, haystack, numberCompare); - }); - - assert.equal(binarySearch.search(needle, haystack, numberCompare), 20); - }; - - exports['test too low'] = function (assert, util) { - var needle = 1; - var haystack = [2,4,6,8,10,12,14,16,18,20]; - - assert.doesNotThrow(function () { - binarySearch.search(needle, haystack, numberCompare); - }); - - assert.equal(binarySearch.search(needle, haystack, numberCompare), null); - }; - - exports['test exact search'] = function (assert, util) { - var needle = 4; - var haystack = [2,4,6,8,10,12,14,16,18,20]; - - assert.equal(binarySearch.search(needle, haystack, numberCompare), 4); - }; - - exports['test fuzzy search'] = function (assert, util) { - var needle = 19; - var haystack = [2,4,6,8,10,12,14,16,18,20]; - - assert.equal(binarySearch.search(needle, haystack, numberCompare), 18); - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-dog-fooding.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-dog-fooding.js deleted file mode 100644 index d831b9262..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-dog-fooding.js +++ /dev/null @@ -1,72 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; - var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; - - exports['test eating our own dog food'] = function (assert, util) { - var smg = new SourceMapGenerator({ - file: 'testing.js', - sourceRoot: '/wu/tang' - }); - - smg.addMapping({ - source: 'gza.coffee', - original: { line: 1, column: 0 }, - generated: { line: 2, column: 2 } - }); - - smg.addMapping({ - source: 'gza.coffee', - original: { line: 2, column: 0 }, - generated: { line: 3, column: 2 } - }); - - smg.addMapping({ - source: 'gza.coffee', - original: { line: 3, column: 0 }, - generated: { line: 4, column: 2 } - }); - - smg.addMapping({ - source: 'gza.coffee', - original: { line: 4, column: 0 }, - generated: { line: 5, column: 2 } - }); - - var smc = new SourceMapConsumer(smg.toString()); - - // Exact - util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 0, null, smc, assert); - util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 0, null, smc, assert); - util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 0, null, smc, assert); - util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 0, null, smc, assert); - - // Fuzzy - - // Original to generated - util.assertMapping(2, 0, null, null, null, null, smc, assert, true); - util.assertMapping(2, 9, '/wu/tang/gza.coffee', 1, 0, null, smc, assert, true); - util.assertMapping(3, 0, '/wu/tang/gza.coffee', 1, 0, null, smc, assert, true); - util.assertMapping(3, 9, '/wu/tang/gza.coffee', 2, 0, null, smc, assert, true); - util.assertMapping(4, 0, '/wu/tang/gza.coffee', 2, 0, null, smc, assert, true); - util.assertMapping(4, 9, '/wu/tang/gza.coffee', 3, 0, null, smc, assert, true); - util.assertMapping(5, 0, '/wu/tang/gza.coffee', 3, 0, null, smc, assert, true); - util.assertMapping(5, 9, '/wu/tang/gza.coffee', 4, 0, null, smc, assert, true); - - // Generated to original - util.assertMapping(2, 2, '/wu/tang/gza.coffee', 1, 1, null, smc, assert, null, true); - util.assertMapping(3, 2, '/wu/tang/gza.coffee', 2, 3, null, smc, assert, null, true); - util.assertMapping(4, 2, '/wu/tang/gza.coffee', 3, 6, null, smc, assert, null, true); - util.assertMapping(5, 2, '/wu/tang/gza.coffee', 4, 9, null, smc, assert, null, true); - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-consumer.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-consumer.js deleted file mode 100644 index f2c65a7f0..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-consumer.js +++ /dev/null @@ -1,451 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; - var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; - - exports['test that we can instantiate with a string or an objects'] = function (assert, util) { - assert.doesNotThrow(function () { - var map = new SourceMapConsumer(util.testMap); - }); - assert.doesNotThrow(function () { - var map = new SourceMapConsumer(JSON.stringify(util.testMap)); - }); - }; - - exports['test that the `sources` field has the original sources'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMap); - var sources = map.sources; - - assert.equal(sources[0], '/the/root/one.js'); - assert.equal(sources[1], '/the/root/two.js'); - assert.equal(sources.length, 2); - }; - - exports['test that the source root is reflected in a mapping\'s source field'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMap); - var mapping; - - mapping = map.originalPositionFor({ - line: 2, - column: 1 - }); - assert.equal(mapping.source, '/the/root/two.js'); - - mapping = map.originalPositionFor({ - line: 1, - column: 1 - }); - assert.equal(mapping.source, '/the/root/one.js'); - }; - - exports['test mapping tokens back exactly'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMap); - - util.assertMapping(1, 1, '/the/root/one.js', 1, 1, null, map, assert); - util.assertMapping(1, 5, '/the/root/one.js', 1, 5, null, map, assert); - util.assertMapping(1, 9, '/the/root/one.js', 1, 11, null, map, assert); - util.assertMapping(1, 18, '/the/root/one.js', 1, 21, 'bar', map, assert); - util.assertMapping(1, 21, '/the/root/one.js', 2, 3, null, map, assert); - util.assertMapping(1, 28, '/the/root/one.js', 2, 10, 'baz', map, assert); - util.assertMapping(1, 32, '/the/root/one.js', 2, 14, 'bar', map, assert); - - util.assertMapping(2, 1, '/the/root/two.js', 1, 1, null, map, assert); - util.assertMapping(2, 5, '/the/root/two.js', 1, 5, null, map, assert); - util.assertMapping(2, 9, '/the/root/two.js', 1, 11, null, map, assert); - util.assertMapping(2, 18, '/the/root/two.js', 1, 21, 'n', map, assert); - util.assertMapping(2, 21, '/the/root/two.js', 2, 3, null, map, assert); - util.assertMapping(2, 28, '/the/root/two.js', 2, 10, 'n', map, assert); - }; - - exports['test mapping tokens fuzzy'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMap); - - // Finding original positions - util.assertMapping(1, 20, '/the/root/one.js', 1, 21, 'bar', map, assert, true); - util.assertMapping(1, 30, '/the/root/one.js', 2, 10, 'baz', map, assert, true); - util.assertMapping(2, 12, '/the/root/two.js', 1, 11, null, map, assert, true); - - // Finding generated positions - util.assertMapping(1, 18, '/the/root/one.js', 1, 22, 'bar', map, assert, null, true); - util.assertMapping(1, 28, '/the/root/one.js', 2, 13, 'baz', map, assert, null, true); - util.assertMapping(2, 9, '/the/root/two.js', 1, 16, null, map, assert, null, true); - }; - - exports['test creating source map consumers with )]}\' prefix'] = function (assert, util) { - assert.doesNotThrow(function () { - var map = new SourceMapConsumer(")]}'" + JSON.stringify(util.testMap)); - }); - }; - - exports['test eachMapping'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMap); - var previousLine = -Infinity; - var previousColumn = -Infinity; - map.eachMapping(function (mapping) { - assert.ok(mapping.generatedLine >= previousLine); - - if (mapping.source) { - assert.equal(mapping.source.indexOf(util.testMap.sourceRoot), 0); - } - - if (mapping.generatedLine === previousLine) { - assert.ok(mapping.generatedColumn >= previousColumn); - previousColumn = mapping.generatedColumn; - } - else { - previousLine = mapping.generatedLine; - previousColumn = -Infinity; - } - }); - }; - - exports['test iterating over mappings in a different order'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMap); - var previousLine = -Infinity; - var previousColumn = -Infinity; - var previousSource = ""; - map.eachMapping(function (mapping) { - assert.ok(mapping.source >= previousSource); - - if (mapping.source === previousSource) { - assert.ok(mapping.originalLine >= previousLine); - - if (mapping.originalLine === previousLine) { - assert.ok(mapping.originalColumn >= previousColumn); - previousColumn = mapping.originalColumn; - } - else { - previousLine = mapping.originalLine; - previousColumn = -Infinity; - } - } - else { - previousSource = mapping.source; - previousLine = -Infinity; - previousColumn = -Infinity; - } - }, null, SourceMapConsumer.ORIGINAL_ORDER); - }; - - exports['test that we can set the context for `this` in eachMapping'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMap); - var context = {}; - map.eachMapping(function () { - assert.equal(this, context); - }, context); - }; - - exports['test that the `sourcesContent` field has the original sources'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMapWithSourcesContent); - var sourcesContent = map.sourcesContent; - - assert.equal(sourcesContent[0], ' ONE.foo = function (bar) {\n return baz(bar);\n };'); - assert.equal(sourcesContent[1], ' TWO.inc = function (n) {\n return n + 1;\n };'); - assert.equal(sourcesContent.length, 2); - }; - - exports['test that we can get the original sources for the sources'] = function (assert, util) { - var map = new SourceMapConsumer(util.testMapWithSourcesContent); - var sources = map.sources; - - assert.equal(map.sourceContentFor(sources[0]), ' ONE.foo = function (bar) {\n return baz(bar);\n };'); - assert.equal(map.sourceContentFor(sources[1]), ' TWO.inc = function (n) {\n return n + 1;\n };'); - assert.equal(map.sourceContentFor("one.js"), ' ONE.foo = function (bar) {\n return baz(bar);\n };'); - assert.equal(map.sourceContentFor("two.js"), ' TWO.inc = function (n) {\n return n + 1;\n };'); - assert.throws(function () { - map.sourceContentFor(""); - }, Error); - assert.throws(function () { - map.sourceContentFor("/the/root/three.js"); - }, Error); - assert.throws(function () { - map.sourceContentFor("three.js"); - }, Error); - }; - - exports['test sourceRoot + generatedPositionFor'] = function (assert, util) { - var map = new SourceMapGenerator({ - sourceRoot: 'foo/bar', - file: 'baz.js' - }); - map.addMapping({ - original: { line: 1, column: 1 }, - generated: { line: 2, column: 2 }, - source: 'bang.coffee' - }); - map.addMapping({ - original: { line: 5, column: 5 }, - generated: { line: 6, column: 6 }, - source: 'bang.coffee' - }); - map = new SourceMapConsumer(map.toString()); - - // Should handle without sourceRoot. - var pos = map.generatedPositionFor({ - line: 1, - column: 1, - source: 'bang.coffee' - }); - - assert.equal(pos.line, 2); - assert.equal(pos.column, 2); - - // Should handle with sourceRoot. - var pos = map.generatedPositionFor({ - line: 1, - column: 1, - source: 'foo/bar/bang.coffee' - }); - - assert.equal(pos.line, 2); - assert.equal(pos.column, 2); - }; - - exports['test sourceRoot + originalPositionFor'] = function (assert, util) { - var map = new SourceMapGenerator({ - sourceRoot: 'foo/bar', - file: 'baz.js' - }); - map.addMapping({ - original: { line: 1, column: 1 }, - generated: { line: 2, column: 2 }, - source: 'bang.coffee' - }); - map = new SourceMapConsumer(map.toString()); - - var pos = map.originalPositionFor({ - line: 2, - column: 2, - }); - - // Should always have the prepended source root - assert.equal(pos.source, 'foo/bar/bang.coffee'); - assert.equal(pos.line, 1); - assert.equal(pos.column, 1); - }; - - exports['test github issue #56'] = function (assert, util) { - var map = new SourceMapGenerator({ - sourceRoot: 'http://', - file: 'www.example.com/foo.js' - }); - map.addMapping({ - original: { line: 1, column: 1 }, - generated: { line: 2, column: 2 }, - source: 'www.example.com/original.js' - }); - map = new SourceMapConsumer(map.toString()); - - var sources = map.sources; - assert.equal(sources.length, 1); - assert.equal(sources[0], 'http://www.example.com/original.js'); - }; - - exports['test github issue #43'] = function (assert, util) { - var map = new SourceMapGenerator({ - sourceRoot: 'http://example.com', - file: 'foo.js' - }); - map.addMapping({ - original: { line: 1, column: 1 }, - generated: { line: 2, column: 2 }, - source: 'http://cdn.example.com/original.js' - }); - map = new SourceMapConsumer(map.toString()); - - var sources = map.sources; - assert.equal(sources.length, 1, - 'Should only be one source.'); - assert.equal(sources[0], 'http://cdn.example.com/original.js', - 'Should not be joined with the sourceRoot.'); - }; - - exports['test absolute path, but same host sources'] = function (assert, util) { - var map = new SourceMapGenerator({ - sourceRoot: 'http://example.com/foo/bar', - file: 'foo.js' - }); - map.addMapping({ - original: { line: 1, column: 1 }, - generated: { line: 2, column: 2 }, - source: '/original.js' - }); - map = new SourceMapConsumer(map.toString()); - - var sources = map.sources; - assert.equal(sources.length, 1, - 'Should only be one source.'); - assert.equal(sources[0], 'http://example.com/original.js', - 'Source should be relative the host of the source root.'); - }; - - exports['test github issue #64'] = function (assert, util) { - var map = new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sourceRoot": "http://example.com/", - "sources": ["/a"], - "names": [], - "mappings": "AACA", - "sourcesContent": ["foo"] - }); - - assert.equal(map.sourceContentFor("a"), "foo"); - assert.equal(map.sourceContentFor("/a"), "foo"); - }; - - exports['test bug 885597'] = function (assert, util) { - var map = new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sourceRoot": "file:///Users/AlGore/Invented/The/Internet/", - "sources": ["/a"], - "names": [], - "mappings": "AACA", - "sourcesContent": ["foo"] - }); - - var s = map.sources[0]; - assert.equal(map.sourceContentFor(s), "foo"); - }; - - exports['test github issue #72, duplicate sources'] = function (assert, util) { - var map = new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sources": ["source1.js", "source1.js", "source3.js"], - "names": [], - "mappings": ";EAAC;;IAEE;;MEEE", - "sourceRoot": "http://example.com" - }); - - var pos = map.originalPositionFor({ - line: 2, - column: 2 - }); - assert.equal(pos.source, 'http://example.com/source1.js'); - assert.equal(pos.line, 1); - assert.equal(pos.column, 1); - - var pos = map.originalPositionFor({ - line: 4, - column: 4 - }); - assert.equal(pos.source, 'http://example.com/source1.js'); - assert.equal(pos.line, 3); - assert.equal(pos.column, 3); - - var pos = map.originalPositionFor({ - line: 6, - column: 6 - }); - assert.equal(pos.source, 'http://example.com/source3.js'); - assert.equal(pos.line, 5); - assert.equal(pos.column, 5); - }; - - exports['test github issue #72, duplicate names'] = function (assert, util) { - var map = new SourceMapConsumer({ - "version": 3, - "file": "foo.js", - "sources": ["source.js"], - "names": ["name1", "name1", "name3"], - "mappings": ";EAACA;;IAEEA;;MAEEE", - "sourceRoot": "http://example.com" - }); - - var pos = map.originalPositionFor({ - line: 2, - column: 2 - }); - assert.equal(pos.name, 'name1'); - assert.equal(pos.line, 1); - assert.equal(pos.column, 1); - - var pos = map.originalPositionFor({ - line: 4, - column: 4 - }); - assert.equal(pos.name, 'name1'); - assert.equal(pos.line, 3); - assert.equal(pos.column, 3); - - var pos = map.originalPositionFor({ - line: 6, - column: 6 - }); - assert.equal(pos.name, 'name3'); - assert.equal(pos.line, 5); - assert.equal(pos.column, 5); - }; - - exports['test SourceMapConsumer.fromSourceMap'] = function (assert, util) { - var smg = new SourceMapGenerator({ - sourceRoot: 'http://example.com/', - file: 'foo.js' - }); - smg.addMapping({ - original: { line: 1, column: 1 }, - generated: { line: 2, column: 2 }, - source: 'bar.js' - }); - smg.addMapping({ - original: { line: 2, column: 2 }, - generated: { line: 4, column: 4 }, - source: 'baz.js', - name: 'dirtMcGirt' - }); - smg.setSourceContent('baz.js', 'baz.js content'); - - var smc = SourceMapConsumer.fromSourceMap(smg); - assert.equal(smc.file, 'foo.js'); - assert.equal(smc.sourceRoot, 'http://example.com/'); - assert.equal(smc.sources.length, 2); - assert.equal(smc.sources[0], 'http://example.com/bar.js'); - assert.equal(smc.sources[1], 'http://example.com/baz.js'); - assert.equal(smc.sourceContentFor('baz.js'), 'baz.js content'); - - var pos = smc.originalPositionFor({ - line: 2, - column: 2 - }); - assert.equal(pos.line, 1); - assert.equal(pos.column, 1); - assert.equal(pos.source, 'http://example.com/bar.js'); - assert.equal(pos.name, null); - - pos = smc.generatedPositionFor({ - line: 1, - column: 1, - source: 'http://example.com/bar.js' - }); - assert.equal(pos.line, 2); - assert.equal(pos.column, 2); - - pos = smc.originalPositionFor({ - line: 4, - column: 4 - }); - assert.equal(pos.line, 2); - assert.equal(pos.column, 2); - assert.equal(pos.source, 'http://example.com/baz.js'); - assert.equal(pos.name, 'dirtMcGirt'); - - pos = smc.generatedPositionFor({ - line: 2, - column: 2, - source: 'http://example.com/baz.js' - }); - assert.equal(pos.line, 4); - assert.equal(pos.column, 4); - }; -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-generator.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-generator.js deleted file mode 100644 index ba292f548..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-map-generator.js +++ /dev/null @@ -1,417 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; - var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; - var SourceNode = require('../../lib/source-map/source-node').SourceNode; - var util = require('./util'); - - exports['test some simple stuff'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'foo.js', - sourceRoot: '.' - }); - assert.ok(true); - }; - - exports['test JSON serialization'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'foo.js', - sourceRoot: '.' - }); - assert.equal(map.toString(), JSON.stringify(map)); - }; - - exports['test adding mappings (case 1)'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'generated-foo.js', - sourceRoot: '.' - }); - - assert.doesNotThrow(function () { - map.addMapping({ - generated: { line: 1, column: 1 } - }); - }); - }; - - exports['test adding mappings (case 2)'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'generated-foo.js', - sourceRoot: '.' - }); - - assert.doesNotThrow(function () { - map.addMapping({ - generated: { line: 1, column: 1 }, - source: 'bar.js', - original: { line: 1, column: 1 } - }); - }); - }; - - exports['test adding mappings (case 3)'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'generated-foo.js', - sourceRoot: '.' - }); - - assert.doesNotThrow(function () { - map.addMapping({ - generated: { line: 1, column: 1 }, - source: 'bar.js', - original: { line: 1, column: 1 }, - name: 'someToken' - }); - }); - }; - - exports['test adding mappings (invalid)'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'generated-foo.js', - sourceRoot: '.' - }); - - // Not enough info. - assert.throws(function () { - map.addMapping({}); - }); - - // Original file position, but no source. - assert.throws(function () { - map.addMapping({ - generated: { line: 1, column: 1 }, - original: { line: 1, column: 1 } - }); - }); - }; - - exports['test that the correct mappings are being generated'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'min.js', - sourceRoot: '/the/root' - }); - - map.addMapping({ - generated: { line: 1, column: 1 }, - original: { line: 1, column: 1 }, - source: 'one.js' - }); - map.addMapping({ - generated: { line: 1, column: 5 }, - original: { line: 1, column: 5 }, - source: 'one.js' - }); - map.addMapping({ - generated: { line: 1, column: 9 }, - original: { line: 1, column: 11 }, - source: 'one.js' - }); - map.addMapping({ - generated: { line: 1, column: 18 }, - original: { line: 1, column: 21 }, - source: 'one.js', - name: 'bar' - }); - map.addMapping({ - generated: { line: 1, column: 21 }, - original: { line: 2, column: 3 }, - source: 'one.js' - }); - map.addMapping({ - generated: { line: 1, column: 28 }, - original: { line: 2, column: 10 }, - source: 'one.js', - name: 'baz' - }); - map.addMapping({ - generated: { line: 1, column: 32 }, - original: { line: 2, column: 14 }, - source: 'one.js', - name: 'bar' - }); - - map.addMapping({ - generated: { line: 2, column: 1 }, - original: { line: 1, column: 1 }, - source: 'two.js' - }); - map.addMapping({ - generated: { line: 2, column: 5 }, - original: { line: 1, column: 5 }, - source: 'two.js' - }); - map.addMapping({ - generated: { line: 2, column: 9 }, - original: { line: 1, column: 11 }, - source: 'two.js' - }); - map.addMapping({ - generated: { line: 2, column: 18 }, - original: { line: 1, column: 21 }, - source: 'two.js', - name: 'n' - }); - map.addMapping({ - generated: { line: 2, column: 21 }, - original: { line: 2, column: 3 }, - source: 'two.js' - }); - map.addMapping({ - generated: { line: 2, column: 28 }, - original: { line: 2, column: 10 }, - source: 'two.js', - name: 'n' - }); - - map = JSON.parse(map.toString()); - - util.assertEqualMaps(assert, map, util.testMap); - }; - - exports['test that source content can be set'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'min.js', - sourceRoot: '/the/root' - }); - map.addMapping({ - generated: { line: 1, column: 1 }, - original: { line: 1, column: 1 }, - source: 'one.js' - }); - map.addMapping({ - generated: { line: 2, column: 1 }, - original: { line: 1, column: 1 }, - source: 'two.js' - }); - map.setSourceContent('one.js', 'one file content'); - - map = JSON.parse(map.toString()); - assert.equal(map.sources[0], 'one.js'); - assert.equal(map.sources[1], 'two.js'); - assert.equal(map.sourcesContent[0], 'one file content'); - assert.equal(map.sourcesContent[1], null); - }; - - exports['test .fromSourceMap'] = function (assert, util) { - var map = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(util.testMap)); - util.assertEqualMaps(assert, map.toJSON(), util.testMap); - }; - - exports['test .fromSourceMap with sourcesContent'] = function (assert, util) { - var map = SourceMapGenerator.fromSourceMap( - new SourceMapConsumer(util.testMapWithSourcesContent)); - util.assertEqualMaps(assert, map.toJSON(), util.testMapWithSourcesContent); - }; - - exports['test applySourceMap'] = function (assert, util) { - var node = new SourceNode(null, null, null, [ - new SourceNode(2, 0, 'fileX', 'lineX2\n'), - 'genA1\n', - new SourceNode(2, 0, 'fileY', 'lineY2\n'), - 'genA2\n', - new SourceNode(1, 0, 'fileX', 'lineX1\n'), - 'genA3\n', - new SourceNode(1, 0, 'fileY', 'lineY1\n') - ]); - var mapStep1 = node.toStringWithSourceMap({ - file: 'fileA' - }).map; - mapStep1.setSourceContent('fileX', 'lineX1\nlineX2\n'); - mapStep1 = mapStep1.toJSON(); - - node = new SourceNode(null, null, null, [ - 'gen1\n', - new SourceNode(1, 0, 'fileA', 'lineA1\n'), - new SourceNode(2, 0, 'fileA', 'lineA2\n'), - new SourceNode(3, 0, 'fileA', 'lineA3\n'), - new SourceNode(4, 0, 'fileA', 'lineA4\n'), - new SourceNode(1, 0, 'fileB', 'lineB1\n'), - new SourceNode(2, 0, 'fileB', 'lineB2\n'), - 'gen2\n' - ]); - var mapStep2 = node.toStringWithSourceMap({ - file: 'fileGen' - }).map; - mapStep2.setSourceContent('fileB', 'lineB1\nlineB2\n'); - mapStep2 = mapStep2.toJSON(); - - node = new SourceNode(null, null, null, [ - 'gen1\n', - new SourceNode(2, 0, 'fileX', 'lineA1\n'), - new SourceNode(2, 0, 'fileA', 'lineA2\n'), - new SourceNode(2, 0, 'fileY', 'lineA3\n'), - new SourceNode(4, 0, 'fileA', 'lineA4\n'), - new SourceNode(1, 0, 'fileB', 'lineB1\n'), - new SourceNode(2, 0, 'fileB', 'lineB2\n'), - 'gen2\n' - ]); - var expectedMap = node.toStringWithSourceMap({ - file: 'fileGen' - }).map; - expectedMap.setSourceContent('fileX', 'lineX1\nlineX2\n'); - expectedMap.setSourceContent('fileB', 'lineB1\nlineB2\n'); - expectedMap = expectedMap.toJSON(); - - // apply source map "mapStep1" to "mapStep2" - var generator = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(mapStep2)); - generator.applySourceMap(new SourceMapConsumer(mapStep1)); - var actualMap = generator.toJSON(); - - util.assertEqualMaps(assert, actualMap, expectedMap); - }; - - exports['test sorting with duplicate generated mappings'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'test.js' - }); - map.addMapping({ - generated: { line: 3, column: 0 }, - original: { line: 2, column: 0 }, - source: 'a.js' - }); - map.addMapping({ - generated: { line: 2, column: 0 } - }); - map.addMapping({ - generated: { line: 2, column: 0 } - }); - map.addMapping({ - generated: { line: 1, column: 0 }, - original: { line: 1, column: 0 }, - source: 'a.js' - }); - - util.assertEqualMaps(assert, map.toJSON(), { - version: 3, - file: 'test.js', - sources: ['a.js'], - names: [], - mappings: 'AAAA;A;AACA' - }); - }; - - exports['test ignore duplicate mappings.'] = function (assert, util) { - var init = { file: 'min.js', sourceRoot: '/the/root' }; - var map1, map2; - - // null original source location - var nullMapping1 = { - generated: { line: 1, column: 0 } - }; - var nullMapping2 = { - generated: { line: 2, column: 2 } - }; - - map1 = new SourceMapGenerator(init); - map2 = new SourceMapGenerator(init); - - map1.addMapping(nullMapping1); - map1.addMapping(nullMapping1); - - map2.addMapping(nullMapping1); - - util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); - - map1.addMapping(nullMapping2); - map1.addMapping(nullMapping1); - - map2.addMapping(nullMapping2); - - util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); - - // original source location - var srcMapping1 = { - generated: { line: 1, column: 0 }, - original: { line: 11, column: 0 }, - source: 'srcMapping1.js' - }; - var srcMapping2 = { - generated: { line: 2, column: 2 }, - original: { line: 11, column: 0 }, - source: 'srcMapping2.js' - }; - - map1 = new SourceMapGenerator(init); - map2 = new SourceMapGenerator(init); - - map1.addMapping(srcMapping1); - map1.addMapping(srcMapping1); - - map2.addMapping(srcMapping1); - - util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); - - map1.addMapping(srcMapping2); - map1.addMapping(srcMapping1); - - map2.addMapping(srcMapping2); - - util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); - - // full original source and name information - var fullMapping1 = { - generated: { line: 1, column: 0 }, - original: { line: 11, column: 0 }, - source: 'fullMapping1.js', - name: 'fullMapping1' - }; - var fullMapping2 = { - generated: { line: 2, column: 2 }, - original: { line: 11, column: 0 }, - source: 'fullMapping2.js', - name: 'fullMapping2' - }; - - map1 = new SourceMapGenerator(init); - map2 = new SourceMapGenerator(init); - - map1.addMapping(fullMapping1); - map1.addMapping(fullMapping1); - - map2.addMapping(fullMapping1); - - util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); - - map1.addMapping(fullMapping2); - map1.addMapping(fullMapping1); - - map2.addMapping(fullMapping2); - - util.assertEqualMaps(assert, map1.toJSON(), map2.toJSON()); - }; - - exports['test github issue #72, check for duplicate names or sources'] = function (assert, util) { - var map = new SourceMapGenerator({ - file: 'test.js' - }); - map.addMapping({ - generated: { line: 1, column: 1 }, - original: { line: 2, column: 2 }, - source: 'a.js', - name: 'foo' - }); - map.addMapping({ - generated: { line: 3, column: 3 }, - original: { line: 4, column: 4 }, - source: 'a.js', - name: 'foo' - }); - util.assertEqualMaps(assert, map.toJSON(), { - version: 3, - file: 'test.js', - sources: ['a.js'], - names: ['foo'], - mappings: 'CACEA;;GAEEA' - }); - }; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-node.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-node.js deleted file mode 100644 index 6e0eca82d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/test-source-node.js +++ /dev/null @@ -1,365 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var SourceMapGenerator = require('../../lib/source-map/source-map-generator').SourceMapGenerator; - var SourceMapConsumer = require('../../lib/source-map/source-map-consumer').SourceMapConsumer; - var SourceNode = require('../../lib/source-map/source-node').SourceNode; - - exports['test .add()'] = function (assert, util) { - var node = new SourceNode(null, null, null); - - // Adding a string works. - node.add('function noop() {}'); - - // Adding another source node works. - node.add(new SourceNode(null, null, null)); - - // Adding an array works. - node.add(['function foo() {', - new SourceNode(null, null, null, - 'return 10;'), - '}']); - - // Adding other stuff doesn't. - assert.throws(function () { - node.add({}); - }); - assert.throws(function () { - node.add(function () {}); - }); - }; - - exports['test .prepend()'] = function (assert, util) { - var node = new SourceNode(null, null, null); - - // Prepending a string works. - node.prepend('function noop() {}'); - assert.equal(node.children[0], 'function noop() {}'); - assert.equal(node.children.length, 1); - - // Prepending another source node works. - node.prepend(new SourceNode(null, null, null)); - assert.equal(node.children[0], ''); - assert.equal(node.children[1], 'function noop() {}'); - assert.equal(node.children.length, 2); - - // Prepending an array works. - node.prepend(['function foo() {', - new SourceNode(null, null, null, - 'return 10;'), - '}']); - assert.equal(node.children[0], 'function foo() {'); - assert.equal(node.children[1], 'return 10;'); - assert.equal(node.children[2], '}'); - assert.equal(node.children[3], ''); - assert.equal(node.children[4], 'function noop() {}'); - assert.equal(node.children.length, 5); - - // Prepending other stuff doesn't. - assert.throws(function () { - node.prepend({}); - }); - assert.throws(function () { - node.prepend(function () {}); - }); - }; - - exports['test .toString()'] = function (assert, util) { - assert.equal((new SourceNode(null, null, null, - ['function foo() {', - new SourceNode(null, null, null, 'return 10;'), - '}'])).toString(), - 'function foo() {return 10;}'); - }; - - exports['test .join()'] = function (assert, util) { - assert.equal((new SourceNode(null, null, null, - ['a', 'b', 'c', 'd'])).join(', ').toString(), - 'a, b, c, d'); - }; - - exports['test .walk()'] = function (assert, util) { - var node = new SourceNode(null, null, null, - ['(function () {\n', - ' ', new SourceNode(1, 0, 'a.js', ['someCall()']), ';\n', - ' ', new SourceNode(2, 0, 'b.js', ['if (foo) bar()']), ';\n', - '}());']); - var expected = [ - { str: '(function () {\n', source: null, line: null, column: null }, - { str: ' ', source: null, line: null, column: null }, - { str: 'someCall()', source: 'a.js', line: 1, column: 0 }, - { str: ';\n', source: null, line: null, column: null }, - { str: ' ', source: null, line: null, column: null }, - { str: 'if (foo) bar()', source: 'b.js', line: 2, column: 0 }, - { str: ';\n', source: null, line: null, column: null }, - { str: '}());', source: null, line: null, column: null }, - ]; - var i = 0; - node.walk(function (chunk, loc) { - assert.equal(expected[i].str, chunk); - assert.equal(expected[i].source, loc.source); - assert.equal(expected[i].line, loc.line); - assert.equal(expected[i].column, loc.column); - i++; - }); - }; - - exports['test .replaceRight'] = function (assert, util) { - var node; - - // Not nested - node = new SourceNode(null, null, null, 'hello world'); - node.replaceRight(/world/, 'universe'); - assert.equal(node.toString(), 'hello universe'); - - // Nested - node = new SourceNode(null, null, null, - [new SourceNode(null, null, null, 'hey sexy mama, '), - new SourceNode(null, null, null, 'want to kill all humans?')]); - node.replaceRight(/kill all humans/, 'watch Futurama'); - assert.equal(node.toString(), 'hey sexy mama, want to watch Futurama?'); - }; - - exports['test .toStringWithSourceMap()'] = function (assert, util) { - var node = new SourceNode(null, null, null, - ['(function () {\n', - ' ', - new SourceNode(1, 0, 'a.js', 'someCall', 'originalCall'), - new SourceNode(1, 8, 'a.js', '()'), - ';\n', - ' ', new SourceNode(2, 0, 'b.js', ['if (foo) bar()']), ';\n', - '}());']); - var map = node.toStringWithSourceMap({ - file: 'foo.js' - }).map; - - assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); - map = new SourceMapConsumer(map.toString()); - - var actual; - - actual = map.originalPositionFor({ - line: 1, - column: 4 - }); - assert.equal(actual.source, null); - assert.equal(actual.line, null); - assert.equal(actual.column, null); - - actual = map.originalPositionFor({ - line: 2, - column: 2 - }); - assert.equal(actual.source, 'a.js'); - assert.equal(actual.line, 1); - assert.equal(actual.column, 0); - assert.equal(actual.name, 'originalCall'); - - actual = map.originalPositionFor({ - line: 3, - column: 2 - }); - assert.equal(actual.source, 'b.js'); - assert.equal(actual.line, 2); - assert.equal(actual.column, 0); - - actual = map.originalPositionFor({ - line: 3, - column: 16 - }); - assert.equal(actual.source, null); - assert.equal(actual.line, null); - assert.equal(actual.column, null); - - actual = map.originalPositionFor({ - line: 4, - column: 2 - }); - assert.equal(actual.source, null); - assert.equal(actual.line, null); - assert.equal(actual.column, null); - }; - - exports['test .fromStringWithSourceMap()'] = function (assert, util) { - var node = SourceNode.fromStringWithSourceMap( - util.testGeneratedCode, - new SourceMapConsumer(util.testMap)); - - var result = node.toStringWithSourceMap({ - file: 'min.js' - }); - var map = result.map; - var code = result.code; - - assert.equal(code, util.testGeneratedCode); - assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); - map = map.toJSON(); - assert.equal(map.version, util.testMap.version); - assert.equal(map.file, util.testMap.file); - assert.equal(map.mappings, util.testMap.mappings); - }; - - exports['test .fromStringWithSourceMap() empty map'] = function (assert, util) { - var node = SourceNode.fromStringWithSourceMap( - util.testGeneratedCode, - new SourceMapConsumer(util.emptyMap)); - var result = node.toStringWithSourceMap({ - file: 'min.js' - }); - var map = result.map; - var code = result.code; - - assert.equal(code, util.testGeneratedCode); - assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); - map = map.toJSON(); - assert.equal(map.version, util.emptyMap.version); - assert.equal(map.file, util.emptyMap.file); - assert.equal(map.mappings.length, util.emptyMap.mappings.length); - assert.equal(map.mappings, util.emptyMap.mappings); - }; - - exports['test .fromStringWithSourceMap() complex version'] = function (assert, util) { - var input = new SourceNode(null, null, null, [ - "(function() {\n", - " var Test = {};\n", - " ", new SourceNode(1, 0, "a.js", "Test.A = { value: 1234 };\n"), - " ", new SourceNode(2, 0, "a.js", "Test.A.x = 'xyz';"), "\n", - "}());\n", - "/* Generated Source */"]); - input = input.toStringWithSourceMap({ - file: 'foo.js' - }); - - var node = SourceNode.fromStringWithSourceMap( - input.code, - new SourceMapConsumer(input.map.toString())); - - var result = node.toStringWithSourceMap({ - file: 'foo.js' - }); - var map = result.map; - var code = result.code; - - assert.equal(code, input.code); - assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); - map = map.toJSON(); - var inputMap = input.map.toJSON(); - util.assertEqualMaps(assert, map, inputMap); - }; - - exports['test .fromStringWithSourceMap() merging duplicate mappings'] = function (assert, util) { - var input = new SourceNode(null, null, null, [ - new SourceNode(1, 0, "a.js", "(function"), - new SourceNode(1, 0, "a.js", "() {\n"), - " ", - new SourceNode(1, 0, "a.js", "var Test = "), - new SourceNode(1, 0, "b.js", "{};\n"), - new SourceNode(2, 0, "b.js", "Test"), - new SourceNode(2, 0, "b.js", ".A", "A"), - new SourceNode(2, 20, "b.js", " = { value: 1234 };\n", "A"), - "}());\n", - "/* Generated Source */" - ]); - input = input.toStringWithSourceMap({ - file: 'foo.js' - }); - - var correctMap = new SourceMapGenerator({ - file: 'foo.js' - }); - correctMap.addMapping({ - generated: { line: 1, column: 0 }, - source: 'a.js', - original: { line: 1, column: 0 } - }); - correctMap.addMapping({ - generated: { line: 2, column: 0 } - }); - correctMap.addMapping({ - generated: { line: 2, column: 2 }, - source: 'a.js', - original: { line: 1, column: 0 } - }); - correctMap.addMapping({ - generated: { line: 2, column: 13 }, - source: 'b.js', - original: { line: 1, column: 0 } - }); - correctMap.addMapping({ - generated: { line: 3, column: 0 }, - source: 'b.js', - original: { line: 2, column: 0 } - }); - correctMap.addMapping({ - generated: { line: 3, column: 4 }, - source: 'b.js', - name: 'A', - original: { line: 2, column: 0 } - }); - correctMap.addMapping({ - generated: { line: 3, column: 6 }, - source: 'b.js', - name: 'A', - original: { line: 2, column: 20 } - }); - correctMap.addMapping({ - generated: { line: 4, column: 0 } - }); - - var inputMap = input.map.toJSON(); - correctMap = correctMap.toJSON(); - util.assertEqualMaps(assert, correctMap, inputMap); - }; - - exports['test setSourceContent with toStringWithSourceMap'] = function (assert, util) { - var aNode = new SourceNode(1, 1, 'a.js', 'a'); - aNode.setSourceContent('a.js', 'someContent'); - var node = new SourceNode(null, null, null, - ['(function () {\n', - ' ', aNode, - ' ', new SourceNode(1, 1, 'b.js', 'b'), - '}());']); - node.setSourceContent('b.js', 'otherContent'); - var map = node.toStringWithSourceMap({ - file: 'foo.js' - }).map; - - assert.ok(map instanceof SourceMapGenerator, 'map instanceof SourceMapGenerator'); - map = new SourceMapConsumer(map.toString()); - - assert.equal(map.sources.length, 2); - assert.equal(map.sources[0], 'a.js'); - assert.equal(map.sources[1], 'b.js'); - assert.equal(map.sourcesContent.length, 2); - assert.equal(map.sourcesContent[0], 'someContent'); - assert.equal(map.sourcesContent[1], 'otherContent'); - }; - - exports['test walkSourceContents'] = function (assert, util) { - var aNode = new SourceNode(1, 1, 'a.js', 'a'); - aNode.setSourceContent('a.js', 'someContent'); - var node = new SourceNode(null, null, null, - ['(function () {\n', - ' ', aNode, - ' ', new SourceNode(1, 1, 'b.js', 'b'), - '}());']); - node.setSourceContent('b.js', 'otherContent'); - var results = []; - node.walkSourceContents(function (sourceFile, sourceContent) { - results.push([sourceFile, sourceContent]); - }); - assert.equal(results.length, 2); - assert.equal(results[0][0], 'a.js'); - assert.equal(results[0][1], 'someContent'); - assert.equal(results[1][0], 'b.js'); - assert.equal(results[1][1], 'otherContent'); - }; -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/util.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/util.js deleted file mode 100644 index 288046bfa..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/node_modules/source-map/test/source-map/util.js +++ /dev/null @@ -1,161 +0,0 @@ -/* -*- Mode: js; js-indent-level: 2; -*- */ -/* - * Copyright 2011 Mozilla Foundation and contributors - * Licensed under the New BSD license. See LICENSE or: - * http://opensource.org/licenses/BSD-3-Clause - */ -if (typeof define !== 'function') { - var define = require('amdefine')(module, require); -} -define(function (require, exports, module) { - - var util = require('../../lib/source-map/util'); - - // This is a test mapping which maps functions from two different files - // (one.js and two.js) to a minified generated source. - // - // Here is one.js: - // - // ONE.foo = function (bar) { - // return baz(bar); - // }; - // - // Here is two.js: - // - // TWO.inc = function (n) { - // return n + 1; - // }; - // - // And here is the generated code (min.js): - // - // ONE.foo=function(a){return baz(a);}; - // TWO.inc=function(a){return a+1;}; - exports.testGeneratedCode = " ONE.foo=function(a){return baz(a);};\n"+ - " TWO.inc=function(a){return a+1;};"; - exports.testMap = { - version: 3, - file: 'min.js', - names: ['bar', 'baz', 'n'], - sources: ['one.js', 'two.js'], - sourceRoot: '/the/root', - mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' - }; - exports.testMapWithSourcesContent = { - version: 3, - file: 'min.js', - names: ['bar', 'baz', 'n'], - sources: ['one.js', 'two.js'], - sourcesContent: [ - ' ONE.foo = function (bar) {\n' + - ' return baz(bar);\n' + - ' };', - ' TWO.inc = function (n) {\n' + - ' return n + 1;\n' + - ' };' - ], - sourceRoot: '/the/root', - mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' - }; - exports.emptyMap = { - version: 3, - file: 'min.js', - names: [], - sources: [], - mappings: '' - }; - - - function assertMapping(generatedLine, generatedColumn, originalSource, - originalLine, originalColumn, name, map, assert, - dontTestGenerated, dontTestOriginal) { - if (!dontTestOriginal) { - var origMapping = map.originalPositionFor({ - line: generatedLine, - column: generatedColumn - }); - assert.equal(origMapping.name, name, - 'Incorrect name, expected ' + JSON.stringify(name) - + ', got ' + JSON.stringify(origMapping.name)); - assert.equal(origMapping.line, originalLine, - 'Incorrect line, expected ' + JSON.stringify(originalLine) - + ', got ' + JSON.stringify(origMapping.line)); - assert.equal(origMapping.column, originalColumn, - 'Incorrect column, expected ' + JSON.stringify(originalColumn) - + ', got ' + JSON.stringify(origMapping.column)); - - var expectedSource; - - if (originalSource && map.sourceRoot && originalSource.indexOf(map.sourceRoot) === 0) { - expectedSource = originalSource; - } else if (originalSource) { - expectedSource = map.sourceRoot - ? util.join(map.sourceRoot, originalSource) - : originalSource; - } else { - expectedSource = null; - } - - assert.equal(origMapping.source, expectedSource, - 'Incorrect source, expected ' + JSON.stringify(expectedSource) - + ', got ' + JSON.stringify(origMapping.source)); - } - - if (!dontTestGenerated) { - var genMapping = map.generatedPositionFor({ - source: originalSource, - line: originalLine, - column: originalColumn - }); - assert.equal(genMapping.line, generatedLine, - 'Incorrect line, expected ' + JSON.stringify(generatedLine) - + ', got ' + JSON.stringify(genMapping.line)); - assert.equal(genMapping.column, generatedColumn, - 'Incorrect column, expected ' + JSON.stringify(generatedColumn) - + ', got ' + JSON.stringify(genMapping.column)); - } - } - exports.assertMapping = assertMapping; - - function assertEqualMaps(assert, actualMap, expectedMap) { - assert.equal(actualMap.version, expectedMap.version, "version mismatch"); - assert.equal(actualMap.file, expectedMap.file, "file mismatch"); - assert.equal(actualMap.names.length, - expectedMap.names.length, - "names length mismatch: " + - actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); - for (var i = 0; i < actualMap.names.length; i++) { - assert.equal(actualMap.names[i], - expectedMap.names[i], - "names[" + i + "] mismatch: " + - actualMap.names.join(", ") + " != " + expectedMap.names.join(", ")); - } - assert.equal(actualMap.sources.length, - expectedMap.sources.length, - "sources length mismatch: " + - actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); - for (var i = 0; i < actualMap.sources.length; i++) { - assert.equal(actualMap.sources[i], - expectedMap.sources[i], - "sources[" + i + "] length mismatch: " + - actualMap.sources.join(", ") + " != " + expectedMap.sources.join(", ")); - } - assert.equal(actualMap.sourceRoot, - expectedMap.sourceRoot, - "sourceRoot mismatch: " + - actualMap.sourceRoot + " != " + expectedMap.sourceRoot); - assert.equal(actualMap.mappings, expectedMap.mappings, - "mappings mismatch:\nActual: " + actualMap.mappings + "\nExpected: " + expectedMap.mappings); - if (actualMap.sourcesContent) { - assert.equal(actualMap.sourcesContent.length, - expectedMap.sourcesContent.length, - "sourcesContent length mismatch"); - for (var i = 0; i < actualMap.sourcesContent.length; i++) { - assert.equal(actualMap.sourcesContent[i], - expectedMap.sourcesContent[i], - "sourcesContent[" + i + "] mismatch"); - } - } - } - exports.assertEqualMaps = assertEqualMaps; - -}); diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/package.json b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/package.json deleted file mode 100644 index 403722821..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "uglify-js", - "description": "JavaScript parser, mangler/compressor and beautifier toolkit", - "homepage": "http://lisperator.net/uglifyjs", - "main": "tools/node.js", - "version": "2.3.6", - "engines": { - "node": ">=0.4.0" - }, - "maintainers": [ - { - "name": "Mihai Bazon", - "email": "mihai.bazon@gmail.com", - "url": "http://lisperator.net/" - } - ], - "repository": { - "type": "git", - "url": "https://github.com/mishoo/UglifyJS2.git" - }, - "dependencies": { - "async": "~0.2.6", - "source-map": "~0.1.7", - "optimist": "~0.3.5" - }, - "bin": { - "uglifyjs": "bin/uglifyjs" - }, - "scripts": { - "test": "node test/run-tests.js" - }, - "readme": "UglifyJS 2\n==========\n[![Build Status](https://travis-ci.org/mishoo/UglifyJS2.png)](https://travis-ci.org/mishoo/UglifyJS2)\n\nUglifyJS is a JavaScript parser, minifier, compressor or beautifier toolkit.\n\nThis page documents the command line utility. For\n[API and internals documentation see my website](http://lisperator.net/uglifyjs/).\nThere's also an\n[in-browser online demo](http://lisperator.net/uglifyjs/#demo) (for Firefox,\nChrome and probably Safari).\n\nInstall\n-------\n\nFirst make sure you have installed the latest version of [node.js](http://nodejs.org/)\n(You may need to restart your computer after this step).\n\nFrom NPM for use as a command line app:\n\n npm install uglify-js -g\n\nFrom NPM for programmatic use:\n\n npm install uglify-js\n\nFrom Git:\n\n git clone git://github.com/mishoo/UglifyJS2.git\n cd UglifyJS2\n npm link .\n\nUsage\n-----\n\n uglifyjs [input files] [options]\n\nUglifyJS2 can take multiple input files. It's recommended that you pass the\ninput files first, then pass the options. UglifyJS will parse input files\nin sequence and apply any compression options. The files are parsed in the\nsame global scope, that is, a reference from a file to some\nvariable/function declared in another file will be matched properly.\n\nIf you want to read from STDIN instead, pass a single dash instead of input\nfiles.\n\nThe available options are:\n\n --source-map Specify an output file where to generate source map.\n [string]\n --source-map-root The path to the original source to be included in the\n source map. [string]\n --source-map-url The path to the source map to be added in //@\n sourceMappingURL. Defaults to the value passed with\n --source-map. [string]\n --in-source-map Input source map, useful if you're compressing JS that was\n generated from some other original code.\n --screw-ie8 Pass this flag if you don't care about full compliance with\n Internet Explorer 6-8 quirks (by default UglifyJS will try\n to be IE-proof).\n -p, --prefix Skip prefix for original filenames that appear in source\n maps. For example -p 3 will drop 3 directories from file\n names and ensure they are relative paths.\n -o, --output Output file (default STDOUT).\n -b, --beautify Beautify output/specify output options. [string]\n -m, --mangle Mangle names/pass mangler options. [string]\n -r, --reserved Reserved names to exclude from mangling.\n -c, --compress Enable compressor/pass compressor options. Pass options\n like -c hoist_vars=false,if_return=false. Use -c with no\n argument to use the default compression options. [string]\n -d, --define Global definitions [string]\n --comments Preserve copyright comments in the output. By default this\n works like Google Closure, keeping JSDoc-style comments\n that contain \"@license\" or \"@preserve\". You can optionally\n pass one of the following arguments to this flag:\n - \"all\" to keep all comments\n - a valid JS regexp (needs to start with a slash) to keep\n only comments that match.\n Note that currently not *all* comments can be kept when\n compression is on, because of dead code removal or\n cascading statements into sequences. [string]\n --stats Display operations run time on STDERR. [boolean]\n --acorn Use Acorn for parsing. [boolean]\n --spidermonkey Assume input files are SpiderMonkey AST format (as JSON).\n [boolean]\n --self Build itself (UglifyJS2) as a library (implies\n --wrap=UglifyJS --export-all) [boolean]\n --wrap Embed everything in a big function, making the “exports”\n and “global” variables available. You need to pass an\n argument to this option to specify the name that your\n module will take when included in, say, a browser.\n [string]\n --export-all Only used when --wrap, this tells UglifyJS to add code to\n automatically export all globals. [boolean]\n --lint Display some scope warnings [boolean]\n -v, --verbose Verbose [boolean]\n -V, --version Print version number and exit. [boolean]\n\nSpecify `--output` (`-o`) to declare the output file. Otherwise the output\ngoes to STDOUT.\n\n## Source map options\n\nUglifyJS2 can generate a source map file, which is highly useful for\ndebugging your compressed JavaScript. To get a source map, pass\n`--source-map output.js.map` (full path to the file where you want the\nsource map dumped).\n\nAdditionally you might need `--source-map-root` to pass the URL where the\noriginal files can be found. In case you are passing full paths to input\nfiles to UglifyJS, you can use `--prefix` (`-p`) to specify the number of\ndirectories to drop from the path prefix when declaring files in the source\nmap.\n\nFor example:\n\n uglifyjs /home/doe/work/foo/src/js/file1.js \\\n /home/doe/work/foo/src/js/file2.js \\\n -o foo.min.js \\\n --source-map foo.min.js.map \\\n --source-map-root http://foo.com/src \\\n -p 5 -c -m\n\nThe above will compress and mangle `file1.js` and `file2.js`, will drop the\noutput in `foo.min.js` and the source map in `foo.min.js.map`. The source\nmapping will refer to `http://foo.com/src/js/file1.js` and\n`http://foo.com/src/js/file2.js` (in fact it will list `http://foo.com/src`\nas the source map root, and the original files as `js/file1.js` and\n`js/file2.js`).\n\n### Composed source map\n\nWhen you're compressing JS code that was output by a compiler such as\nCoffeeScript, mapping to the JS code won't be too helpful. Instead, you'd\nlike to map back to the original code (i.e. CoffeeScript). UglifyJS has an\noption to take an input source map. Assuming you have a mapping from\nCoffeeScript → compiled JS, UglifyJS can generate a map from CoffeeScript →\ncompressed JS by mapping every token in the compiled JS to its original\nlocation.\n\nTo use this feature you need to pass `--in-source-map\n/path/to/input/source.map`. Normally the input source map should also point\nto the file containing the generated JS, so if that's correct you can omit\ninput files from the command line.\n\n## Mangler options\n\nTo enable the mangler you need to pass `--mangle` (`-m`). The following\n(comma-separated) options are supported:\n\n- `sort` — to assign shorter names to most frequently used variables. This\n saves a few hundred bytes on jQuery before gzip, but the output is\n _bigger_ after gzip (and seems to happen for other libraries I tried it\n on) therefore it's not enabled by default.\n\n- `toplevel` — mangle names declared in the toplevel scope (disabled by\n default).\n\n- `eval` — mangle names visible in scopes where `eval` or `when` are used\n (disabled by default).\n\nWhen mangling is enabled but you want to prevent certain names from being\nmangled, you can declare those names with `--reserved` (`-r`) — pass a\ncomma-separated list of names. For example:\n\n uglifyjs ... -m -r '$,require,exports'\n\nto prevent the `require`, `exports` and `$` names from being changed.\n\n## Compressor options\n\nYou need to pass `--compress` (`-c`) to enable the compressor. Optionally\nyou can pass a comma-separated list of options. Options are in the form\n`foo=bar`, or just `foo` (the latter implies a boolean option that you want\nto set `true`; it's effectively a shortcut for `foo=true`).\n\n- `sequences` -- join consecutive simple statements using the comma operator\n- `properties` -- rewrite property access using the dot notation, for\n example `foo[\"bar\"] → foo.bar`\n- `dead_code` -- remove unreachable code\n- `drop_debugger` -- remove `debugger;` statements\n- `unsafe` (default: false) -- apply \"unsafe\" transformations (discussion below)\n- `conditionals` -- apply optimizations for `if`-s and conditional\n expressions\n- `comparisons` -- apply certain optimizations to binary nodes, for example:\n `!(a <= b) → a > b` (only when `unsafe`), attempts to negate binary nodes,\n e.g. `a = !b && !c && !d && !e → a=!(b||c||d||e)` etc.\n- `evaluate` -- attempt to evaluate constant expressions\n- `booleans` -- various optimizations for boolean context, for example `!!a\n ? b : c → a ? b : c`\n- `loops` -- optimizations for `do`, `while` and `for` loops when we can\n statically determine the condition\n- `unused` -- drop unreferenced functions and variables\n- `hoist_funs` -- hoist function declarations\n- `hoist_vars` (default: false) -- hoist `var` declarations (this is `false`\n by default because it seems to increase the size of the output in general)\n- `if_return` -- optimizations for if/return and if/continue\n- `join_vars` -- join consecutive `var` statements\n- `cascade` -- small optimization for sequences, transform `x, x` into `x`\n and `x = something(), x` into `x = something()`\n- `warnings` -- display warnings when dropping unreachable code or unused\n declarations etc.\n\n### The `unsafe` option\n\nIt enables some transformations that *might* break code logic in certain\ncontrived cases, but should be fine for most code. You might want to try it\non your own code, it should reduce the minified size. Here's what happens\nwhen this flag is on:\n\n- `new Array(1, 2, 3)` or `Array(1, 2, 3)` → `[1, 2, 3 ]`\n- `new Object()` → `{}`\n- `String(exp)` or `exp.toString()` → `\"\" + exp`\n- `new Object/RegExp/Function/Error/Array (...)` → we discard the `new`\n- `typeof foo == \"undefined\"` → `foo === void 0`\n- `void 0` → `\"undefined\"` (if there is a variable named \"undefined\" in\n scope; we do it because the variable name will be mangled, typically\n reduced to a single character).\n\n### Conditional compilation\n\nYou can use the `--define` (`-d`) switch in order to declare global\nvariables that UglifyJS will assume to be constants (unless defined in\nscope). For example if you pass `--define DEBUG=false` then, coupled with\ndead code removal UglifyJS will discard the following from the output:\n```javascript\nif (DEBUG) {\n\tconsole.log(\"debug stuff\");\n}\n```\n\nUglifyJS will warn about the condition being always false and about dropping\nunreachable code; for now there is no option to turn off only this specific\nwarning, you can pass `warnings=false` to turn off *all* warnings.\n\nAnother way of doing that is to declare your globals as constants in a\nseparate file and include it into the build. For example you can have a\n`build/defines.js` file with the following:\n```javascript\nconst DEBUG = false;\nconst PRODUCTION = true;\n// etc.\n```\n\nand build your code like this:\n\n uglifyjs build/defines.js js/foo.js js/bar.js... -c\n\nUglifyJS will notice the constants and, since they cannot be altered, it\nwill evaluate references to them to the value itself and drop unreachable\ncode as usual. The possible downside of this approach is that the build\nwill contain the `const` declarations.\n\n\n## Beautifier options\n\nThe code generator tries to output shortest code possible by default. In\ncase you want beautified output, pass `--beautify` (`-b`). Optionally you\ncan pass additional arguments that control the code output:\n\n- `beautify` (default `true`) -- whether to actually beautify the output.\n Passing `-b` will set this to true, but you might need to pass `-b` even\n when you want to generate minified code, in order to specify additional\n arguments, so you can use `-b beautify=false` to override it.\n- `indent-level` (default 4)\n- `indent-start` (default 0) -- prefix all lines by that many spaces\n- `quote-keys` (default `false`) -- pass `true` to quote all keys in literal\n objects\n- `space-colon` (default `true`) -- insert a space after the colon signs\n- `ascii-only` (default `false`) -- escape Unicode characters in strings and\n regexps\n- `inline-script` (default `false`) -- escape the slash in occurrences of\n `= (x = f(…)) - * - * For example, let the equation be: - * (a = parseInt('100')) <= a - * - * If a was an integer and has the value of 99, - * (a = parseInt('100')) <= a → 100 <= 100 → true - * - * When transformed incorrectly: - * a >= (a = parseInt('100')) → 99 >= 100 → false - */ - -tranformation_sort_order_equal: { - options = { - comparisons: true, - }; - - input: { (a = parseInt('100')) == a } - expect: { (a = parseInt('100')) == a } -} - -tranformation_sort_order_unequal: { - options = { - comparisons: true, - }; - - input: { (a = parseInt('100')) != a } - expect: { (a = parseInt('100')) != a } -} - -tranformation_sort_order_lesser_or_equal: { - options = { - comparisons: true, - }; - - input: { (a = parseInt('100')) <= a } - expect: { (a = parseInt('100')) <= a } -} -tranformation_sort_order_greater_or_equal: { - options = { - comparisons: true, - }; - - input: { (a = parseInt('100')) >= a } - expect: { (a = parseInt('100')) >= a } -} \ No newline at end of file diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-22.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-22.js deleted file mode 100644 index a8b7bc600..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-22.js +++ /dev/null @@ -1,17 +0,0 @@ -return_with_no_value_in_if_body: { - options = { conditionals: true }; - input: { - function foo(bar) { - if (bar) { - return; - } else { - return 1; - } - } - } - expect: { - function foo (bar) { - return bar ? void 0 : 1; - } - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-44.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-44.js deleted file mode 100644 index 7a972f9ea..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-44.js +++ /dev/null @@ -1,31 +0,0 @@ -issue_44_valid_ast_1: { - options = { unused: true }; - input: { - function a(b) { - for (var i = 0, e = b.qoo(); ; i++) {} - } - } - expect: { - function a(b) { - var i = 0; - for (b.qoo(); ; i++); - } - } -} - -issue_44_valid_ast_2: { - options = { unused: true }; - input: { - function a(b) { - if (foo) for (var i = 0, e = b.qoo(); ; i++) {} - } - } - expect: { - function a(b) { - if (foo) { - var i = 0; - for (b.qoo(); ; i++); - } - } - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-59.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-59.js deleted file mode 100644 index 82b388067..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/issue-59.js +++ /dev/null @@ -1,30 +0,0 @@ -keep_continue: { - options = { - dead_code: true, - evaluate: true - }; - input: { - while (a) { - if (b) { - switch (true) { - case c(): - d(); - } - continue; - } - f(); - } - } - expect: { - while (a) { - if (b) { - switch (true) { - case c(): - d(); - } - continue; - } - f(); - } - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/labels.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/labels.js deleted file mode 100644 index 044b7a7ea..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/labels.js +++ /dev/null @@ -1,163 +0,0 @@ -labels_1: { - options = { if_return: true, conditionals: true, dead_code: true }; - input: { - out: { - if (foo) break out; - console.log("bar"); - } - }; - expect: { - foo || console.log("bar"); - } -} - -labels_2: { - options = { if_return: true, conditionals: true, dead_code: true }; - input: { - out: { - if (foo) print("stuff"); - else break out; - console.log("here"); - } - }; - expect: { - if (foo) { - print("stuff"); - console.log("here"); - } - } -} - -labels_3: { - options = { if_return: true, conditionals: true, dead_code: true }; - input: { - for (var i = 0; i < 5; ++i) { - if (i < 3) continue; - console.log(i); - } - }; - expect: { - for (var i = 0; i < 5; ++i) - i < 3 || console.log(i); - } -} - -labels_4: { - options = { if_return: true, conditionals: true, dead_code: true }; - input: { - out: for (var i = 0; i < 5; ++i) { - if (i < 3) continue out; - console.log(i); - } - }; - expect: { - for (var i = 0; i < 5; ++i) - i < 3 || console.log(i); - } -} - -labels_5: { - options = { if_return: true, conditionals: true, dead_code: true }; - // should keep the break-s in the following - input: { - while (foo) { - if (bar) break; - console.log("foo"); - } - out: while (foo) { - if (bar) break out; - console.log("foo"); - } - }; - expect: { - while (foo) { - if (bar) break; - console.log("foo"); - } - out: while (foo) { - if (bar) break out; - console.log("foo"); - } - } -} - -labels_6: { - input: { - out: break out; - }; - expect: {} -} - -labels_7: { - options = { if_return: true, conditionals: true, dead_code: true }; - input: { - while (foo) { - x(); - y(); - continue; - } - }; - expect: { - while (foo) { - x(); - y(); - } - } -} - -labels_8: { - options = { if_return: true, conditionals: true, dead_code: true }; - input: { - while (foo) { - x(); - y(); - break; - } - }; - expect: { - while (foo) { - x(); - y(); - break; - } - } -} - -labels_9: { - options = { if_return: true, conditionals: true, dead_code: true }; - input: { - out: while (foo) { - x(); - y(); - continue out; - z(); - k(); - } - }; - expect: { - while (foo) { - x(); - y(); - } - } -} - -labels_10: { - options = { if_return: true, conditionals: true, dead_code: true }; - input: { - out: while (foo) { - x(); - y(); - break out; - z(); - k(); - } - }; - expect: { - out: while (foo) { - x(); - y(); - break out; - } - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/loops.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/loops.js deleted file mode 100644 index cdf1f045d..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/loops.js +++ /dev/null @@ -1,123 +0,0 @@ -while_becomes_for: { - options = { loops: true }; - input: { - while (foo()) bar(); - } - expect: { - for (; foo(); ) bar(); - } -} - -drop_if_break_1: { - options = { loops: true }; - input: { - for (;;) - if (foo()) break; - } - expect: { - for (; !foo();); - } -} - -drop_if_break_2: { - options = { loops: true }; - input: { - for (;bar();) - if (foo()) break; - } - expect: { - for (; bar() && !foo();); - } -} - -drop_if_break_3: { - options = { loops: true }; - input: { - for (;bar();) { - if (foo()) break; - stuff1(); - stuff2(); - } - } - expect: { - for (; bar() && !foo();) { - stuff1(); - stuff2(); - } - } -} - -drop_if_break_4: { - options = { loops: true, sequences: true }; - input: { - for (;bar();) { - x(); - y(); - if (foo()) break; - z(); - k(); - } - } - expect: { - for (; bar() && (x(), y(), !foo());) z(), k(); - } -} - -drop_if_else_break_1: { - options = { loops: true }; - input: { - for (;;) if (foo()) bar(); else break; - } - expect: { - for (; foo(); ) bar(); - } -} - -drop_if_else_break_2: { - options = { loops: true }; - input: { - for (;bar();) { - if (foo()) baz(); - else break; - } - } - expect: { - for (; bar() && foo();) baz(); - } -} - -drop_if_else_break_3: { - options = { loops: true }; - input: { - for (;bar();) { - if (foo()) baz(); - else break; - stuff1(); - stuff2(); - } - } - expect: { - for (; bar() && foo();) { - baz(); - stuff1(); - stuff2(); - } - } -} - -drop_if_else_break_4: { - options = { loops: true, sequences: true }; - input: { - for (;bar();) { - x(); - y(); - if (foo()) baz(); - else break; - z(); - k(); - } - } - expect: { - for (; bar() && (x(), y(), foo());) baz(), z(), k(); - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/properties.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/properties.js deleted file mode 100644 index 85045961e..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/properties.js +++ /dev/null @@ -1,54 +0,0 @@ -keep_properties: { - options = { - properties: false - }; - input: { - a["foo"] = "bar"; - } - expect: { - a["foo"] = "bar"; - } -} - -dot_properties: { - options = { - properties: true - }; - input: { - a["foo"] = "bar"; - a["if"] = "if"; - a["*"] = "asterisk"; - a["\u0EB3"] = "unicode"; - a[""] = "whitespace"; - a["1_1"] = "foo"; - } - expect: { - a.foo = "bar"; - a["if"] = "if"; - a["*"] = "asterisk"; - a.\u0EB3 = "unicode"; - a[""] = "whitespace"; - a["1_1"] = "foo"; - } -} - -dot_properties_es5: { - options = { - properties: true, - screw_ie8: true - }; - input: { - a["foo"] = "bar"; - a["if"] = "if"; - a["*"] = "asterisk"; - a["\u0EB3"] = "unicode"; - a[""] = "whitespace"; - } - expect: { - a.foo = "bar"; - a.if = "if"; - a["*"] = "asterisk"; - a.\u0EB3 = "unicode"; - a[""] = "whitespace"; - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/sequences.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/sequences.js deleted file mode 100644 index 6f63ace47..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/sequences.js +++ /dev/null @@ -1,161 +0,0 @@ -make_sequences_1: { - options = { - sequences: true - }; - input: { - foo(); - bar(); - baz(); - } - expect: { - foo(),bar(),baz(); - } -} - -make_sequences_2: { - options = { - sequences: true - }; - input: { - if (boo) { - foo(); - bar(); - baz(); - } else { - x(); - y(); - z(); - } - } - expect: { - if (boo) foo(),bar(),baz(); - else x(),y(),z(); - } -} - -make_sequences_3: { - options = { - sequences: true - }; - input: { - function f() { - foo(); - bar(); - return baz(); - } - function g() { - foo(); - bar(); - throw new Error(); - } - } - expect: { - function f() { - return foo(), bar(), baz(); - } - function g() { - throw foo(), bar(), new Error(); - } - } -} - -make_sequences_4: { - options = { - sequences: true - }; - input: { - x = 5; - if (y) z(); - - x = 5; - for (i = 0; i < 5; i++) console.log(i); - - x = 5; - for (; i < 5; i++) console.log(i); - - x = 5; - switch (y) {} - - x = 5; - with (obj) {} - } - expect: { - if (x = 5, y) z(); - for (x = 5, i = 0; i < 5; i++) console.log(i); - for (x = 5; i < 5; i++) console.log(i); - switch (x = 5, y) {} - with (x = 5, obj); - } -} - -lift_sequences_1: { - options = { sequences: true }; - input: { - foo = !(x(), y(), bar()); - } - expect: { - x(), y(), foo = !bar(); - } -} - -lift_sequences_2: { - options = { sequences: true, evaluate: true }; - input: { - q = 1 + (foo(), bar(), 5) + 7 * (5 / (3 - (a(), (QW=ER), c(), 2))) - (x(), y(), 5); - } - expect: { - foo(), bar(), a(), QW = ER, c(), x(), y(), q = 36 - } -} - -lift_sequences_3: { - options = { sequences: true, conditionals: true }; - input: { - x = (foo(), bar(), baz()) ? 10 : 20; - } - expect: { - foo(), bar(), x = baz() ? 10 : 20; - } -} - -lift_sequences_4: { - options = { side_effects: true }; - input: { - x = (foo, bar, baz); - } - expect: { - x = baz; - } -} - -for_sequences: { - options = { sequences: true }; - input: { - // 1 - foo(); - bar(); - for (; false;); - // 2 - foo(); - bar(); - for (x = 5; false;); - // 3 - x = (foo in bar); - for (; false;); - // 4 - x = (foo in bar); - for (y = 5; false;); - } - expect: { - // 1 - for (foo(), bar(); false;); - // 2 - for (foo(), bar(), x = 5; false;); - // 3 - x = (foo in bar); - for (; false;); - // 4 - x = (foo in bar); - for (y = 5; false;); - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/switch.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/switch.js deleted file mode 100644 index 62e39cf7b..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/switch.js +++ /dev/null @@ -1,260 +0,0 @@ -constant_switch_1: { - options = { dead_code: true, evaluate: true }; - input: { - switch (1+1) { - case 1: foo(); break; - case 1+1: bar(); break; - case 1+1+1: baz(); break; - } - } - expect: { - bar(); - } -} - -constant_switch_2: { - options = { dead_code: true, evaluate: true }; - input: { - switch (1) { - case 1: foo(); - case 1+1: bar(); break; - case 1+1+1: baz(); - } - } - expect: { - foo(); - bar(); - } -} - -constant_switch_3: { - options = { dead_code: true, evaluate: true }; - input: { - switch (10) { - case 1: foo(); - case 1+1: bar(); break; - case 1+1+1: baz(); - default: - def(); - } - } - expect: { - def(); - } -} - -constant_switch_4: { - options = { dead_code: true, evaluate: true }; - input: { - switch (2) { - case 1: - x(); - if (foo) break; - y(); - break; - case 1+1: - bar(); - default: - def(); - } - } - expect: { - bar(); - def(); - } -} - -constant_switch_5: { - options = { dead_code: true, evaluate: true }; - input: { - switch (1) { - case 1: - x(); - if (foo) break; - y(); - break; - case 1+1: - bar(); - default: - def(); - } - } - expect: { - // the break inside the if ruins our job - // we can still get rid of irrelevant cases. - switch (1) { - case 1: - x(); - if (foo) break; - y(); - } - // XXX: we could optimize this better by inventing an outer - // labeled block, but that's kinda tricky. - } -} - -constant_switch_6: { - options = { dead_code: true, evaluate: true }; - input: { - OUT: { - foo(); - switch (1) { - case 1: - x(); - if (foo) break OUT; - y(); - case 1+1: - bar(); - break; - default: - def(); - } - } - } - expect: { - OUT: { - foo(); - x(); - if (foo) break OUT; - y(); - bar(); - } - } -} - -constant_switch_7: { - options = { dead_code: true, evaluate: true }; - input: { - OUT: { - foo(); - switch (1) { - case 1: - x(); - if (foo) break OUT; - for (var x = 0; x < 10; x++) { - if (x > 5) break; // this break refers to the for, not to the switch; thus it - // shouldn't ruin our optimization - console.log(x); - } - y(); - case 1+1: - bar(); - break; - default: - def(); - } - } - } - expect: { - OUT: { - foo(); - x(); - if (foo) break OUT; - for (var x = 0; x < 10; x++) { - if (x > 5) break; - console.log(x); - } - y(); - bar(); - } - } -} - -constant_switch_8: { - options = { dead_code: true, evaluate: true }; - input: { - OUT: switch (1) { - case 1: - x(); - for (;;) break OUT; - y(); - break; - case 1+1: - bar(); - default: - def(); - } - } - expect: { - OUT: { - x(); - for (;;) break OUT; - y(); - } - } -} - -constant_switch_9: { - options = { dead_code: true, evaluate: true }; - input: { - OUT: switch (1) { - case 1: - x(); - for (;;) if (foo) break OUT; - y(); - case 1+1: - bar(); - default: - def(); - } - } - expect: { - OUT: { - x(); - for (;;) if (foo) break OUT; - y(); - bar(); - def(); - } - } -} - -drop_default_1: { - options = { dead_code: true }; - input: { - switch (foo) { - case 'bar': baz(); - default: - } - } - expect: { - switch (foo) { - case 'bar': baz(); - } - } -} - -drop_default_2: { - options = { dead_code: true }; - input: { - switch (foo) { - case 'bar': baz(); break; - default: - break; - } - } - expect: { - switch (foo) { - case 'bar': baz(); - } - } -} - -keep_default: { - options = { dead_code: true }; - input: { - switch (foo) { - case 'bar': baz(); - default: - something(); - break; - } - } - expect: { - switch (foo) { - case 'bar': baz(); - default: - something(); - } - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/typeof.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/typeof.js deleted file mode 100644 index cefdd43c2..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/compress/typeof.js +++ /dev/null @@ -1,25 +0,0 @@ -typeof_evaluation: { - options = { - evaluate: true - }; - input: { - a = typeof 1; - b = typeof 'test'; - c = typeof []; - d = typeof {}; - e = typeof /./; - f = typeof false; - g = typeof function(){}; - h = typeof undefined; - } - expect: { - a='number'; - b='string'; - c=typeof[]; - d=typeof{}; - e=typeof/./; - f='boolean'; - g='function'; - h='undefined'; - } -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/run-tests.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/run-tests.js deleted file mode 100644 index 0568c6a7a..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/test/run-tests.js +++ /dev/null @@ -1,170 +0,0 @@ -#! /usr/bin/env node - -var U = require("../tools/node"); -var path = require("path"); -var fs = require("fs"); -var assert = require("assert"); -var sys = require("util"); - -var tests_dir = path.dirname(module.filename); - -run_compress_tests(); - -/* -----[ utils ]----- */ - -function tmpl() { - return U.string_template.apply(this, arguments); -} - -function log() { - var txt = tmpl.apply(this, arguments); - sys.puts(txt); -} - -function log_directory(dir) { - log("*** Entering [{dir}]", { dir: dir }); -} - -function log_start_file(file) { - log("--- {file}", { file: file }); -} - -function log_test(name) { - log(" Running test [{name}]", { name: name }); -} - -function find_test_files(dir) { - var files = fs.readdirSync(dir).filter(function(name){ - return /\.js$/i.test(name); - }); - if (process.argv.length > 2) { - var x = process.argv.slice(2); - files = files.filter(function(f){ - return x.indexOf(f) >= 0; - }); - } - return files; -} - -function test_directory(dir) { - return path.resolve(tests_dir, dir); -} - -function as_toplevel(input) { - if (input instanceof U.AST_BlockStatement) input = input.body; - else if (input instanceof U.AST_Statement) input = [ input ]; - else throw new Error("Unsupported input syntax"); - var toplevel = new U.AST_Toplevel({ body: input }); - toplevel.figure_out_scope(); - return toplevel; -} - -function run_compress_tests() { - var dir = test_directory("compress"); - log_directory("compress"); - var files = find_test_files(dir); - function test_file(file) { - log_start_file(file); - function test_case(test) { - log_test(test.name); - var options = U.defaults(test.options, { - warnings: false - }); - var cmp = new U.Compressor(options, true); - var expect = make_code(as_toplevel(test.expect), false); - var input = as_toplevel(test.input); - var input_code = make_code(test.input); - var output = input.transform(cmp); - output.figure_out_scope(); - output = make_code(output, false); - if (expect != output) { - log("!!! failed\n---INPUT---\n{input}\n---OUTPUT---\n{output}\n---EXPECTED---\n{expected}\n\n", { - input: input_code, - output: output, - expected: expect - }); - } - } - var tests = parse_test(path.resolve(dir, file)); - for (var i in tests) if (tests.hasOwnProperty(i)) { - test_case(tests[i]); - } - } - files.forEach(function(file){ - test_file(file); - }); -} - -function parse_test(file) { - var script = fs.readFileSync(file, "utf8"); - var ast = U.parse(script, { - filename: file - }); - var tests = {}; - var tw = new U.TreeWalker(function(node, descend){ - if (node instanceof U.AST_LabeledStatement - && tw.parent() instanceof U.AST_Toplevel) { - var name = node.label.name; - tests[name] = get_one_test(name, node.body); - return true; - } - if (!(node instanceof U.AST_Toplevel)) croak(node); - }); - ast.walk(tw); - return tests; - - function croak(node) { - throw new Error(tmpl("Can't understand test file {file} [{line},{col}]\n{code}", { - file: file, - line: node.start.line, - col: node.start.col, - code: make_code(node, false) - })); - } - - function get_one_test(name, block) { - var test = { name: name, options: {} }; - var tw = new U.TreeWalker(function(node, descend){ - if (node instanceof U.AST_Assign) { - if (!(node.left instanceof U.AST_SymbolRef)) { - croak(node); - } - var name = node.left.name; - test[name] = evaluate(node.right); - return true; - } - if (node instanceof U.AST_LabeledStatement) { - assert.ok( - node.label.name == "input" || node.label.name == "expect", - tmpl("Unsupported label {name} [{line},{col}]", { - name: node.label.name, - line: node.label.start.line, - col: node.label.start.col - }) - ); - var stat = node.body; - if (stat instanceof U.AST_BlockStatement) { - if (stat.body.length == 1) stat = stat.body[0]; - else if (stat.body.length == 0) stat = new U.AST_EmptyStatement(); - } - test[node.label.name] = stat; - return true; - } - }); - block.walk(tw); - return test; - }; -} - -function make_code(ast, beautify) { - if (arguments.length == 1) beautify = true; - var stream = U.OutputStream({ beautify: beautify }); - ast.print(stream); - return stream.get(); -} - -function evaluate(code) { - if (code instanceof U.AST_Node) - code = make_code(code); - return new Function("return(" + code + ")")(); -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/tools/node.js b/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/tools/node.js deleted file mode 100644 index c0dd3dbc4..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/node_modules/uglify-js/tools/node.js +++ /dev/null @@ -1,165 +0,0 @@ -var path = require("path"); -var fs = require("fs"); -var vm = require("vm"); -var sys = require("util"); - -var UglifyJS = vm.createContext({ - sys : sys, - console : console, - MOZ_SourceMap : require("source-map") -}); - -function load_global(file) { - file = path.resolve(path.dirname(module.filename), file); - try { - var code = fs.readFileSync(file, "utf8"); - return vm.runInContext(code, UglifyJS, file); - } catch(ex) { - // XXX: in case of a syntax error, the message is kinda - // useless. (no location information). - sys.debug("ERROR in file: " + file + " / " + ex); - process.exit(1); - } -}; - -var FILES = exports.FILES = [ - "../lib/utils.js", - "../lib/ast.js", - "../lib/parse.js", - "../lib/transform.js", - "../lib/scope.js", - "../lib/output.js", - "../lib/compress.js", - "../lib/sourcemap.js", - "../lib/mozilla-ast.js" -].map(function(file){ - return path.join(path.dirname(fs.realpathSync(__filename)), file); -}); - -FILES.forEach(load_global); - -UglifyJS.AST_Node.warn_function = function(txt) { - sys.error("WARN: " + txt); -}; - -// XXX: perhaps we shouldn't export everything but heck, I'm lazy. -for (var i in UglifyJS) { - if (UglifyJS.hasOwnProperty(i)) { - exports[i] = UglifyJS[i]; - } -} - -exports.minify = function(files, options) { - options = UglifyJS.defaults(options, { - outSourceMap : null, - sourceRoot : null, - inSourceMap : null, - fromString : false, - warnings : false, - mangle : {}, - output : null, - compress : {} - }); - if (typeof files == "string") - files = [ files ]; - - // 1. parse - var toplevel = null; - files.forEach(function(file){ - var code = options.fromString - ? file - : fs.readFileSync(file, "utf8"); - toplevel = UglifyJS.parse(code, { - filename: options.fromString ? "?" : file, - toplevel: toplevel - }); - }); - - // 2. compress - if (options.compress) { - var compress = { warnings: options.warnings }; - UglifyJS.merge(compress, options.compress); - toplevel.figure_out_scope(); - var sq = UglifyJS.Compressor(compress); - toplevel = toplevel.transform(sq); - } - - // 3. mangle - if (options.mangle) { - toplevel.figure_out_scope(); - toplevel.compute_char_frequency(); - toplevel.mangle_names(options.mangle); - } - - // 4. output - var inMap = options.inSourceMap; - var output = {}; - if (typeof options.inSourceMap == "string") { - inMap = fs.readFileSync(options.inSourceMap, "utf8"); - } - if (options.outSourceMap) { - output.source_map = UglifyJS.SourceMap({ - file: options.outSourceMap, - orig: inMap, - root: options.sourceRoot - }); - } - if (options.output) { - UglifyJS.merge(output, options.output); - } - var stream = UglifyJS.OutputStream(output); - toplevel.print(stream); - return { - code : stream + "", - map : output.source_map + "" - }; -}; - -// exports.describe_ast = function() { -// function doitem(ctor) { -// var sub = {}; -// ctor.SUBCLASSES.forEach(function(ctor){ -// sub[ctor.TYPE] = doitem(ctor); -// }); -// var ret = {}; -// if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS; -// if (ctor.SUBCLASSES.length > 0) ret.sub = sub; -// return ret; -// } -// return doitem(UglifyJS.AST_Node).sub; -// } - -exports.describe_ast = function() { - var out = UglifyJS.OutputStream({ beautify: true }); - function doitem(ctor) { - out.print("AST_" + ctor.TYPE); - var props = ctor.SELF_PROPS.filter(function(prop){ - return !/^\$/.test(prop); - }); - if (props.length > 0) { - out.space(); - out.with_parens(function(){ - props.forEach(function(prop, i){ - if (i) out.space(); - out.print(prop); - }); - }); - } - if (ctor.documentation) { - out.space(); - out.print_string(ctor.documentation); - } - if (ctor.SUBCLASSES.length > 0) { - out.space(); - out.with_block(function(){ - ctor.SUBCLASSES.forEach(function(ctor, i){ - out.indent(); - doitem(ctor); - out.newline(); - }); - }); - } - }; - doitem(UglifyJS.AST_Node); - return out + ""; -}; diff --git a/node_modules/express3-handlebars/node_modules/handlebars/package.json b/node_modules/express3-handlebars/node_modules/handlebars/package.json deleted file mode 100644 index 1292c6018..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "handlebars", - "barename": "handlebars", - "version": "1.3.0", - "description": "Handlebars provides the power necessary to let you build semantic templates effectively with no frustration", - "homepage": "http://www.handlebarsjs.com/", - "keywords": [ - "handlebars", - "mustache", - "template", - "html" - ], - "repository": { - "type": "git", - "url": "https://github.com/wycats/handlebars.js.git" - }, - "author": { - "name": "Yehuda Katz" - }, - "license": "MIT", - "readmeFilename": "README.markdown", - "engines": { - "node": ">=0.4.7" - }, - "dependencies": { - "optimist": "~0.3", - "uglify-js": "~2.3" - }, - "optionalDependencies": { - "uglify-js": "~2.3" - }, - "devDependencies": { - "async": "~0.2.9", - "aws-sdk": "~1.5.0", - "benchmark": "~1.0", - "dustjs-linkedin": "~2.0.2", - "eco": "~1.1.0-rc-3", - "grunt": "~0.4.1", - "grunt-cli": "~0.1.10", - "grunt-contrib-clean": "~0.4.1", - "grunt-contrib-concat": "~0.3.0", - "grunt-contrib-connect": "~0.5.0", - "grunt-contrib-copy": "~0.4.1", - "grunt-contrib-jshint": "0.x", - "grunt-contrib-requirejs": "~0.4.1", - "grunt-contrib-uglify": "~0.2.2", - "grunt-contrib-watch": "~0.5.3", - "grunt-saucelabs": "~4.1.2", - "es6-module-packager": "0.x", - "jison": "~0.3.0", - "keen.io": "0.0.3", - "mocha": "*", - "mustache": "~0.7.2", - "semver": "~2.1.0", - "underscore": "~1.5.1" - }, - "main": "lib/index.js", - "bin": { - "handlebars": "bin/handlebars" - }, - "scripts": { - "test": "grunt" - }, - "readme": "[![Travis Build Status](https://travis-ci.org/wycats/handlebars.js.png?branch=master)](https://travis-ci.org/wycats/handlebars.js)\n[![Selenium Test Status](https://saucelabs.com/buildstatus/handlebars)](https://saucelabs.com/u/handlebars)\n\nHandlebars.js\n=============\n\nHandlebars.js is an extension to the [Mustache templating\nlanguage](http://mustache.github.com/) created by Chris Wanstrath.\nHandlebars.js and Mustache are both logicless templating languages that\nkeep the view and the code separated like we all know they should be.\n\nCheckout the official Handlebars docs site at\n[http://www.handlebarsjs.com](http://www.handlebarsjs.com).\n\nInstalling\n----------\nInstalling Handlebars is easy. Simply download the package [from the official site](http://handlebarsjs.com/) or the [bower repository][bower-repo] and add it to your web pages (you should usually use the most recent version).\n\nAlternatively, if you prefer having the latest version of handlebars from\nthe 'master' branch, passing builds of the 'master' branch are automatically\npublished to S3. You may download the latest passing master build by grabbing\na `handlebars-latest.js` file from the [builds page][builds-page]. When the\nbuild is published, it is also available as a `handlebars-gitSHA.js` file on\nthe builds page if you need a version to refer to others.\n`handlebars-runtime.js` builds are also available.\n\n**Note**: The S3 builds page is provided as a convenience for the community,\nbut you should not use it for hosting Handlebars in production.\n\nUsage\n-----\nIn general, the syntax of Handlebars.js templates is a superset\nof Mustache templates. For basic syntax, check out the [Mustache\nmanpage](http://mustache.github.com/mustache.5.html).\n\nOnce you have a template, use the `Handlebars.compile` method to compile\nthe template into a function. The generated function takes a context\nargument, which will be used to render the template.\n\n```js\nvar source = \"

    Hello, my name is {{name}}. I am from {{hometown}}. I have \" +\n \"{{kids.length}} kids:

    \" +\n \"
      {{#kids}}
    • {{name}} is {{age}}
    • {{/kids}}
    \";\nvar template = Handlebars.compile(source);\n\nvar data = { \"name\": \"Alan\", \"hometown\": \"Somewhere, TX\",\n \"kids\": [{\"name\": \"Jimmy\", \"age\": \"12\"}, {\"name\": \"Sally\", \"age\": \"4\"}]};\nvar result = template(data);\n\n// Would render:\n//

    Hello, my name is Alan. I am from Somewhere, TX. I have 2 kids:

    \n//
      \n//
    • Jimmy is 12
    • \n//
    • Sally is 4
    • \n//
    \n```\n\n\nRegistering Helpers\n-------------------\n\nYou can register helpers that Handlebars will use when evaluating your\ntemplate. Here's an example, which assumes that your objects have a URL\nembedded in them, as well as the text for a link:\n\n```js\nHandlebars.registerHelper('link_to', function() {\n return \"\" + this.body + \"\";\n});\n\nvar context = { posts: [{url: \"/hello-world\", body: \"Hello World!\"}] };\nvar source = \"
      {{#posts}}
    • {{{link_to}}}
    • {{/posts}}
    \"\n\nvar template = Handlebars.compile(source);\ntemplate(context);\n\n// Would render:\n//\n// \n```\n\nHelpers take precedence over fields defined on the context. To access a field\nthat is masked by a helper, a path reference may be used. In the example above\na field named `link_to` on the `context` object would be referenced using:\n\n```\n{{./link_to}}\n```\n\nEscaping\n--------\n\nBy default, the `{{expression}}` syntax will escape its contents. This\nhelps to protect you against accidental XSS problems caused by malicious\ndata passed from the server as JSON.\n\nTo explicitly *not* escape the contents, use the triple-mustache\n(`{{{}}}`). You have seen this used in the above example.\n\n\nDifferences Between Handlebars.js and Mustache\n----------------------------------------------\nHandlebars.js adds a couple of additional features to make writing\ntemplates easier and also changes a tiny detail of how partials work.\n\n### Paths\n\nHandlebars.js supports an extended expression syntax that we call paths.\nPaths are made up of typical expressions and . characters. Expressions\nallow you to not only display data from the current context, but to\ndisplay data from contexts that are descendants and ancestors of the\ncurrent context.\n\nTo display data from descendant contexts, use the `.` character. So, for\nexample, if your data were structured like:\n\n```js\nvar data = {\"person\": { \"name\": \"Alan\" }, \"company\": {\"name\": \"Rad, Inc.\" } };\n```\n\nYou could display the person's name from the top-level context with the\nfollowing expression:\n\n```\n{{person.name}}\n```\n\nYou can backtrack using `../`. For example, if you've already traversed\ninto the person object you could still display the company's name with\nan expression like `{{../company.name}}`, so:\n\n```\n{{#person}}{{name}} - {{../company.name}}{{/person}}\n```\n\nwould render:\n\n```\nAlan - Rad, Inc.\n```\n\n### Strings\n\nWhen calling a helper, you can pass paths or Strings as parameters. For\ninstance:\n\n```js\nHandlebars.registerHelper('link_to', function(title, options) {\n return \"\" + title + \"!\"\n});\n\nvar context = { posts: [{url: \"/hello-world\", body: \"Hello World!\"}] };\nvar source = '
      {{#posts}}
    • {{{link_to \"Post\"}}}
    • {{/posts}}
    '\n\nvar template = Handlebars.compile(source);\ntemplate(context);\n\n// Would render:\n//\n// \n```\n\nWhen you pass a String as a parameter to a helper, the literal String\ngets passed to the helper function.\n\n\n### Block Helpers\n\nHandlebars.js also adds the ability to define block helpers. Block\nhelpers are functions that can be called from anywhere in the template.\nHere's an example:\n\n```js\nvar source = \"
      {{#people}}
    • {{#link}}{{name}}{{/link}}
    • {{/people}}
    \";\nHandlebars.registerHelper('link', function(options) {\n return '' + options.fn(this) + '';\n});\nvar template = Handlebars.compile(source);\n\nvar data = { \"people\": [\n { \"name\": \"Alan\", \"id\": 1 },\n { \"name\": \"Yehuda\", \"id\": 2 }\n ]};\ntemplate(data);\n\n// Should render:\n// \n```\n\nWhenever the block helper is called it is given one or more parameters,\nany arguments that are passed in the helper in the call and an `options`\nobject containing the `fn` function which executes the block's child.\nThe block's current context may be accessed through `this`.\n\nBlock helpers have the same syntax as mustache sections but should not be\nconfused with one another. Sections are akin to an implicit `each` or\n`with` statement depending on the input data and helpers are explicit\npieces of code that are free to implement whatever behavior they like.\nThe [mustache spec](http://mustache.github.io/mustache.5.html)\ndefines the exact behavior of sections. In the case of name conflicts,\nhelpers are given priority.\n\n### Partials\n\nYou can register additional templates as partials, which will be used by\nHandlebars when it encounters a partial (`{{> partialName}}`). Partials\ncan either be String templates or compiled template functions. Here's an\nexample:\n\n```js\nvar source = \"
      {{#people}}
    • {{> link}}
    • {{/people}}
    \";\n\nHandlebars.registerPartial('link', '{{name}}')\nvar template = Handlebars.compile(source);\n\nvar data = { \"people\": [\n { \"name\": \"Alan\", \"id\": 1 },\n { \"name\": \"Yehuda\", \"id\": 2 }\n ]};\n\ntemplate(data);\n\n// Should render:\n// \n```\n\n### Comments\n\nYou can add comments to your templates with the following syntax:\n\n```js\n{{! This is a comment }}\n```\n\nYou can also use real html comments if you want them to end up in the output.\n\n```html\n
    \n {{! This comment will not end up in the output }}\n \n
    \n```\n\n\nPrecompiling Templates\n----------------------\n\nHandlebars allows templates to be precompiled and included as javascript\ncode rather than the handlebars template allowing for faster startup time.\n\n### Installation\nThe precompiler script may be installed via npm using the `npm install -g handlebars`\ncommand.\n\n### Usage\n\n
    \nPrecompile handlebar templates.\nUsage: handlebars template...\n\nOptions:\n  -a, --amd            Create an AMD format function (allows loading with RequireJS)          [boolean]\n  -f, --output         Output File                                                            [string]\n  -k, --known          Known helpers                                                          [string]\n  -o, --knownOnly      Known helpers only                                                     [boolean]\n  -m, --min            Minimize output                                                        [boolean]\n  -s, --simple         Output template function only.                                         [boolean]\n  -r, --root           Template root. Base value that will be stripped from template names.   [string]\n  -c, --commonjs       Exports CommonJS style, path to Handlebars module                      [string]\n  -h, --handlebarPath  Path to handlebar.js (only valid for amd-style)                        [string]\n  -n, --namespace      Template namespace                                                     [string]\n  -p, --partial        Compiling a partial template                                           [boolean]\n  -d, --data           Include data when compiling                                            [boolean]\n  -e, --extension      Template extension.                                                    [string]\n  -b, --bom            Removes the BOM (Byte Order Mark) from the beginning of the templates. [boolean]\n
    \n\nIf using the precompiler's normal mode, the resulting templates will be\nstored to the `Handlebars.templates` object using the relative template\nname sans the extension. These templates may be executed in the same\nmanner as templates.\n\nIf using the simple mode the precompiler will generate a single\njavascript method. To execute this method it must be passed to the using\nthe `Handlebars.template` method and the resulting object may be as\nnormal.\n\n### Optimizations\n\n- Rather than using the full _handlebars.js_ library, implementations that\n do not need to compile templates at runtime may include _handlebars.runtime.js_\n whose min+gzip size is approximately 1k.\n- If a helper is known to exist in the target environment they may be defined\n using the `--known name` argument may be used to optimize accesses to these\n helpers for size and speed.\n- When all helpers are known in advance the `--knownOnly` argument may be used\n to optimize all block helper references.\n- Implementations that do not use `@data` variables can improve performance of\n iteration centric templates by specifying `{data: false}` in the compiler options.\n\nSupported Environments\n----------------------\n\nHandlebars has been designed to work in any ECMAScript 3 environment. This includes\n\n- Node.js\n- Chrome\n- Firefox\n- Safari 5+\n- Opera 11+\n- IE 6+\n\nOlder versions and other runtimes are likely to work but have not been formally\ntested.\n\n[![Selenium Test Status](https://saucelabs.com/browser-matrix/handlebars.svg)](https://saucelabs.com/u/handlebars)\n\nPerformance\n-----------\n\nIn a rough performance test, precompiled Handlebars.js templates (in\nthe original version of Handlebars.js) rendered in about half the\ntime of Mustache templates. It would be a shame if it were any other\nway, since they were precompiled, but the difference in architecture\ndoes have some big performance advantages. Justin Marney, a.k.a.\n[gotascii](http://github.com/gotascii), confirmed that with an\n[independent test](http://sorescode.com/2010/09/12/benchmarks.html). The\nrewritten Handlebars (current version) is faster than the old version,\nand we will have some benchmarks in the near future.\n\n\nBuilding\n--------\n\nTo build handlebars, just run `grunt build`, and the build will output to the `dist` directory.\n\n\nUpgrading\n---------\n\nSee [release-notes.md](https://github.com/wycats/handlebars.js/blob/master/release-notes.md) for upgrade notes.\n\nKnown Issues\n------------\n* Handlebars.js can be cryptic when there's an error while rendering.\n* Using a variable, helper, or partial named `class` causes errors in IE browsers. (Instead, use `className`)\n\nHandlebars in the Wild\n----------------------\n\n* [Assemble](http://assemble.io), by [@jonschlinkert](https://github.com/jonschlinkert)\n and [@doowb](https://github.com/doowb), is a static site generator that uses Handlebars.js\n as its template engine.\n* [CoSchedule](http://coschedule.com) An editorial calendar for WordPress that uses Handlebars.js\n* [Ember.js](http://www.emberjs.com) makes Handlebars.js the primary way to\n structure your views, also with automatic data binding support.\n* [Ghost](https://ghost.org/) Just a blogging platform.\n* [handlebars_assets](http://github.com/leshill/handlebars_assets): A Rails Asset Pipeline gem\n from Les Hill (@leshill).\n* [handlebars-helpers](https://github.com/assemble/handlebars-helpers) is an extensive library\n with 100+ handlebars helpers.\n* [hbs](http://github.com/donpark/hbs): An Express.js view engine adapter for Handlebars.js,\n from Don Park.\n* [jblotus](http://github.com/jblotus) created [http://tryhandlebarsjs.com](http://tryhandlebarsjs.com)\n for anyone who would like to try out Handlebars.js in their browser.\n* [jQuery plugin](http://71104.github.io/jquery-handlebars/): allows you to use\n Handlebars.js with [jQuery](http://jquery.com/).\n* [Lumbar](http://walmartlabs.github.io/lumbar) provides easy module-based template management for\n handlebars projects.\n* [sammy.js](http://github.com/quirkey/sammy) by Aaron Quint, a.k.a. quirkey,\n supports Handlebars.js as one of its template plugins.\n* [SproutCore](http://www.sproutcore.com) uses Handlebars.js as its main\n templating engine, extending it with automatic data binding support.\n* [YUI](http://yuilibrary.com/yui/docs/handlebars/) implements a port of handlebars\n* [Swag](https://github.com/elving/swag) by [@elving](https://github.com/elving) is a growing collection of helpers for handlebars.js. Give your handlebars.js templates some swag son!\n* [DOMBars](https://github.com/blakeembrey/dombars) is a DOM-based templating engine built on the Handlebars parser and runtime\n\nExternal Resources\n------------------\n\n* [Gist about Synchronous and asynchronous loading of external handlebars templates](https://gist.github.com/2287070)\n\nHave a project using Handlebars? Send us a [pull request][pull-request]!\n\nHelping Out\n-----------\n\nTo build Handlebars.js you'll need a few things installed.\n\n* Node.js\n* [Grunt](http://gruntjs.com/getting-started)\n\nProject dependencies may be installed via `npm install`.\n\nTo build Handlebars.js from scratch, you'll want to run `grunt`\nin the root of the project. That will build Handlebars and output the\nresults to the dist/ folder. To re-run tests, run `grunt test` or `npm test`.\nYou can also run our set of benchmarks with `grunt bench`.\n\nThe `grunt dev` implements watching for tests and allows for in browser testing at `http://localhost:9999/spec/`.\n\nIf you notice any problems, please report them to the GitHub issue tracker at\n[http://github.com/wycats/handlebars.js/issues](http://github.com/wycats/handlebars.js/issues).\nFeel free to contact commondream or wycats through GitHub with any other\nquestions or feature requests. To submit changes fork the project and\nsend a pull request.\n\n### Ember testing\n\nThe current ember distribution should be tested as part of the handlebars release process. This requires building the `handlebars-source` gem locally and then executing the ember test script.\n\n```sh\ngrunt build release\nexport HANDLEBARS_PATH=`pwd`\n\ncd $emberRepoDir\nbundle exec rake clean\nbundle exec rake test\n```\n\n### Releasing\n\nHandlebars utilizes the [release yeoman generator][generator-release] to perform most release tasks.\n\nA full release may be completed with the following:\n\n```\nyo release:notes patch\nyo release:release patch\nnpm publish\nyo release:publish cdnjs handlebars.js dist/cdnjs/\nyo release:publish components handlebars.js dist/components/\n\ncd dist/components/\ngem build handlebars-source.gemspec\ngem push handlebars-source-*.gem\n```\n\nAfter this point the handlebars site needs to be updated to point to the new version numbers.\n\nLicense\n-------\nHandlebars.js is released under the MIT license.\n\n[bower-repo]: https://github.com/components/handlebars.js\n[builds-page]: http://builds.handlebarsjs.com.s3.amazonaws.com/bucket-listing.html?sort=lastmod&sortdir=desc\n[generator-release]: https://github.com/walmartlabs/generator-release\n[pull-request]: https://github.com/wycats/handlebars.js/pull/new/master\n", - "bugs": { - "url": "https://github.com/wycats/handlebars.js/issues" - }, - "_id": "handlebars@1.3.0", - "_from": "handlebars@1.x" -} diff --git a/node_modules/express3-handlebars/node_modules/handlebars/release-notes.md b/node_modules/express3-handlebars/node_modules/handlebars/release-notes.md deleted file mode 100644 index 3f0fac995..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/release-notes.md +++ /dev/null @@ -1,193 +0,0 @@ -# Release Notes - -## Development - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.3.0...master) - -## v1.3.0 - January 1st, 2014 -- [#690](https://github.com/wycats/handlebars.js/pull/690) - Added support for subexpressions ([@machty](https://api.github.com/users/machty)) -- [#696](https://github.com/wycats/handlebars.js/pull/696) - Fix for reserved keyword "default" ([@nateirwin](https://api.github.com/users/nateirwin)) -- [#692](https://github.com/wycats/handlebars.js/pull/692) - add line numbers to nodes when parsing ([@fivetanley](https://api.github.com/users/fivetanley)) -- [#695](https://github.com/wycats/handlebars.js/pull/695) - Pull options out from param setup to allow easier extension ([@blakeembrey](https://api.github.com/users/blakeembrey)) -- [#694](https://github.com/wycats/handlebars.js/pull/694) - Make the environment reusable ([@blakeembrey](https://api.github.com/users/blakeembrey)) -- [#636](https://github.com/wycats/handlebars.js/issues/636) - Print line and column of errors ([@sgronblo](https://api.github.com/users/sgronblo)) -- Use literal for data lookup - c1a93d3 -- Add stack handling sanity checks - cd885bf -- Fix stack id "leak" on replaceStack - ddfe457 -- Fix incorrect stack pop when replacing literals - f4d337d - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.2.1...v1.3.0) - -## v1.2.1 - December 26th, 2013 -- [#684](https://github.com/wycats/handlebars.js/pull/684) - Allow any number of trailing characters for valid JavaScript variable ([@blakeembrey](https://api.github.com/users/blakeembrey)) -- [#686](https://github.com/wycats/handlebars.js/pull/686) - Falsy AMD module names in version 1.2.0 ([@kpdecker](https://api.github.com/users/kpdecker)) - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.2.0...v1.2.1) - -## v1.2.0 - December 23rd, 2013 -- [#675](https://github.com/wycats/handlebars.js/issues/675) - Cannot compile empty template for partial ([@erwinw](https://api.github.com/users/erwinw)) -- [#677](https://github.com/wycats/handlebars.js/issues/677) - Triple brace statements fail under IE ([@hamzaCM](https://api.github.com/users/hamzaCM)) -- [#655](https://github.com/wycats/handlebars.js/issues/655) - Loading Handlebars using bower ([@niki4810](https://api.github.com/users/niki4810)) -- [#657](https://github.com/wycats/handlebars.js/pull/657) - Fixes issue where cli compiles non handlebars templates ([@chrishoage](https://api.github.com/users/chrishoage)) -- [#681](https://github.com/wycats/handlebars.js/pull/681) - Adds in-browser testing and Saucelabs CI ([@kpdecker](https://api.github.com/users/kpdecker)) -- [#661](https://github.com/wycats/handlebars.js/pull/661) - Add @first and @index to #each object iteration ([@cgp](https://api.github.com/users/cgp)) -- [#650](https://github.com/wycats/handlebars.js/pull/650) - Handlebars is MIT-licensed ([@thomasboyt](https://api.github.com/users/thomasboyt)) -- [#641](https://github.com/wycats/handlebars.js/pull/641) - Document ember testing process ([@kpdecker](https://api.github.com/users/kpdecker)) -- [#662](https://github.com/wycats/handlebars.js/issues/662) - handlebars-source 1.1.2 is missing from RubyGems. -- [#656](https://github.com/wycats/handlebars.js/issues/656) - Expose COMPILER_REVISION checks as a hook ([@machty](https://api.github.com/users/machty)) -- [#668](https://github.com/wycats/handlebars.js/issues/668) - Consider publishing handlebars-runtime as a separate module on npm ([@dlmanning](https://api.github.com/users/dlmanning)) -- [#679](https://github.com/wycats/handlebars.js/issues/679) - Unable to override invokePartial ([@mattbrailsford](https://api.github.com/users/mattbrailsford)) -- [#646](https://github.com/wycats/handlebars.js/pull/646) - Fix "\\{{" immediately following "\{{" ([@dmarcotte](https://api.github.com/users/dmarcotte)) -- Allow extend to work with non-prototyped objects - eb53f2e -- Add JavascriptCompiler public API tests - 1a751b2 -- Add AST test coverage for more complex paths - ddea5be -- Fix handling of boolean escape in MustacheNode - b4968bb - -Compatibility notes: -- `@index` and `@first` are now supported for `each` iteration on objects -- `Handlebars.VM.checkRevision` and `Handlebars.JavaScriptCompiler.prototype.compilerInfo` now available to modify the version checking behavior. -- Browserify users may link to the runtime library via `require('handlebars/runtime')` - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.1.2...v1.2.0) - -## v1.1.2 - November 5th, 2013 - -- [#645](https://github.com/wycats/handlebars.js/issues/645) - 1.1.1 fails under IE8 ([@kpdecker](https://api.github.com/users/kpdecker)) -- [#644](https://github.com/wycats/handlebars.js/issues/644) - Using precompiled templates (AMD mode) with handlebars.runtime 1.1.1 ([@fddima](https://api.github.com/users/fddima)) - -- Add simple binary utility tests - 96a45a4 -- Fix empty string compilation - eea708a - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.1.1...v1.1.2) - -## v1.1.1 - November 4th, 2013 - -- [#642](https://github.com/wycats/handlebars.js/issues/642) - handlebars 1.1.0 are broken with nodejs - -- Fix release notes link - 17ba258 - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.1.0...v1.1.1) - -## v1.1.0 - November 3rd, 2013 - -- [#628](https://github.com/wycats/handlebars.js/pull/628) - Convert code to ES6 modules ([@kpdecker](https://api.github.com/users/kpdecker)) -- [#336](https://github.com/wycats/handlebars.js/pull/336) - Add whitespace control syntax ([@kpdecker](https://api.github.com/users/kpdecker)) -- [#535](https://github.com/wycats/handlebars.js/pull/535) - Fix for probable JIT error under Safari ([@sorentwo](https://api.github.com/users/sorentwo)) -- [#483](https://github.com/wycats/handlebars.js/issues/483) - Add first and last @ vars to each helper ([@denniskuczynski](https://api.github.com/users/denniskuczynski)) -- [#557](https://github.com/wycats/handlebars.js/pull/557) - `\\{{foo}}` escaping only works in some situations ([@dmarcotte](https://api.github.com/users/dmarcotte)) -- [#552](https://github.com/wycats/handlebars.js/pull/552) - Added BOM removal flag. ([@blessenm](https://api.github.com/users/blessenm)) -- [#543](https://github.com/wycats/handlebars.js/pull/543) - publish passing master builds to s3 ([@fivetanley](https://api.github.com/users/fivetanley)) - -- [#608](https://github.com/wycats/handlebars.js/issues/608) - Add `includeZero` flag to `if` conditional -- [#498](https://github.com/wycats/handlebars.js/issues/498) - `Handlebars.compile` fails on empty string although a single blank works fine -- [#599](https://github.com/wycats/handlebars.js/issues/599) - lambda helpers only receive options if used with arguments -- [#592](https://github.com/wycats/handlebars.js/issues/592) - Optimize array and subprogram performance -- [#571](https://github.com/wycats/handlebars.js/issues/571) - uglify upgrade breaks compatibility with older versions of node -- [#587](https://github.com/wycats/handlebars.js/issues/587) - Partial inside partial breaks? - - -Compatibility notes: -- The project now includes separate artifacts for AMD, CommonJS, and global objects. - - AMD: Users may load the bundled `handlebars.amd.js` or `handlebars.runtime.amd.js` files or load individual modules directly. AMD users should also note that the handlebars object is exposed via the `default` field on the imported object. This [gist](https://gist.github.com/wycats/7417be0dc361a69d5916) provides some discussion of possible compatibility shims. - - CommonJS/Node: Node loading occurs as normal via `require` - - Globals: The `handlebars.js` and `handlebars.runtime.js` files should behave in the same manner as the v1.0.12 / 1.0.0 release. -- Build artifacts have been removed from the repository. [npm][npm], [components/handlebars.js][components], [cdnjs][cdnjs], or the [builds page][builds-page] should now be used as the source of built artifacts. -- Context-stored helpers are now always passed the `options` hash. Previously no-argument helpers did not have this argument. - - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.0.12...v1.1.0) - -## v1.0.12 / 1.0.0 - May 31 2013 - -- [#515](https://github.com/wycats/handlebars.js/issues/515) - Add node require extensions support ([@jjclark1982](https://github.com/jjclark1982)) -- [#517](https://github.com/wycats/handlebars.js/issues/517) - Fix amd precompiler output with directories ([@blessenm](https://github.com/blessenm)) -- [#433](https://github.com/wycats/handlebars.js/issues/433) - Add support for unicode ids -- [#469](https://github.com/wycats/handlebars.js/issues/469) - Add support for `?` in ids -- [#534](https://github.com/wycats/handlebars.js/issues/534) - Protect from object prototype modifications -- [#519](https://github.com/wycats/handlebars.js/issues/519) - Fix partials with . name ([@jamesgorrie](https://github.com/jamesgorrie)) -- [#519](https://github.com/wycats/handlebars.js/issues/519) - Allow ID or strings in partial names -- [#437](https://github.com/wycats/handlebars.js/issues/437) - Require matching brace counts in escaped expressions -- Merge passed partials and helpers with global namespace values -- Add support for complex ids in @data references -- Docs updates - -Compatibility notes: -- The parser is now stricter on `{{{`, requiring that the end token be `}}}`. Templates that do not - follow this convention should add the additional brace value. -- Code that relies on global the namespace being muted when custom helpers or partials are passed will need to explicitly pass an `undefined` value for any helpers that should not be available. -- The compiler version has changed. Precompiled templates with 1.0.12 or higher must use the 1.0.0 or higher runtime. - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.0.11...v1.0.12) - -## v1.0.11 / 1.0.0-rc4 - May 13 2013 - -- [#458](https://github.com/wycats/handlebars.js/issues/458) - Fix `./foo` syntax ([@jpfiset](https://github.com/jpfiset)) -- [#460](https://github.com/wycats/handlebars.js/issues/460) - Allow `:` in unescaped identifers ([@jpfiset](https://github.com/jpfiset)) -- [#471](https://github.com/wycats/handlebars.js/issues/471) - Create release notes (These!) -- [#456](https://github.com/wycats/handlebars.js/issues/456) - Allow escaping of `\\` -- [#211](https://github.com/wycats/handlebars.js/issues/211) - Fix exception in `escapeExpression` -- [#375](https://github.com/wycats/handlebars.js/issues/375) - Escape unicode newlines -- [#461](https://github.com/wycats/handlebars.js/issues/461) - Do not fail when compiling `""` -- [#302](https://github.com/wycats/handlebars.js/issues/302) - Fix sanity check in knownHelpersOnly mode -- [#369](https://github.com/wycats/handlebars.js/issues/369) - Allow registration of multiple helpers and partial by passing definition object -- Add bower package declaration ([@DevinClark](https://github.com/DevinClark)) -- Add NuSpec package declaration ([@MikeMayer](https://github.com/MikeMayer)) -- Handle empty context in `with` ([@thejohnfreeman](https://github.com/thejohnfreeman)) -- Support custom template extensions in CLI ([@matteoagosti](https://github.com/matteoagosti)) -- Fix Rhino support ([@broady](https://github.com/broady)) -- Include contexts in string mode ([@leshill](https://github.com/leshill)) -- Return precompiled scripts when compiling to AMD ([@JamesMaroney](https://github.com/JamesMaroney)) -- Docs updates ([@iangreenleaf](https://github.com/iangreenleaf), [@gilesbowkett](https://github.com/gilesbowkett), [@utkarsh2012](https://github.com/utkarsh2012)) -- Fix `toString` handling under IE and browserify ([@tommydudebreaux](https://github.com/tommydudebreaux)) -- Add program metadata - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.0.10...v1.0.11) - -## v1.0.10 - Node - Feb 27 2013 - -- [#428](https://github.com/wycats/handlebars.js/issues/428) - Fix incorrect rendering of nested programs -- Fix exception message ([@tricknotes](https://github.com/tricknotes)) -- Added negative number literal support -- Concert library to single IIFE -- Add handlebars-source gemspec ([@machty](https://github.com/machty)) - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.0.9...v1.0.10) - -## v1.0.9 - Node - Feb 15 2013 - -- Added `Handlebars.create` API in node module for sandboxed instances ([@tommydudebreaux](https://github.com/tommydudebreaux)) - -[Commits](https://github.com/wycats/handlebars.js/compare/1.0.0-rc.3...v1.0.9) - -## 1.0.0-rc3 - Browser - Feb 14 2013 - -- Prevent use of `this` or `..` in illogical place ([@leshill](https://github.com/leshill)) -- Allow AST passing for `parse`/`compile`/`precompile` ([@machty](https://github.com/machty)) -- Optimize generated output by inlining statements where possible -- Check compiler version when evaluating templates -- Package browser dist in npm package - -[Commits](https://github.com/wycats/handlebars.js/compare/v1.0.8...1.0.0-rc.3) - -## Prior Versions - -When upgrading from the Handlebars 0.9 series, be aware that the -signature for passing custom helpers or partials to templates has -changed. - -Instead of: - -```js -template(context, helpers, partials, [data]) -``` - -Use: - -```js -template(context, {helpers: helpers, partials: partials, data: data}) -``` - -[builds-page]: http://builds.handlebarsjs.com.s3.amazonaws.com/index.html -[cdnjs]: http://cdnjs.com/libraries/handlebars.js/ -[components]: https://github.com/components/handlebars.js -[npm]: https://npmjs.org/package/handlebars diff --git a/node_modules/express3-handlebars/node_modules/handlebars/runtime.js b/node_modules/express3-handlebars/node_modules/handlebars/runtime.js deleted file mode 100644 index b7a7b12eb..000000000 --- a/node_modules/express3-handlebars/node_modules/handlebars/runtime.js +++ /dev/null @@ -1,3 +0,0 @@ -// Create a simple path alias to allow browserify to resolve -// the runtime on a supported path. -module.exports = require('./dist/cjs/handlebars.runtime'); diff --git a/node_modules/express3-handlebars/node_modules/semver/.npmignore b/node_modules/express3-handlebars/node_modules/semver/.npmignore deleted file mode 100644 index 7300fbc79..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/.npmignore +++ /dev/null @@ -1 +0,0 @@ -# nada diff --git a/node_modules/express3-handlebars/node_modules/semver/LICENSE b/node_modules/express3-handlebars/node_modules/semver/LICENSE deleted file mode 100644 index 0c44ae716..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) Isaac Z. Schlueter ("Author") -All rights reserved. - -The BSD License - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/express3-handlebars/node_modules/semver/Makefile b/node_modules/express3-handlebars/node_modules/semver/Makefile deleted file mode 100644 index 5717ccf42..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/Makefile +++ /dev/null @@ -1,24 +0,0 @@ -files = semver.browser.js \ - semver.min.js \ - semver.browser.js.gz \ - semver.min.js.gz - -all: $(files) - -clean: - rm -f $(files) - -semver.browser.js: head.js semver.js foot.js - ( cat head.js; \ - cat semver.js | \ - egrep -v '^ *\/\* nomin \*\/' | \ - perl -pi -e 's/debug\([^\)]+\)//g'; \ - cat foot.js ) > semver.browser.js - -semver.min.js: semver.browser.js - uglifyjs -m semver.min.js - -%.gz: % - gzip --stdout -9 <$< >$@ - -.PHONY: all clean diff --git a/node_modules/express3-handlebars/node_modules/semver/README.md b/node_modules/express3-handlebars/node_modules/semver/README.md deleted file mode 100644 index ef0465981..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/README.md +++ /dev/null @@ -1,142 +0,0 @@ -semver(1) -- The semantic versioner for npm -=========================================== - -## Usage - - $ npm install semver - - semver.valid('1.2.3') // '1.2.3' - semver.valid('a.b.c') // null - semver.clean(' =v1.2.3 ') // '1.2.3' - semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true - semver.gt('1.2.3', '9.8.7') // false - semver.lt('1.2.3', '9.8.7') // true - -As a command-line utility: - - $ semver -h - - Usage: semver [ [...]] [-r | -i | -d ] - Test if version(s) satisfy the supplied range(s), and sort them. - - Multiple versions or ranges may be supplied, unless increment - or decrement options are specified. In that case, only a single - version may be used, and it is incremented by the specified level - - Program exits successfully if any valid version satisfies - all supplied ranges, and prints all satisfying versions. - - If no versions are valid, or ranges are not satisfied, - then exits failure. - - Versions are printed in ascending order, so supplying - multiple versions to the utility will just sort them. - -## Versions - -A "version" is described by the v2.0.0 specification found at -. - -A leading `"="` or `"v"` character is stripped off and ignored. - -## Ranges - -The following range styles are supported: - -* `1.2.3` A specific version. When nothing else will do. Note that - build metadata is still ignored, so `1.2.3+build2012` will satisfy - this range. -* `>1.2.3` Greater than a specific version. -* `<1.2.3` Less than a specific version. If there is no prerelease - tag on the version range, then no prerelease version will be allowed - either, even though these are technically "less than". -* `>=1.2.3` Greater than or equal to. Note that prerelease versions - are NOT equal to their "normal" equivalents, so `1.2.3-beta` will - not satisfy this range, but `2.3.0-beta` will. -* `<=1.2.3` Less than or equal to. In this case, prerelease versions - ARE allowed, so `1.2.3-beta` would satisfy. -* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` -* `~1.2.3` := `>=1.2.3-0 <1.3.0-0` "Reasonably close to 1.2.3". When - using tilde operators, prerelease versions are supported as well, - but a prerelease of the next significant digit will NOT be - satisfactory, so `1.3.0-beta` will not satisfy `~1.2.3`. -* `^1.2.3` := `>=1.2.3-0 <2.0.0-0` "Compatible with 1.2.3". When - using caret operators, anything from the specified version (including - prerelease) will be supported up to, but not including, the next - major version (or its prereleases). `1.5.1` will satisfy `^1.2.3`, - while `1.2.2` and `2.0.0-beta` will not. -* `^0.1.3` := `>=0.1.3-0 <0.2.0-0` "Compatible with 0.1.3". 0.x.x versions are - special: the first non-zero component indicates potentially breaking changes, - meaning the caret operator matches any version with the same first non-zero - component starting at the specified version. -* `^0.0.2` := `=0.0.2` "Only the version 0.0.2 is considered compatible" -* `~1.2` := `>=1.2.0-0 <1.3.0-0` "Any version starting with 1.2" -* `^1.2` := `>=1.2.0-0 <2.0.0-0` "Any version compatible with 1.2" -* `1.2.x` := `>=1.2.0-0 <1.3.0-0` "Any version starting with 1.2" -* `~1` := `>=1.0.0-0 <2.0.0-0` "Any version starting with 1" -* `^1` := `>=1.0.0-0 <2.0.0-0` "Any version compatible with 1" -* `1.x` := `>=1.0.0-0 <2.0.0-0` "Any version starting with 1" - - -Ranges can be joined with either a space (which implies "and") or a -`||` (which implies "or"). - -## Functions - -All methods and classes take a final `loose` boolean argument that, if -true, will be more forgiving about not-quite-valid semver strings. -The resulting output will always be 100% strict, of course. - -Strict-mode Comparators and Ranges will be strict about the SemVer -strings that they parse. - -* valid(v): Return the parsed version, or null if it's not valid. -* inc(v, release): Return the version incremented by the release type - (major, minor, patch, or prerelease), or null if it's not valid. - -### Comparison - -* gt(v1, v2): `v1 > v2` -* gte(v1, v2): `v1 >= v2` -* lt(v1, v2): `v1 < v2` -* lte(v1, v2): `v1 <= v2` -* eq(v1, v2): `v1 == v2` This is true if they're logically equivalent, - even if they're not the exact same string. You already know how to - compare strings. -* neq(v1, v2): `v1 != v2` The opposite of eq. -* cmp(v1, comparator, v2): Pass in a comparison string, and it'll call - the corresponding function above. `"==="` and `"!=="` do simple - string comparison, but are included for completeness. Throws if an - invalid comparison string is provided. -* compare(v1, v2): Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if - v2 is greater. Sorts in ascending order if passed to Array.sort(). -* rcompare(v1, v2): The reverse of compare. Sorts an array of versions - in descending order when passed to Array.sort(). - - -### Ranges - -* validRange(range): Return the valid range or null if it's not valid -* satisfies(version, range): Return true if the version satisfies the - range. -* maxSatisfying(versions, range): Return the highest version in the list - that satisfies the range, or null if none of them do. -* gtr(version, range): Return true if version is greater than all the - versions possible in the range. -* ltr(version, range): Return true if version is less than all the - versions possible in the range. -* outside(version, range, hilo): Return true if the version is outside - the bounds of the range in either the high or low direction. The - `hilo` argument must be either the string `'>'` or `'<'`. (This is - the function called by `gtr` and `ltr`.) - -Note that, since ranges may be non-contiguous, a version might not be -greater than a range, less than a range, *or* satisfy a range! For -example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9` -until `2.0.0`, so the version `1.2.10` would not be greater than the -range (because 2.0.1 satisfies, which is higher), nor less than the -range (since 1.2.8 satisfies, which is lower), and it also does not -satisfy the range. - -If you want to know if a version satisfies or does not satisfy a -range, use the `satisfies(version, range)` function. diff --git a/node_modules/express3-handlebars/node_modules/semver/bin/semver b/node_modules/express3-handlebars/node_modules/semver/bin/semver deleted file mode 100644 index 88b4c7d31..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/bin/semver +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env node -// Standalone semver comparison program. -// Exits successfully and prints matching version(s) if -// any supplied version is valid and passes all tests. - -var argv = process.argv.slice(2) - , versions = [] - , range = [] - , gt = [] - , lt = [] - , eq = [] - , inc = null - , version = require("../package.json").version - , loose = false - , semver = require("../semver") - , reverse = false - -main() - -function main () { - if (!argv.length) return help() - while (argv.length) { - var a = argv.shift() - var i = a.indexOf('=') - if (i !== -1) { - a = a.slice(0, i) - argv.unshift(a.slice(i + 1)) - } - switch (a) { - case "-rv": case "-rev": case "--rev": case "--reverse": - reverse = true - break - case "-l": case "--loose": - loose = true - break - case "-v": case "--version": - versions.push(argv.shift()) - break - case "-i": case "--inc": case "--increment": - switch (argv[0]) { - case "major": case "minor": case "patch": case "prerelease": - inc = argv.shift() - break - default: - inc = "patch" - break - } - break - case "-r": case "--range": - range.push(argv.shift()) - break - case "-h": case "--help": case "-?": - return help() - default: - versions.push(a) - break - } - } - - versions = versions.filter(function (v) { - return semver.valid(v, loose) - }) - if (!versions.length) return fail() - if (inc && (versions.length !== 1 || range.length)) - return failInc() - - for (var i = 0, l = range.length; i < l ; i ++) { - versions = versions.filter(function (v) { - return semver.satisfies(v, range[i], loose) - }) - if (!versions.length) return fail() - } - return success(versions) -} - -function failInc () { - console.error("--inc can only be used on a single version with no range") - fail() -} - -function fail () { process.exit(1) } - -function success () { - var compare = reverse ? "rcompare" : "compare" - versions.sort(function (a, b) { - return semver[compare](a, b, loose) - }).map(function (v) { - return semver.clean(v, loose) - }).map(function (v) { - return inc ? semver.inc(v, inc, loose) : v - }).forEach(function (v,i,_) { console.log(v) }) -} - -function help () { - console.log(["SemVer " + version - ,"" - ,"A JavaScript implementation of the http://semver.org/ specification" - ,"Copyright Isaac Z. Schlueter" - ,"" - ,"Usage: semver [options] [ [...]]" - ,"Prints valid versions sorted by SemVer precedence" - ,"" - ,"Options:" - ,"-r --range " - ," Print versions that match the specified range." - ,"" - ,"-i --increment []" - ," Increment a version by the specified level. Level can" - ," be one of: major, minor, patch, or prerelease" - ," Default level is 'patch'." - ," Only one version may be specified." - ,"" - ,"-l --loose" - ," Interpret versions and ranges loosely" - ,"" - ,"Program exits successfully if any valid version satisfies" - ,"all supplied ranges, and prints all satisfying versions." - ,"" - ,"If no satisfying versions are found, then exits failure." - ,"" - ,"Versions are printed in ascending order, so supplying" - ,"multiple versions to the utility will just sort them." - ].join("\n")) -} diff --git a/node_modules/express3-handlebars/node_modules/semver/foot.js b/node_modules/express3-handlebars/node_modules/semver/foot.js deleted file mode 100644 index 8f83c20f8..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/foot.js +++ /dev/null @@ -1,6 +0,0 @@ - -})( - typeof exports === 'object' ? exports : - typeof define === 'function' && define.amd ? {} : - semver = {} -); diff --git a/node_modules/express3-handlebars/node_modules/semver/head.js b/node_modules/express3-handlebars/node_modules/semver/head.js deleted file mode 100644 index 653686517..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/head.js +++ /dev/null @@ -1,2 +0,0 @@ -;(function(exports) { - diff --git a/node_modules/express3-handlebars/node_modules/semver/package.json b/node_modules/express3-handlebars/node_modules/semver/package.json deleted file mode 100644 index 8b28a9af9..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "semver", - "version": "2.2.1", - "description": "The semantic version parser used by npm.", - "main": "semver.js", - "browser": "semver.browser.js", - "min": "semver.min.js", - "scripts": { - "test": "tap test/*.js", - "prepublish": "make" - }, - "devDependencies": { - "tap": "0.x >=0.0.4", - "uglify-js": "~2.3.6" - }, - "license": "BSD", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-semver.git" - }, - "bin": { - "semver": "./bin/semver" - }, - "readme": "semver(1) -- The semantic versioner for npm\n===========================================\n\n## Usage\n\n $ npm install semver\n\n semver.valid('1.2.3') // '1.2.3'\n semver.valid('a.b.c') // null\n semver.clean(' =v1.2.3 ') // '1.2.3'\n semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true\n semver.gt('1.2.3', '9.8.7') // false\n semver.lt('1.2.3', '9.8.7') // true\n\nAs a command-line utility:\n\n $ semver -h\n\n Usage: semver [ [...]] [-r | -i | -d ]\n Test if version(s) satisfy the supplied range(s), and sort them.\n\n Multiple versions or ranges may be supplied, unless increment\n or decrement options are specified. In that case, only a single\n version may be used, and it is incremented by the specified level\n\n Program exits successfully if any valid version satisfies\n all supplied ranges, and prints all satisfying versions.\n\n If no versions are valid, or ranges are not satisfied,\n then exits failure.\n\n Versions are printed in ascending order, so supplying\n multiple versions to the utility will just sort them.\n\n## Versions\n\nA \"version\" is described by the v2.0.0 specification found at\n.\n\nA leading `\"=\"` or `\"v\"` character is stripped off and ignored.\n\n## Ranges\n\nThe following range styles are supported:\n\n* `1.2.3` A specific version. When nothing else will do. Note that\n build metadata is still ignored, so `1.2.3+build2012` will satisfy\n this range.\n* `>1.2.3` Greater than a specific version.\n* `<1.2.3` Less than a specific version. If there is no prerelease\n tag on the version range, then no prerelease version will be allowed\n either, even though these are technically \"less than\".\n* `>=1.2.3` Greater than or equal to. Note that prerelease versions\n are NOT equal to their \"normal\" equivalents, so `1.2.3-beta` will\n not satisfy this range, but `2.3.0-beta` will.\n* `<=1.2.3` Less than or equal to. In this case, prerelease versions\n ARE allowed, so `1.2.3-beta` would satisfy.\n* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`\n* `~1.2.3` := `>=1.2.3-0 <1.3.0-0` \"Reasonably close to 1.2.3\". When\n using tilde operators, prerelease versions are supported as well,\n but a prerelease of the next significant digit will NOT be\n satisfactory, so `1.3.0-beta` will not satisfy `~1.2.3`.\n* `^1.2.3` := `>=1.2.3-0 <2.0.0-0` \"Compatible with 1.2.3\". When\n using caret operators, anything from the specified version (including\n prerelease) will be supported up to, but not including, the next\n major version (or its prereleases). `1.5.1` will satisfy `^1.2.3`,\n while `1.2.2` and `2.0.0-beta` will not.\n* `^0.1.3` := `>=0.1.3-0 <0.2.0-0` \"Compatible with 0.1.3\". 0.x.x versions are\n special: the first non-zero component indicates potentially breaking changes,\n meaning the caret operator matches any version with the same first non-zero\n component starting at the specified version.\n* `^0.0.2` := `=0.0.2` \"Only the version 0.0.2 is considered compatible\"\n* `~1.2` := `>=1.2.0-0 <1.3.0-0` \"Any version starting with 1.2\"\n* `^1.2` := `>=1.2.0-0 <2.0.0-0` \"Any version compatible with 1.2\"\n* `1.2.x` := `>=1.2.0-0 <1.3.0-0` \"Any version starting with 1.2\"\n* `~1` := `>=1.0.0-0 <2.0.0-0` \"Any version starting with 1\"\n* `^1` := `>=1.0.0-0 <2.0.0-0` \"Any version compatible with 1\"\n* `1.x` := `>=1.0.0-0 <2.0.0-0` \"Any version starting with 1\"\n\n\nRanges can be joined with either a space (which implies \"and\") or a\n`||` (which implies \"or\").\n\n## Functions\n\nAll methods and classes take a final `loose` boolean argument that, if\ntrue, will be more forgiving about not-quite-valid semver strings.\nThe resulting output will always be 100% strict, of course.\n\nStrict-mode Comparators and Ranges will be strict about the SemVer\nstrings that they parse.\n\n* valid(v): Return the parsed version, or null if it's not valid.\n* inc(v, release): Return the version incremented by the release type\n (major, minor, patch, or prerelease), or null if it's not valid.\n\n### Comparison\n\n* gt(v1, v2): `v1 > v2`\n* gte(v1, v2): `v1 >= v2`\n* lt(v1, v2): `v1 < v2`\n* lte(v1, v2): `v1 <= v2`\n* eq(v1, v2): `v1 == v2` This is true if they're logically equivalent,\n even if they're not the exact same string. You already know how to\n compare strings.\n* neq(v1, v2): `v1 != v2` The opposite of eq.\n* cmp(v1, comparator, v2): Pass in a comparison string, and it'll call\n the corresponding function above. `\"===\"` and `\"!==\"` do simple\n string comparison, but are included for completeness. Throws if an\n invalid comparison string is provided.\n* compare(v1, v2): Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if\n v2 is greater. Sorts in ascending order if passed to Array.sort().\n* rcompare(v1, v2): The reverse of compare. Sorts an array of versions\n in descending order when passed to Array.sort().\n\n\n### Ranges\n\n* validRange(range): Return the valid range or null if it's not valid\n* satisfies(version, range): Return true if the version satisfies the\n range.\n* maxSatisfying(versions, range): Return the highest version in the list\n that satisfies the range, or null if none of them do.\n* gtr(version, range): Return true if version is greater than all the\n versions possible in the range.\n* ltr(version, range): Return true if version is less than all the\n versions possible in the range.\n* outside(version, range, hilo): Return true if the version is outside\n the bounds of the range in either the high or low direction. The\n `hilo` argument must be either the string `'>'` or `'<'`. (This is\n the function called by `gtr` and `ltr`.)\n\nNote that, since ranges may be non-contiguous, a version might not be\ngreater than a range, less than a range, *or* satisfy a range! For\nexample, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`\nuntil `2.0.0`, so the version `1.2.10` would not be greater than the\nrange (because 2.0.1 satisfies, which is higher), nor less than the\nrange (since 1.2.8 satisfies, which is lower), and it also does not\nsatisfy the range.\n\nIf you want to know if a version satisfies or does not satisfy a\nrange, use the `satisfies(version, range)` function.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-semver/issues" - }, - "homepage": "https://github.com/isaacs/node-semver", - "_id": "semver@2.2.1", - "_from": "semver@2.x" -} diff --git a/node_modules/express3-handlebars/node_modules/semver/semver.browser.js b/node_modules/express3-handlebars/node_modules/semver/semver.browser.js deleted file mode 100644 index e05ecc19c..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/semver.browser.js +++ /dev/null @@ -1,1007 +0,0 @@ -;(function(exports) { - -// export the class if we are in a Node-like system. -if (typeof module === 'object' && module.exports === exports) - exports = module.exports = SemVer; - -// The debug function is excluded entirely from the minified version. - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0'; - -// The actual regexps go on exports.re -var re = exports.re = []; -var src = exports.src = []; -var R = 0; - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++; -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; -var NUMERICIDENTIFIERLOOSE = R++; -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; - - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++; -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; - - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++; -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')'; - -var MAINVERSIONLOOSE = R++; -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++; -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - -var PRERELEASEIDENTIFIERLOOSE = R++; -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++; -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; - -var PRERELEASELOOSE = R++; -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++; -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++; -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; - - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++; -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?'; - -src[FULL] = '^' + FULLPLAIN + '$'; - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?'; - -var LOOSE = R++; -src[LOOSE] = '^' + LOOSEPLAIN + '$'; - -var GTLT = R++; -src[GTLT] = '((?:<|>)?=?)'; - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++; -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; -var XRANGEIDENTIFIER = R++; -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; - -var XRANGEPLAIN = R++; -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:(' + src[PRERELEASE] + ')' + - ')?)?)?'; - -var XRANGEPLAINLOOSE = R++; -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:(' + src[PRERELEASELOOSE] + ')' + - ')?)?)?'; - -// >=2.x, for example, means >=2.0.0-0 -// <1.x would be the same as "<1.0.0-0", though. -var XRANGE = R++; -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; -var XRANGELOOSE = R++; -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++; -src[LONETILDE] = '(?:~>?)'; - -var TILDETRIM = R++; -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); -var tildeTrimReplace = '$1~'; - -var TILDE = R++; -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; -var TILDELOOSE = R++; -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++; -src[LONECARET] = '(?:\\^)'; - -var CARETTRIM = R++; -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); -var caretTrimReplace = '$1^'; - -var CARET = R++; -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; -var CARETLOOSE = R++; -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++; -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; -var COMPARATOR = R++; -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; - - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++; -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); -var comparatorTrimReplace = '$1$2$3'; - - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++; -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$'; - -var HYPHENRANGELOOSE = R++; -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$'; - -// Star ranges basically just allow anything at all. -var STAR = R++; -src[STAR] = '(<|>)?=?\\s*\\*'; - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - ; - if (!re[i]) - re[i] = new RegExp(src[i]); -} - -exports.parse = parse; -function parse(version, loose) { - var r = loose ? re[LOOSE] : re[FULL]; - return (r.test(version)) ? new SemVer(version, loose) : null; -} - -exports.valid = valid; -function valid(version, loose) { - var v = parse(version, loose); - return v ? v.version : null; -} - - -exports.clean = clean; -function clean(version, loose) { - var s = parse(version, loose); - return s ? s.version : null; -} - -exports.SemVer = SemVer; - -function SemVer(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) - return version; - else - version = version.version; - } - - if (!(this instanceof SemVer)) - return new SemVer(version, loose); - - ; - this.loose = loose; - var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); - - if (!m) - throw new TypeError('Invalid Version: ' + version); - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - // numberify any prerelease numeric ids - if (!m[4]) - this.prerelease = []; - else - this.prerelease = m[4].split('.').map(function(id) { - return (/^[0-9]+$/.test(id)) ? +id : id; - }); - - this.build = m[5] ? m[5].split('.') : []; - this.format(); -} - -SemVer.prototype.format = function() { - this.version = this.major + '.' + this.minor + '.' + this.patch; - if (this.prerelease.length) - this.version += '-' + this.prerelease.join('.'); - return this.version; -}; - -SemVer.prototype.inspect = function() { - return ''; -}; - -SemVer.prototype.toString = function() { - return this.version; -}; - -SemVer.prototype.compare = function(other) { - ; - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return this.compareMain(other) || this.comparePre(other); -}; - -SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch); -}; - -SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) - return -1; - else if (!this.prerelease.length && other.prerelease.length) - return 1; - else if (!this.prerelease.lenth && !other.prerelease.length) - return 0; - - var i = 0; - do { - var a = this.prerelease[i]; - var b = other.prerelease[i]; - ; - if (a === undefined && b === undefined) - return 0; - else if (b === undefined) - return 1; - else if (a === undefined) - return -1; - else if (a === b) - continue; - else - return compareIdentifiers(a, b); - } while (++i); -}; - -SemVer.prototype.inc = function(release) { - switch (release) { - case 'major': - this.major++; - this.minor = -1; - case 'minor': - this.minor++; - this.patch = -1; - case 'patch': - this.patch++; - this.prerelease = []; - break; - case 'prerelease': - if (this.prerelease.length === 0) - this.prerelease = [0]; - else { - var i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) // didn't increment anything - this.prerelease.push(0); - } - break; - - default: - throw new Error('invalid increment argument: ' + release); - } - this.format(); - return this; -}; - -exports.inc = inc; -function inc(version, release, loose) { - try { - return new SemVer(version, loose).inc(release).version; - } catch (er) { - return null; - } -} - -exports.compareIdentifiers = compareIdentifiers; - -var numeric = /^[0-9]+$/; -function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return (anum && !bnum) ? -1 : - (bnum && !anum) ? 1 : - a < b ? -1 : - a > b ? 1 : - 0; -} - -exports.rcompareIdentifiers = rcompareIdentifiers; -function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); -} - -exports.compare = compare; -function compare(a, b, loose) { - return new SemVer(a, loose).compare(b); -} - -exports.compareLoose = compareLoose; -function compareLoose(a, b) { - return compare(a, b, true); -} - -exports.rcompare = rcompare; -function rcompare(a, b, loose) { - return compare(b, a, loose); -} - -exports.sort = sort; -function sort(list, loose) { - return list.sort(function(a, b) { - return exports.compare(a, b, loose); - }); -} - -exports.rsort = rsort; -function rsort(list, loose) { - return list.sort(function(a, b) { - return exports.rcompare(a, b, loose); - }); -} - -exports.gt = gt; -function gt(a, b, loose) { - return compare(a, b, loose) > 0; -} - -exports.lt = lt; -function lt(a, b, loose) { - return compare(a, b, loose) < 0; -} - -exports.eq = eq; -function eq(a, b, loose) { - return compare(a, b, loose) === 0; -} - -exports.neq = neq; -function neq(a, b, loose) { - return compare(a, b, loose) !== 0; -} - -exports.gte = gte; -function gte(a, b, loose) { - return compare(a, b, loose) >= 0; -} - -exports.lte = lte; -function lte(a, b, loose) { - return compare(a, b, loose) <= 0; -} - -exports.cmp = cmp; -function cmp(a, op, b, loose) { - var ret; - switch (op) { - case '===': ret = a === b; break; - case '!==': ret = a !== b; break; - case '': case '=': case '==': ret = eq(a, b, loose); break; - case '!=': ret = neq(a, b, loose); break; - case '>': ret = gt(a, b, loose); break; - case '>=': ret = gte(a, b, loose); break; - case '<': ret = lt(a, b, loose); break; - case '<=': ret = lte(a, b, loose); break; - default: throw new TypeError('Invalid operator: ' + op); - } - return ret; -} - -exports.Comparator = Comparator; -function Comparator(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) - return comp; - else - comp = comp.value; - } - - if (!(this instanceof Comparator)) - return new Comparator(comp, loose); - - ; - this.loose = loose; - this.parse(comp); - - if (this.semver === ANY) - this.value = ''; - else - this.value = this.operator + this.semver.version; -} - -var ANY = {}; -Comparator.prototype.parse = function(comp) { - var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var m = comp.match(r); - - if (!m) - throw new TypeError('Invalid comparator: ' + comp); - - this.operator = m[1]; - // if it literally is just '>' or '' then allow anything. - if (!m[2]) - this.semver = ANY; - else { - this.semver = new SemVer(m[2], this.loose); - - // <1.2.3-rc DOES allow 1.2.3-beta (has prerelease) - // >=1.2.3 DOES NOT allow 1.2.3-beta - // <=1.2.3 DOES allow 1.2.3-beta - // However, <1.2.3 does NOT allow 1.2.3-beta, - // even though `1.2.3-beta < 1.2.3` - // The assumption is that the 1.2.3 version has something you - // *don't* want, so we push the prerelease down to the minimum. - if (this.operator === '<' && !this.semver.prerelease.length) { - this.semver.prerelease = ['0']; - this.semver.format(); - } - } -}; - -Comparator.prototype.inspect = function() { - return ''; -}; - -Comparator.prototype.toString = function() { - return this.value; -}; - -Comparator.prototype.test = function(version) { - ; - return (this.semver === ANY) ? true : - cmp(version, this.operator, this.semver, this.loose); -}; - - -exports.Range = Range; -function Range(range, loose) { - if ((range instanceof Range) && range.loose === loose) - return range; - - if (!(this instanceof Range)) - return new Range(range, loose); - - this.loose = loose; - - // First, split based on boolean or || - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map(function(range) { - return this.parseRange(range.trim()); - }, this).filter(function(c) { - // throw out any that are not relevant for whatever reason - return c.length; - }); - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range); - } - - this.format(); -} - -Range.prototype.inspect = function() { - return ''; -}; - -Range.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(' ').trim(); - }).join('||').trim(); - return this.range; -}; - -Range.prototype.toString = function() { - return this.range; -}; - -Range.prototype.parseRange = function(range) { - var loose = this.loose; - range = range.trim(); - ; - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - ; - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - ; - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var set = range.split(' ').map(function(comp) { - return parseComparator(comp, loose); - }).join(' ').split(/\s+/); - if (this.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function(comp) { - return !!comp.match(compRe); - }); - } - set = set.map(function(comp) { - return new Comparator(comp, loose); - }); - - return set; -}; - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators; -function toComparators(range, loose) { - return new Range(range, loose).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(' ').trim().split(' '); - }); -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator(comp, loose) { - ; - comp = replaceCarets(comp, loose); - ; - comp = replaceTildes(comp, loose); - ; - comp = replaceXRanges(comp, loose); - ; - comp = replaceStars(comp, loose); - ; - return comp; -} - -function isX(id) { - return !id || id.toLowerCase() === 'x' || id === '*'; -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, loose); - }).join(' '); -} - -function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - ; - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; - else if (isX(p)) - // ~1.2 == >=1.2.0- <1.3.0- - ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; - else if (pr) { - ; - if (pr.charAt(0) !== '-') - pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0-0'; - } else - // ~1.2.3 == >=1.2.3-0 <1.3.0-0 - ret = '>=' + M + '.' + m + '.' + p + '-0' + - ' <' + M + '.' + (+m + 1) + '.0-0'; - - ; - return ret; - }); -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, loose); - }).join(' '); -} - -function replaceCaret(comp, loose) { - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - ; - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; - else if (isX(p)) { - if (M === '0') - ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; - else - ret = '>=' + M + '.' + m + '.0-0 <' + (+M + 1) + '.0.0-0'; - } else if (pr) { - ; - if (pr.charAt(0) !== '-') - pr = '-' + pr; - if (M === '0') { - if (m === '0') - ret = '=' + M + '.' + m + '.' + p + pr; - else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0-0'; - } else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + (+M + 1) + '.0.0-0'; - } else { - if (M === '0') { - if (m === '0') - ret = '=' + M + '.' + m + '.' + p; - else - ret = '>=' + M + '.' + m + '.' + p + '-0' + - ' <' + M + '.' + (+m + 1) + '.0-0'; - } else - ret = '>=' + M + '.' + m + '.' + p + '-0' + - ' <' + (+M + 1) + '.0.0-0'; - } - - ; - return ret; - }); -} - -function replaceXRanges(comp, loose) { - ; - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, loose); - }).join(' '); -} - -function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - ; - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - - if (gtlt === '=' && anyX) - gtlt = ''; - - if (gtlt && anyX) { - // replace X with 0, and then append the -0 min-prerelease - if (xM) - M = 0; - if (xm) - m = 0; - if (xp) - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0-0 - // >1.2 => >=1.3.0-0 - // >1.2.3 => >= 1.2.4-0 - gtlt = '>='; - if (xM) { - // no change - } else if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; - } - } - - - ret = gtlt + M + '.' + m + '.' + p + '-0'; - } else if (xM) { - // allow any - ret = '*'; - } else if (xm) { - // append '-0' onto the version, otherwise - // '1.x.x' matches '2.0.0-beta', since the tag - // *lowers* the version value - ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; - } - - ; - - return ret; - }); -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars(comp, loose) { - ; - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ''); -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0-0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0-0 <3.5.0-0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0-0 <3.5.0-0 -function hyphenReplace($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - - if (isX(fM)) - from = ''; - else if (isX(fm)) - from = '>=' + fM + '.0.0-0'; - else if (isX(fp)) - from = '>=' + fM + '.' + fm + '.0-0'; - else - from = '>=' + from; - - if (isX(tM)) - to = ''; - else if (isX(tm)) - to = '<' + (+tM + 1) + '.0.0-0'; - else if (isX(tp)) - to = '<' + tM + '.' + (+tm + 1) + '.0-0'; - else if (tpr) - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; - else - to = '<=' + to; - - return (from + ' ' + to).trim(); -} - - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function(version) { - if (!version) - return false; - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) - return true; - } - return false; -}; - -function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; - } - return true; -} - -exports.satisfies = satisfies; -function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; - } - return range.test(version); -} - -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, loose) { - return versions.filter(function(version) { - return satisfies(version, range, loose); - }).sort(function(a, b) { - return rcompare(a, b, loose); - })[0] || null; -} - -exports.validRange = validRange; -function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr; -function ltr(version, range, loose) { - return outside(version, range, '<', loose); -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, loose) { - return outside(version, range, '>', loose); -} - -exports.outside = outside; -function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); - - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, loose)) { - return false; - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; - - var high = null; - var low = null; - - comparators.forEach(function(comparator) { - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false; - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - return true; -} - -// Use the define() function if we're in AMD land -if (typeof define === 'function' && define.amd) - define(exports); - -})( - typeof exports === 'object' ? exports : - typeof define === 'function' && define.amd ? {} : - semver = {} -); diff --git a/node_modules/express3-handlebars/node_modules/semver/semver.js b/node_modules/express3-handlebars/node_modules/semver/semver.js deleted file mode 100644 index 9e9470d86..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/semver.js +++ /dev/null @@ -1,1011 +0,0 @@ -// export the class if we are in a Node-like system. -if (typeof module === 'object' && module.exports === exports) - exports = module.exports = SemVer; - -// The debug function is excluded entirely from the minified version. -/* nomin */ var debug; -/* nomin */ if (typeof process === 'object' && - /* nomin */ process.env && - /* nomin */ process.env.NODE_DEBUG && - /* nomin */ /\bsemver\b/i.test(process.env.NODE_DEBUG)) - /* nomin */ debug = function() { - /* nomin */ var args = Array.prototype.slice.call(arguments, 0); - /* nomin */ args.unshift('SEMVER'); - /* nomin */ console.log.apply(console, args); - /* nomin */ }; -/* nomin */ else - /* nomin */ debug = function() {}; - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0'; - -// The actual regexps go on exports.re -var re = exports.re = []; -var src = exports.src = []; -var R = 0; - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -var NUMERICIDENTIFIER = R++; -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; -var NUMERICIDENTIFIERLOOSE = R++; -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; - - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -var NONNUMERICIDENTIFIER = R++; -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; - - -// ## Main Version -// Three dot-separated numeric identifiers. - -var MAINVERSION = R++; -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')'; - -var MAINVERSIONLOOSE = R++; -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. - -var PRERELEASEIDENTIFIER = R++; -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - -var PRERELEASEIDENTIFIERLOOSE = R++; -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')'; - - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -var PRERELEASE = R++; -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; - -var PRERELEASELOOSE = R++; -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -var BUILDIDENTIFIER = R++; -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -var BUILD = R++; -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; - - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -var FULL = R++; -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?'; - -src[FULL] = '^' + FULLPLAIN + '$'; - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?'; - -var LOOSE = R++; -src[LOOSE] = '^' + LOOSEPLAIN + '$'; - -var GTLT = R++; -src[GTLT] = '((?:<|>)?=?)'; - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++; -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; -var XRANGEIDENTIFIER = R++; -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; - -var XRANGEPLAIN = R++; -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:(' + src[PRERELEASE] + ')' + - ')?)?)?'; - -var XRANGEPLAINLOOSE = R++; -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:(' + src[PRERELEASELOOSE] + ')' + - ')?)?)?'; - -// >=2.x, for example, means >=2.0.0-0 -// <1.x would be the same as "<1.0.0-0", though. -var XRANGE = R++; -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; -var XRANGELOOSE = R++; -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++; -src[LONETILDE] = '(?:~>?)'; - -var TILDETRIM = R++; -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); -var tildeTrimReplace = '$1~'; - -var TILDE = R++; -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; -var TILDELOOSE = R++; -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++; -src[LONECARET] = '(?:\\^)'; - -var CARETTRIM = R++; -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); -var caretTrimReplace = '$1^'; - -var CARET = R++; -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; -var CARETLOOSE = R++; -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++; -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; -var COMPARATOR = R++; -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; - - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++; -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; - -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); -var comparatorTrimReplace = '$1$2$3'; - - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++; -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$'; - -var HYPHENRANGELOOSE = R++; -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$'; - -// Star ranges basically just allow anything at all. -var STAR = R++; -src[STAR] = '(<|>)?=?\\s*\\*'; - -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]); - if (!re[i]) - re[i] = new RegExp(src[i]); -} - -exports.parse = parse; -function parse(version, loose) { - var r = loose ? re[LOOSE] : re[FULL]; - return (r.test(version)) ? new SemVer(version, loose) : null; -} - -exports.valid = valid; -function valid(version, loose) { - var v = parse(version, loose); - return v ? v.version : null; -} - - -exports.clean = clean; -function clean(version, loose) { - var s = parse(version, loose); - return s ? s.version : null; -} - -exports.SemVer = SemVer; - -function SemVer(version, loose) { - if (version instanceof SemVer) { - if (version.loose === loose) - return version; - else - version = version.version; - } - - if (!(this instanceof SemVer)) - return new SemVer(version, loose); - - debug('SemVer', version, loose); - this.loose = loose; - var m = version.trim().match(loose ? re[LOOSE] : re[FULL]); - - if (!m) - throw new TypeError('Invalid Version: ' + version); - - this.raw = version; - - // these are actually numbers - this.major = +m[1]; - this.minor = +m[2]; - this.patch = +m[3]; - - // numberify any prerelease numeric ids - if (!m[4]) - this.prerelease = []; - else - this.prerelease = m[4].split('.').map(function(id) { - return (/^[0-9]+$/.test(id)) ? +id : id; - }); - - this.build = m[5] ? m[5].split('.') : []; - this.format(); -} - -SemVer.prototype.format = function() { - this.version = this.major + '.' + this.minor + '.' + this.patch; - if (this.prerelease.length) - this.version += '-' + this.prerelease.join('.'); - return this.version; -}; - -SemVer.prototype.inspect = function() { - return ''; -}; - -SemVer.prototype.toString = function() { - return this.version; -}; - -SemVer.prototype.compare = function(other) { - debug('SemVer.compare', this.version, this.loose, other); - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return this.compareMain(other) || this.comparePre(other); -}; - -SemVer.prototype.compareMain = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch); -}; - -SemVer.prototype.comparePre = function(other) { - if (!(other instanceof SemVer)) - other = new SemVer(other, this.loose); - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) - return -1; - else if (!this.prerelease.length && other.prerelease.length) - return 1; - else if (!this.prerelease.lenth && !other.prerelease.length) - return 0; - - var i = 0; - do { - var a = this.prerelease[i]; - var b = other.prerelease[i]; - debug('prerelease compare', i, a, b); - if (a === undefined && b === undefined) - return 0; - else if (b === undefined) - return 1; - else if (a === undefined) - return -1; - else if (a === b) - continue; - else - return compareIdentifiers(a, b); - } while (++i); -}; - -SemVer.prototype.inc = function(release) { - switch (release) { - case 'major': - this.major++; - this.minor = -1; - case 'minor': - this.minor++; - this.patch = -1; - case 'patch': - this.patch++; - this.prerelease = []; - break; - case 'prerelease': - if (this.prerelease.length === 0) - this.prerelease = [0]; - else { - var i = this.prerelease.length; - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++; - i = -2; - } - } - if (i === -1) // didn't increment anything - this.prerelease.push(0); - } - break; - - default: - throw new Error('invalid increment argument: ' + release); - } - this.format(); - return this; -}; - -exports.inc = inc; -function inc(version, release, loose) { - try { - return new SemVer(version, loose).inc(release).version; - } catch (er) { - return null; - } -} - -exports.compareIdentifiers = compareIdentifiers; - -var numeric = /^[0-9]+$/; -function compareIdentifiers(a, b) { - var anum = numeric.test(a); - var bnum = numeric.test(b); - - if (anum && bnum) { - a = +a; - b = +b; - } - - return (anum && !bnum) ? -1 : - (bnum && !anum) ? 1 : - a < b ? -1 : - a > b ? 1 : - 0; -} - -exports.rcompareIdentifiers = rcompareIdentifiers; -function rcompareIdentifiers(a, b) { - return compareIdentifiers(b, a); -} - -exports.compare = compare; -function compare(a, b, loose) { - return new SemVer(a, loose).compare(b); -} - -exports.compareLoose = compareLoose; -function compareLoose(a, b) { - return compare(a, b, true); -} - -exports.rcompare = rcompare; -function rcompare(a, b, loose) { - return compare(b, a, loose); -} - -exports.sort = sort; -function sort(list, loose) { - return list.sort(function(a, b) { - return exports.compare(a, b, loose); - }); -} - -exports.rsort = rsort; -function rsort(list, loose) { - return list.sort(function(a, b) { - return exports.rcompare(a, b, loose); - }); -} - -exports.gt = gt; -function gt(a, b, loose) { - return compare(a, b, loose) > 0; -} - -exports.lt = lt; -function lt(a, b, loose) { - return compare(a, b, loose) < 0; -} - -exports.eq = eq; -function eq(a, b, loose) { - return compare(a, b, loose) === 0; -} - -exports.neq = neq; -function neq(a, b, loose) { - return compare(a, b, loose) !== 0; -} - -exports.gte = gte; -function gte(a, b, loose) { - return compare(a, b, loose) >= 0; -} - -exports.lte = lte; -function lte(a, b, loose) { - return compare(a, b, loose) <= 0; -} - -exports.cmp = cmp; -function cmp(a, op, b, loose) { - var ret; - switch (op) { - case '===': ret = a === b; break; - case '!==': ret = a !== b; break; - case '': case '=': case '==': ret = eq(a, b, loose); break; - case '!=': ret = neq(a, b, loose); break; - case '>': ret = gt(a, b, loose); break; - case '>=': ret = gte(a, b, loose); break; - case '<': ret = lt(a, b, loose); break; - case '<=': ret = lte(a, b, loose); break; - default: throw new TypeError('Invalid operator: ' + op); - } - return ret; -} - -exports.Comparator = Comparator; -function Comparator(comp, loose) { - if (comp instanceof Comparator) { - if (comp.loose === loose) - return comp; - else - comp = comp.value; - } - - if (!(this instanceof Comparator)) - return new Comparator(comp, loose); - - debug('comparator', comp, loose); - this.loose = loose; - this.parse(comp); - - if (this.semver === ANY) - this.value = ''; - else - this.value = this.operator + this.semver.version; -} - -var ANY = {}; -Comparator.prototype.parse = function(comp) { - var r = this.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var m = comp.match(r); - - if (!m) - throw new TypeError('Invalid comparator: ' + comp); - - this.operator = m[1]; - // if it literally is just '>' or '' then allow anything. - if (!m[2]) - this.semver = ANY; - else { - this.semver = new SemVer(m[2], this.loose); - - // <1.2.3-rc DOES allow 1.2.3-beta (has prerelease) - // >=1.2.3 DOES NOT allow 1.2.3-beta - // <=1.2.3 DOES allow 1.2.3-beta - // However, <1.2.3 does NOT allow 1.2.3-beta, - // even though `1.2.3-beta < 1.2.3` - // The assumption is that the 1.2.3 version has something you - // *don't* want, so we push the prerelease down to the minimum. - if (this.operator === '<' && !this.semver.prerelease.length) { - this.semver.prerelease = ['0']; - this.semver.format(); - } - } -}; - -Comparator.prototype.inspect = function() { - return ''; -}; - -Comparator.prototype.toString = function() { - return this.value; -}; - -Comparator.prototype.test = function(version) { - debug('Comparator.test', version, this.loose); - return (this.semver === ANY) ? true : - cmp(version, this.operator, this.semver, this.loose); -}; - - -exports.Range = Range; -function Range(range, loose) { - if ((range instanceof Range) && range.loose === loose) - return range; - - if (!(this instanceof Range)) - return new Range(range, loose); - - this.loose = loose; - - // First, split based on boolean or || - this.raw = range; - this.set = range.split(/\s*\|\|\s*/).map(function(range) { - return this.parseRange(range.trim()); - }, this).filter(function(c) { - // throw out any that are not relevant for whatever reason - return c.length; - }); - - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range); - } - - this.format(); -} - -Range.prototype.inspect = function() { - return ''; -}; - -Range.prototype.format = function() { - this.range = this.set.map(function(comps) { - return comps.join(' ').trim(); - }).join('||').trim(); - return this.range; -}; - -Range.prototype.toString = function() { - return this.range; -}; - -Range.prototype.parseRange = function(range) { - var loose = this.loose; - range = range.trim(); - debug('range', range, loose); - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; - range = range.replace(hr, hyphenReplace); - debug('hyphen replace', range); - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); - debug('comparator trim', range, re[COMPARATORTRIM]); - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace); - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace); - - // normalize spaces - range = range.split(/\s+/).join(' '); - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; - var set = range.split(' ').map(function(comp) { - return parseComparator(comp, loose); - }).join(' ').split(/\s+/); - if (this.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function(comp) { - return !!comp.match(compRe); - }); - } - set = set.map(function(comp) { - return new Comparator(comp, loose); - }); - - return set; -}; - -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators; -function toComparators(range, loose) { - return new Range(range, loose).set.map(function(comp) { - return comp.map(function(c) { - return c.value; - }).join(' ').trim().split(' '); - }); -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator(comp, loose) { - debug('comp', comp); - comp = replaceCarets(comp, loose); - debug('caret', comp); - comp = replaceTildes(comp, loose); - debug('tildes', comp); - comp = replaceXRanges(comp, loose); - debug('xrange', comp); - comp = replaceStars(comp, loose); - debug('stars', comp); - return comp; -} - -function isX(id) { - return !id || id.toLowerCase() === 'x' || id === '*'; -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceTilde(comp, loose); - }).join(' '); -} - -function replaceTilde(comp, loose) { - var r = loose ? re[TILDELOOSE] : re[TILDE]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; - else if (isX(p)) - // ~1.2 == >=1.2.0- <1.3.0- - ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; - else if (pr) { - debug('replaceTilde pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0-0'; - } else - // ~1.2.3 == >=1.2.3-0 <1.3.0-0 - ret = '>=' + M + '.' + m + '.' + p + '-0' + - ' <' + M + '.' + (+m + 1) + '.0-0'; - - debug('tilde return', ret); - return ret; - }); -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets(comp, loose) { - return comp.trim().split(/\s+/).map(function(comp) { - return replaceCaret(comp, loose); - }).join(' '); -} - -function replaceCaret(comp, loose) { - var r = loose ? re[CARETLOOSE] : re[CARET]; - return comp.replace(r, function(_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr); - var ret; - - if (isX(M)) - ret = ''; - else if (isX(m)) - ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; - else if (isX(p)) { - if (M === '0') - ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; - else - ret = '>=' + M + '.' + m + '.0-0 <' + (+M + 1) + '.0.0-0'; - } else if (pr) { - debug('replaceCaret pr', pr); - if (pr.charAt(0) !== '-') - pr = '-' + pr; - if (M === '0') { - if (m === '0') - ret = '=' + M + '.' + m + '.' + p + pr; - else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + M + '.' + (+m + 1) + '.0-0'; - } else - ret = '>=' + M + '.' + m + '.' + p + pr + - ' <' + (+M + 1) + '.0.0-0'; - } else { - if (M === '0') { - if (m === '0') - ret = '=' + M + '.' + m + '.' + p; - else - ret = '>=' + M + '.' + m + '.' + p + '-0' + - ' <' + M + '.' + (+m + 1) + '.0-0'; - } else - ret = '>=' + M + '.' + m + '.' + p + '-0' + - ' <' + (+M + 1) + '.0.0-0'; - } - - debug('caret return', ret); - return ret; - }); -} - -function replaceXRanges(comp, loose) { - debug('replaceXRanges', comp, loose); - return comp.split(/\s+/).map(function(comp) { - return replaceXRange(comp, loose); - }).join(' '); -} - -function replaceXRange(comp, loose) { - comp = comp.trim(); - var r = loose ? re[XRANGELOOSE] : re[XRANGE]; - return comp.replace(r, function(ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr); - var xM = isX(M); - var xm = xM || isX(m); - var xp = xm || isX(p); - var anyX = xp; - - if (gtlt === '=' && anyX) - gtlt = ''; - - if (gtlt && anyX) { - // replace X with 0, and then append the -0 min-prerelease - if (xM) - M = 0; - if (xm) - m = 0; - if (xp) - p = 0; - - if (gtlt === '>') { - // >1 => >=2.0.0-0 - // >1.2 => >=1.3.0-0 - // >1.2.3 => >= 1.2.4-0 - gtlt = '>='; - if (xM) { - // no change - } else if (xm) { - M = +M + 1; - m = 0; - p = 0; - } else if (xp) { - m = +m + 1; - p = 0; - } - } - - - ret = gtlt + M + '.' + m + '.' + p + '-0'; - } else if (xM) { - // allow any - ret = '*'; - } else if (xm) { - // append '-0' onto the version, otherwise - // '1.x.x' matches '2.0.0-beta', since the tag - // *lowers* the version value - ret = '>=' + M + '.0.0-0 <' + (+M + 1) + '.0.0-0'; - } else if (xp) { - ret = '>=' + M + '.' + m + '.0-0 <' + M + '.' + (+m + 1) + '.0-0'; - } - - debug('xRange return', ret); - - return ret; - }); -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars(comp, loose) { - debug('replaceStars', comp, loose); - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], ''); -} - -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0-0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0-0 <3.5.0-0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0-0 <3.5.0-0 -function hyphenReplace($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - - if (isX(fM)) - from = ''; - else if (isX(fm)) - from = '>=' + fM + '.0.0-0'; - else if (isX(fp)) - from = '>=' + fM + '.' + fm + '.0-0'; - else - from = '>=' + from; - - if (isX(tM)) - to = ''; - else if (isX(tm)) - to = '<' + (+tM + 1) + '.0.0-0'; - else if (isX(tp)) - to = '<' + tM + '.' + (+tm + 1) + '.0-0'; - else if (tpr) - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; - else - to = '<=' + to; - - return (from + ' ' + to).trim(); -} - - -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function(version) { - if (!version) - return false; - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version)) - return true; - } - return false; -}; - -function testSet(set, version) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) - return false; - } - return true; -} - -exports.satisfies = satisfies; -function satisfies(version, range, loose) { - try { - range = new Range(range, loose); - } catch (er) { - return false; - } - return range.test(version); -} - -exports.maxSatisfying = maxSatisfying; -function maxSatisfying(versions, range, loose) { - return versions.filter(function(version) { - return satisfies(version, range, loose); - }).sort(function(a, b) { - return rcompare(a, b, loose); - })[0] || null; -} - -exports.validRange = validRange; -function validRange(range, loose) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, loose).range || '*'; - } catch (er) { - return null; - } -} - -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr; -function ltr(version, range, loose) { - return outside(version, range, '<', loose); -} - -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr; -function gtr(version, range, loose) { - return outside(version, range, '>', loose); -} - -exports.outside = outside; -function outside(version, range, hilo, loose) { - version = new SemVer(version, loose); - range = new Range(range, loose); - - var gtfn, ltefn, ltfn, comp, ecomp; - switch (hilo) { - case '>': - gtfn = gt; - ltefn = lte; - ltfn = lt; - comp = '>'; - ecomp = '>='; - break; - case '<': - gtfn = lt; - ltefn = gte; - ltfn = gt; - comp = '<'; - ecomp = '<='; - break; - default: - throw new TypeError('Must provide a hilo val of "<" or ">"'); - } - - // If it satisifes the range it is not outside - if (satisfies(version, range, loose)) { - return false; - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i]; - - var high = null; - var low = null; - - comparators.forEach(function(comparator) { - high = high || comparator; - low = low || comparator; - if (gtfn(comparator.semver, high.semver, loose)) { - high = comparator; - } else if (ltfn(comparator.semver, low.semver, loose)) { - low = comparator; - } - }); - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false; - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false; - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false; - } - } - return true; -} - -// Use the define() function if we're in AMD land -if (typeof define === 'function' && define.amd) - define(exports); diff --git a/node_modules/express3-handlebars/node_modules/semver/semver.min.js b/node_modules/express3-handlebars/node_modules/semver/semver.min.js deleted file mode 100644 index c2164c33e..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/semver.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(e){if(typeof module==="object"&&module.exports===e)e=module.exports=H;e.SEMVER_SPEC_VERSION="2.0.0";var r=e.re=[];var t=e.src=[];var n=0;var i=n++;t[i]="0|[1-9]\\d*";var s=n++;t[s]="[0-9]+";var o=n++;t[o]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";var a=n++;t[a]="("+t[i]+")\\."+"("+t[i]+")\\."+"("+t[i]+")";var f=n++;t[f]="("+t[s]+")\\."+"("+t[s]+")\\."+"("+t[s]+")";var u=n++;t[u]="(?:"+t[i]+"|"+t[o]+")";var l=n++;t[l]="(?:"+t[s]+"|"+t[o]+")";var c=n++;t[c]="(?:-("+t[u]+"(?:\\."+t[u]+")*))";var p=n++;t[p]="(?:-?("+t[l]+"(?:\\."+t[l]+")*))";var h=n++;t[h]="[0-9A-Za-z-]+";var v=n++;t[v]="(?:\\+("+t[h]+"(?:\\."+t[h]+")*))";var m=n++;var g="v?"+t[a]+t[c]+"?"+t[v]+"?";t[m]="^"+g+"$";var w="[v=\\s]*"+t[f]+t[p]+"?"+t[v]+"?";var d=n++;t[d]="^"+w+"$";var y=n++;t[y]="((?:<|>)?=?)";var $=n++;t[$]=t[s]+"|x|X|\\*";var j=n++;t[j]=t[i]+"|x|X|\\*";var b=n++;t[b]="[v=\\s]*("+t[j]+")"+"(?:\\.("+t[j]+")"+"(?:\\.("+t[j]+")"+"(?:("+t[c]+")"+")?)?)?";var E=n++;t[E]="[v=\\s]*("+t[$]+")"+"(?:\\.("+t[$]+")"+"(?:\\.("+t[$]+")"+"(?:("+t[p]+")"+")?)?)?";var k=n++;t[k]="^"+t[y]+"\\s*"+t[b]+"$";var x=n++;t[x]="^"+t[y]+"\\s*"+t[E]+"$";var R=n++;t[R]="(?:~>?)";var S=n++;t[S]="(\\s*)"+t[R]+"\\s+";r[S]=new RegExp(t[S],"g");var V="$1~";var I=n++;t[I]="^"+t[R]+t[b]+"$";var A=n++;t[A]="^"+t[R]+t[E]+"$";var C=n++;t[C]="(?:\\^)";var T=n++;t[T]="(\\s*)"+t[C]+"\\s+";r[T]=new RegExp(t[T],"g");var M="$1^";var z=n++;t[z]="^"+t[C]+t[b]+"$";var P=n++;t[P]="^"+t[C]+t[E]+"$";var Z=n++;t[Z]="^"+t[y]+"\\s*("+w+")$|^$";var q=n++;t[q]="^"+t[y]+"\\s*("+g+")$|^$";var L=n++;t[L]="(\\s*)"+t[y]+"\\s*("+w+"|"+t[b]+")";r[L]=new RegExp(t[L],"g");var X="$1$2$3";var _=n++;t[_]="^\\s*("+t[b]+")"+"\\s+-\\s+"+"("+t[b]+")"+"\\s*$";var N=n++;t[N]="^\\s*("+t[E]+")"+"\\s+-\\s+"+"("+t[E]+")"+"\\s*$";var O=n++;t[O]="(<|>)?=?\\s*\\*";for(var B=0;B'};H.prototype.toString=function(){return this.version};H.prototype.compare=function(e){if(!(e instanceof H))e=new H(e,this.loose);return this.compareMain(e)||this.comparePre(e)};H.prototype.compareMain=function(e){if(!(e instanceof H))e=new H(e,this.loose);return Q(this.major,e.major)||Q(this.minor,e.minor)||Q(this.patch,e.patch)};H.prototype.comparePre=function(e){if(!(e instanceof H))e=new H(e,this.loose);if(this.prerelease.length&&!e.prerelease.length)return-1;else if(!this.prerelease.length&&e.prerelease.length)return 1;else if(!this.prerelease.lenth&&!e.prerelease.length)return 0;var r=0;do{var t=this.prerelease[r];var n=e.prerelease[r];if(t===undefined&&n===undefined)return 0;else if(n===undefined)return 1;else if(t===undefined)return-1;else if(t===n)continue;else return Q(t,n)}while(++r)};H.prototype.inc=function(e){switch(e){case"major":this.major++;this.minor=-1;case"minor":this.minor++;this.patch=-1;case"patch":this.patch++;this.prerelease=[];break;case"prerelease":if(this.prerelease.length===0)this.prerelease=[0];else{var r=this.prerelease.length;while(--r>=0){if(typeof this.prerelease[r]==="number"){this.prerelease[r]++;r=-2}}if(r===-1)this.prerelease.push(0)}break;default:throw new Error("invalid increment argument: "+e)}this.format();return this};e.inc=J;function J(e,r,t){try{return new H(e,t).inc(r).version}catch(n){return null}}e.compareIdentifiers=Q;var K=/^[0-9]+$/;function Q(e,r){var t=K.test(e);var n=K.test(r);if(t&&n){e=+e;r=+r}return t&&!n?-1:n&&!t?1:er?1:0}e.rcompareIdentifiers=U;function U(e,r){return Q(r,e)}e.compare=W;function W(e,r,t){return new H(e,t).compare(r)}e.compareLoose=Y;function Y(e,r){return W(e,r,true)}e.rcompare=er;function er(e,r,t){return W(r,e,t)}e.sort=rr;function rr(r,t){return r.sort(function(r,n){return e.compare(r,n,t)})}e.rsort=tr;function tr(r,t){return r.sort(function(r,n){return e.rcompare(r,n,t)})}e.gt=nr;function nr(e,r,t){return W(e,r,t)>0}e.lt=ir;function ir(e,r,t){return W(e,r,t)<0}e.eq=sr;function sr(e,r,t){return W(e,r,t)===0}e.neq=or;function or(e,r,t){return W(e,r,t)!==0}e.gte=ar;function ar(e,r,t){return W(e,r,t)>=0}e.lte=fr;function fr(e,r,t){return W(e,r,t)<=0}e.cmp=ur;function ur(e,r,t,n){var i;switch(r){case"===":i=e===t;break;case"!==":i=e!==t;break;case"":case"=":case"==":i=sr(e,t,n);break;case"!=":i=or(e,t,n);break;case">":i=nr(e,t,n);break;case">=":i=ar(e,t,n);break;case"<":i=ir(e,t,n);break;case"<=":i=fr(e,t,n);break;default:throw new TypeError("Invalid operator: "+r)}return i}e.Comparator=lr;function lr(e,r){if(e instanceof lr){if(e.loose===r)return e;else e=e.value}if(!(this instanceof lr))return new lr(e,r);this.loose=r;this.parse(e);if(this.semver===cr)this.value="";else this.value=this.operator+this.semver.version}var cr={};lr.prototype.parse=function(e){var t=this.loose?r[Z]:r[q];var n=e.match(t);if(!n)throw new TypeError("Invalid comparator: "+e);this.operator=n[1];if(!n[2])this.semver=cr;else{this.semver=new H(n[2],this.loose);if(this.operator==="<"&&!this.semver.prerelease.length){this.semver.prerelease=["0"];this.semver.format()}}};lr.prototype.inspect=function(){return''};lr.prototype.toString=function(){return this.value};lr.prototype.test=function(e){return this.semver===cr?true:ur(e,this.operator,this.semver,this.loose)};e.Range=pr;function pr(e,r){if(e instanceof pr&&e.loose===r)return e;if(!(this instanceof pr))return new pr(e,r);this.loose=r;this.raw=e;this.set=e.split(/\s*\|\|\s*/).map(function(e){return this.parseRange(e.trim())},this).filter(function(e){return e.length});if(!this.set.length){throw new TypeError("Invalid SemVer Range: "+e)}this.format()}pr.prototype.inspect=function(){return''};pr.prototype.format=function(){this.range=this.set.map(function(e){return e.join(" ").trim()}).join("||").trim();return this.range};pr.prototype.toString=function(){return this.range};pr.prototype.parseRange=function(e){var t=this.loose;e=e.trim();var n=t?r[N]:r[_];e=e.replace(n,Er);e=e.replace(r[L],X);e=e.replace(r[S],V);e=e.replace(r[T],M);e=e.split(/\s+/).join(" ");var i=t?r[Z]:r[q];var s=e.split(" ").map(function(e){return vr(e,t)}).join(" ").split(/\s+/);if(this.loose){s=s.filter(function(e){return!!e.match(i)})}s=s.map(function(e){return new lr(e,t)});return s};e.toComparators=hr;function hr(e,r){return new pr(e,r).set.map(function(e){return e.map(function(e){return e.value}).join(" ").trim().split(" ")})}function vr(e,r){e=dr(e,r);e=gr(e,r);e=$r(e,r);e=br(e,r);return e}function mr(e){return!e||e.toLowerCase()==="x"||e==="*"}function gr(e,r){return e.trim().split(/\s+/).map(function(e){return wr(e,r)}).join(" ")}function wr(e,t){var n=t?r[A]:r[I];return e.replace(n,function(e,r,t,n,i){var s;if(mr(r))s="";else if(mr(t))s=">="+r+".0.0-0 <"+(+r+1)+".0.0-0";else if(mr(n))s=">="+r+"."+t+".0-0 <"+r+"."+(+t+1)+".0-0";else if(i){if(i.charAt(0)!=="-")i="-"+i;s=">="+r+"."+t+"."+n+i+" <"+r+"."+(+t+1)+".0-0"}else s=">="+r+"."+t+"."+n+"-0"+" <"+r+"."+(+t+1)+".0-0";return s})}function dr(e,r){return e.trim().split(/\s+/).map(function(e){return yr(e,r)}).join(" ")}function yr(e,t){var n=t?r[P]:r[z];return e.replace(n,function(e,r,t,n,i){var s;if(mr(r))s="";else if(mr(t))s=">="+r+".0.0-0 <"+(+r+1)+".0.0-0";else if(mr(n)){if(r==="0")s=">="+r+"."+t+".0-0 <"+r+"."+(+t+1)+".0-0";else s=">="+r+"."+t+".0-0 <"+(+r+1)+".0.0-0"}else if(i){if(i.charAt(0)!=="-")i="-"+i;if(r==="0"){if(t==="0")s="="+r+"."+t+"."+n+i;else s=">="+r+"."+t+"."+n+i+" <"+r+"."+(+t+1)+".0-0"}else s=">="+r+"."+t+"."+n+i+" <"+(+r+1)+".0.0-0"}else{if(r==="0"){if(t==="0")s="="+r+"."+t+"."+n;else s=">="+r+"."+t+"."+n+"-0"+" <"+r+"."+(+t+1)+".0-0"}else s=">="+r+"."+t+"."+n+"-0"+" <"+(+r+1)+".0.0-0"}return s})}function $r(e,r){return e.split(/\s+/).map(function(e){return jr(e,r)}).join(" ")}function jr(e,t){e=e.trim();var n=t?r[x]:r[k];return e.replace(n,function(e,r,t,n,i,s){var o=mr(t);var a=o||mr(n);var f=a||mr(i);var u=f;if(r==="="&&u)r="";if(r&&u){if(o)t=0;if(a)n=0;if(f)i=0;if(r===">"){r=">=";if(o){}else if(a){t=+t+1;n=0;i=0}else if(f){n=+n+1;i=0}}e=r+t+"."+n+"."+i+"-0"}else if(o){e="*"}else if(a){e=">="+t+".0.0-0 <"+(+t+1)+".0.0-0"}else if(f){e=">="+t+"."+n+".0-0 <"+t+"."+(+n+1)+".0-0"}return e})}function br(e,t){return e.trim().replace(r[O],"")}function Er(e,r,t,n,i,s,o,a,f,u,l,c,p){if(mr(t))r="";else if(mr(n))r=">="+t+".0.0-0";else if(mr(i))r=">="+t+"."+n+".0-0";else r=">="+r;if(mr(f))a="";else if(mr(u))a="<"+(+f+1)+".0.0-0";else if(mr(l))a="<"+f+"."+(+u+1)+".0-0";else if(c)a="<="+f+"."+u+"."+l+"-"+c;else a="<="+a;return(r+" "+a).trim()}pr.prototype.test=function(e){if(!e)return false;for(var r=0;r",t)}e.outside=Ar;function Ar(e,r,t,n){e=new H(e,n);r=new pr(r,n);var i,s,o,a,f;switch(t){case">":i=nr;s=fr;o=ir;a=">";f=">=";break;case"<":i=ir;s=ar;o=nr;a="<";f="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(xr(e,r,n)){return false}for(var u=0;u=2.4.0 <2.5.0 - ['~2.4', '2.5.5'], - ['~>3.2.1', '3.3.0'], // >=3.2.1 <3.3.0 - ['~1', '2.2.3'], // >=1.0.0 <2.0.0 - ['~>1', '2.2.4'], - ['~> 1', '3.2.3'], - ['~1.0', '1.1.2'], // >=1.0.0 <1.1.0 - ['~ 1.0', '1.1.0'], - ['<1.2', '1.2.0'], - ['< 1.2', '1.2.1'], - ['1', '2.0.0beta', true], - ['~v0.5.4-pre', '0.6.0'], - ['~v0.5.4-pre', '0.6.1-pre'], - ['=0.7.x', '0.8.0'], - ['=0.7.x', '0.8.0-asdf'], - ['<=0.7.x', '0.7.0'], - ['~1.2.2', '1.3.0'], - ['1.0.0 - 2.0.0', '2.2.3'], - ['1.0.0', '1.0.1'], - ['<=2.0.0', '3.0.0'], - ['<=2.0.0', '2.9999.9999'], - ['<=2.0.0', '2.2.9'], - ['<2.0.0', '2.9999.9999'], - ['<2.0.0', '2.2.9'], - ['2.x.x', '3.1.3'], - ['1.2.x', '1.3.3'], - ['1.2.x || 2.x', '3.1.3'], - ['2.*.*', '3.1.3'], - ['1.2.*', '1.3.3'], - ['1.2.* || 2.*', '3.1.3'], - ['2', '3.1.2'], - ['2.3', '2.4.1'], - ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 - ['~>3.2.1', '3.3.2'], // >=3.2.1 <3.3.0 - ['~1', '2.2.3'], // >=1.0.0 <2.0.0 - ['~>1', '2.2.3'], - ['~1.0', '1.1.0'], // >=1.0.0 <1.1.0 - ['<1', '1.0.0'], - ['1', '2.0.0beta', true], - ['<1', '1.0.0beta', true], - ['< 1', '1.0.0beta', true], - ['=0.7.x', '0.8.2'], - ['<=0.7.x', '0.7.2'] - ].forEach(function(tuple) { - var range = tuple[0]; - var version = tuple[1]; - var loose = tuple[2] || false; - var msg = 'gtr(' + version + ', ' + range + ', ' + loose + ')'; - t.ok(gtr(version, range, loose), msg); - }); - t.end(); -}); - -test('\nnegative gtr tests', function(t) { - // [range, version, loose] - // Version should NOT be greater than range - [ - ['~0.6.1-1', '0.6.1-1'], - ['1.0.0 - 2.0.0', '1.2.3'], - ['1.0.0 - 2.0.0', '0.9.9'], - ['1.0.0', '1.0.0'], - ['>=*', '0.2.4'], - ['', '1.0.0', true], - ['*', '1.2.3'], - ['*', 'v1.2.3-foo'], - ['>=1.0.0', '1.0.0'], - ['>=1.0.0', '1.0.1'], - ['>=1.0.0', '1.1.0'], - ['>1.0.0', '1.0.1'], - ['>1.0.0', '1.1.0'], - ['<=2.0.0', '2.0.0'], - ['<=2.0.0', '1.9999.9999'], - ['<=2.0.0', '0.2.9'], - ['<2.0.0', '1.9999.9999'], - ['<2.0.0', '0.2.9'], - ['>= 1.0.0', '1.0.0'], - ['>= 1.0.0', '1.0.1'], - ['>= 1.0.0', '1.1.0'], - ['> 1.0.0', '1.0.1'], - ['> 1.0.0', '1.1.0'], - ['<= 2.0.0', '2.0.0'], - ['<= 2.0.0', '1.9999.9999'], - ['<= 2.0.0', '0.2.9'], - ['< 2.0.0', '1.9999.9999'], - ['<\t2.0.0', '0.2.9'], - ['>=0.1.97', 'v0.1.97'], - ['>=0.1.97', '0.1.97'], - ['0.1.20 || 1.2.4', '1.2.4'], - ['0.1.20 || >1.2.4', '1.2.4'], - ['0.1.20 || 1.2.4', '1.2.3'], - ['0.1.20 || 1.2.4', '0.1.20'], - ['>=0.2.3 || <0.0.1', '0.0.0'], - ['>=0.2.3 || <0.0.1', '0.2.3'], - ['>=0.2.3 || <0.0.1', '0.2.4'], - ['||', '1.3.4'], - ['2.x.x', '2.1.3'], - ['1.2.x', '1.2.3'], - ['1.2.x || 2.x', '2.1.3'], - ['1.2.x || 2.x', '1.2.3'], - ['x', '1.2.3'], - ['2.*.*', '2.1.3'], - ['1.2.*', '1.2.3'], - ['1.2.* || 2.*', '2.1.3'], - ['1.2.* || 2.*', '1.2.3'], - ['1.2.* || 2.*', '1.2.3'], - ['*', '1.2.3'], - ['2', '2.1.2'], - ['2.3', '2.3.1'], - ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 - ['~2.4', '2.4.5'], - ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0 - ['~1', '1.2.3'], // >=1.0.0 <2.0.0 - ['~>1', '1.2.3'], - ['~> 1', '1.2.3'], - ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0 - ['~ 1.0', '1.0.2'], - ['>=1', '1.0.0'], - ['>= 1', '1.0.0'], - ['<1.2', '1.1.1'], - ['< 1.2', '1.1.1'], - ['1', '1.0.0beta', true], - ['~v0.5.4-pre', '0.5.5'], - ['~v0.5.4-pre', '0.5.4'], - ['=0.7.x', '0.7.2'], - ['>=0.7.x', '0.7.2'], - ['=0.7.x', '0.7.0-asdf'], - ['>=0.7.x', '0.7.0-asdf'], - ['<=0.7.x', '0.6.2'], - ['>0.2.3 >0.2.4 <=0.2.5', '0.2.5'], - ['>=0.2.3 <=0.2.4', '0.2.4'], - ['1.0.0 - 2.0.0', '2.0.0'], - ['^1', '0.0.0-0'], - ['^3.0.0', '2.0.0'], - ['^1.0.0 || ~2.0.1', '2.0.0'], - ['^0.1.0 || ~3.0.1 || 5.0.0', '3.2.0'], - ['^0.1.0 || ~3.0.1 || 5.0.0', '1.0.0beta', true], - ['^0.1.0 || ~3.0.1 || 5.0.0', '5.0.0-0', true], - ['^0.1.0 || ~3.0.1 || >4 <=5.0.0', '3.5.0'] - ].forEach(function(tuple) { - var range = tuple[0]; - var version = tuple[1]; - var loose = tuple[2] || false; - var msg = '!gtr(' + version + ', ' + range + ', ' + loose + ')'; - t.notOk(gtr(version, range, loose), msg); - }); - t.end(); -}); diff --git a/node_modules/express3-handlebars/node_modules/semver/test/index.js b/node_modules/express3-handlebars/node_modules/semver/test/index.js deleted file mode 100644 index e6c9cefb0..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/test/index.js +++ /dev/null @@ -1,556 +0,0 @@ -var tap = require('tap'); -var test = tap.test; -var semver = require('../semver.js'); -var eq = semver.eq; -var gt = semver.gt; -var lt = semver.lt; -var neq = semver.neq; -var cmp = semver.cmp; -var gte = semver.gte; -var lte = semver.lte; -var satisfies = semver.satisfies; -var validRange = semver.validRange; -var inc = semver.inc; -var replaceStars = semver.replaceStars; -var toComparators = semver.toComparators; -var SemVer = semver.SemVer; -var Range = semver.Range; - -test('\ncomparison tests', function(t) { - // [version1, version2] - // version1 should be greater than version2 - [['0.0.0', '0.0.0-foo'], - ['0.0.1', '0.0.0'], - ['1.0.0', '0.9.9'], - ['0.10.0', '0.9.0'], - ['0.99.0', '0.10.0'], - ['2.0.0', '1.2.3'], - ['v0.0.0', '0.0.0-foo', true], - ['v0.0.1', '0.0.0', true], - ['v1.0.0', '0.9.9', true], - ['v0.10.0', '0.9.0', true], - ['v0.99.0', '0.10.0', true], - ['v2.0.0', '1.2.3', true], - ['0.0.0', 'v0.0.0-foo', true], - ['0.0.1', 'v0.0.0', true], - ['1.0.0', 'v0.9.9', true], - ['0.10.0', 'v0.9.0', true], - ['0.99.0', 'v0.10.0', true], - ['2.0.0', 'v1.2.3', true], - ['1.2.3', '1.2.3-asdf'], - ['1.2.3', '1.2.3-4'], - ['1.2.3', '1.2.3-4-foo'], - ['1.2.3-5-foo', '1.2.3-5'], - ['1.2.3-5', '1.2.3-4'], - ['1.2.3-5-foo', '1.2.3-5-Foo'], - ['3.0.0', '2.7.2+asdf'], - ['1.2.3-a.10', '1.2.3-a.5'], - ['1.2.3-a.b', '1.2.3-a.5'], - ['1.2.3-a.b', '1.2.3-a'], - ['1.2.3-a.b.c.10.d.5', '1.2.3-a.b.c.5.d.100'] - ].forEach(function(v) { - var v0 = v[0]; - var v1 = v[1]; - var loose = v[2]; - t.ok(gt(v0, v1, loose), "gt('" + v0 + "', '" + v1 + "')"); - t.ok(lt(v1, v0, loose), "lt('" + v1 + "', '" + v0 + "')"); - t.ok(!gt(v1, v0, loose), "!gt('" + v1 + "', '" + v0 + "')"); - t.ok(!lt(v0, v1, loose), "!lt('" + v0 + "', '" + v1 + "')"); - t.ok(eq(v0, v0, loose), "eq('" + v0 + "', '" + v0 + "')"); - t.ok(eq(v1, v1, loose), "eq('" + v1 + "', '" + v1 + "')"); - t.ok(neq(v0, v1, loose), "neq('" + v0 + "', '" + v1 + "')"); - t.ok(cmp(v1, '==', v1, loose), "cmp('" + v1 + "' == '" + v1 + "')"); - t.ok(cmp(v0, '>=', v1, loose), "cmp('" + v0 + "' >= '" + v1 + "')"); - t.ok(cmp(v1, '<=', v0, loose), "cmp('" + v1 + "' <= '" + v0 + "')"); - t.ok(cmp(v0, '!=', v1, loose), "cmp('" + v0 + "' != '" + v1 + "')"); - }); - t.end(); -}); - -test('\nequality tests', function(t) { - // [version1, version2] - // version1 should be equivalent to version2 - [['1.2.3', 'v1.2.3', true], - ['1.2.3', '=1.2.3', true], - ['1.2.3', 'v 1.2.3', true], - ['1.2.3', '= 1.2.3', true], - ['1.2.3', ' v1.2.3', true], - ['1.2.3', ' =1.2.3', true], - ['1.2.3', ' v 1.2.3', true], - ['1.2.3', ' = 1.2.3', true], - ['1.2.3-0', 'v1.2.3-0', true], - ['1.2.3-0', '=1.2.3-0', true], - ['1.2.3-0', 'v 1.2.3-0', true], - ['1.2.3-0', '= 1.2.3-0', true], - ['1.2.3-0', ' v1.2.3-0', true], - ['1.2.3-0', ' =1.2.3-0', true], - ['1.2.3-0', ' v 1.2.3-0', true], - ['1.2.3-0', ' = 1.2.3-0', true], - ['1.2.3-1', 'v1.2.3-1', true], - ['1.2.3-1', '=1.2.3-1', true], - ['1.2.3-1', 'v 1.2.3-1', true], - ['1.2.3-1', '= 1.2.3-1', true], - ['1.2.3-1', ' v1.2.3-1', true], - ['1.2.3-1', ' =1.2.3-1', true], - ['1.2.3-1', ' v 1.2.3-1', true], - ['1.2.3-1', ' = 1.2.3-1', true], - ['1.2.3-beta', 'v1.2.3-beta', true], - ['1.2.3-beta', '=1.2.3-beta', true], - ['1.2.3-beta', 'v 1.2.3-beta', true], - ['1.2.3-beta', '= 1.2.3-beta', true], - ['1.2.3-beta', ' v1.2.3-beta', true], - ['1.2.3-beta', ' =1.2.3-beta', true], - ['1.2.3-beta', ' v 1.2.3-beta', true], - ['1.2.3-beta', ' = 1.2.3-beta', true], - ['1.2.3-beta+build', ' = 1.2.3-beta+otherbuild', true], - ['1.2.3+build', ' = 1.2.3+otherbuild', true], - ['1.2.3-beta+build', '1.2.3-beta+otherbuild'], - ['1.2.3+build', '1.2.3+otherbuild'], - [' v1.2.3+build', '1.2.3+otherbuild'] - ].forEach(function(v) { - var v0 = v[0]; - var v1 = v[1]; - var loose = v[2]; - t.ok(eq(v0, v1, loose), "eq('" + v0 + "', '" + v1 + "')"); - t.ok(!neq(v0, v1, loose), "!neq('" + v0 + "', '" + v1 + "')"); - t.ok(cmp(v0, '==', v1, loose), 'cmp(' + v0 + '==' + v1 + ')'); - t.ok(!cmp(v0, '!=', v1, loose), '!cmp(' + v0 + '!=' + v1 + ')'); - t.ok(!cmp(v0, '===', v1, loose), '!cmp(' + v0 + '===' + v1 + ')'); - t.ok(cmp(v0, '!==', v1, loose), 'cmp(' + v0 + '!==' + v1 + ')'); - t.ok(!gt(v0, v1, loose), "!gt('" + v0 + "', '" + v1 + "')"); - t.ok(gte(v0, v1, loose), "gte('" + v0 + "', '" + v1 + "')"); - t.ok(!lt(v0, v1, loose), "!lt('" + v0 + "', '" + v1 + "')"); - t.ok(lte(v0, v1, loose), "lte('" + v0 + "', '" + v1 + "')"); - }); - t.end(); -}); - - -test('\nrange tests', function(t) { - // [range, version] - // version should be included by range - [['1.0.0 - 2.0.0', '1.2.3'], - ['1.0.0', '1.0.0'], - ['>=*', '0.2.4'], - ['', '1.0.0'], - ['*', '1.2.3'], - ['*', 'v1.2.3-foo', true], - ['>=1.0.0', '1.0.0'], - ['>=1.0.0', '1.0.1'], - ['>=1.0.0', '1.1.0'], - ['>1.0.0', '1.0.1'], - ['>1.0.0', '1.1.0'], - ['<=2.0.0', '2.0.0'], - ['<=2.0.0', '1.9999.9999'], - ['<=2.0.0', '0.2.9'], - ['<2.0.0', '1.9999.9999'], - ['<2.0.0', '0.2.9'], - ['>= 1.0.0', '1.0.0'], - ['>= 1.0.0', '1.0.1'], - ['>= 1.0.0', '1.1.0'], - ['> 1.0.0', '1.0.1'], - ['> 1.0.0', '1.1.0'], - ['<= 2.0.0', '2.0.0'], - ['<= 2.0.0', '1.9999.9999'], - ['<= 2.0.0', '0.2.9'], - ['< 2.0.0', '1.9999.9999'], - ['<\t2.0.0', '0.2.9'], - ['>=0.1.97', 'v0.1.97', true], - ['>=0.1.97', '0.1.97'], - ['0.1.20 || 1.2.4', '1.2.4'], - ['>=0.2.3 || <0.0.1', '0.0.0'], - ['>=0.2.3 || <0.0.1', '0.2.3'], - ['>=0.2.3 || <0.0.1', '0.2.4'], - ['||', '1.3.4'], - ['2.x.x', '2.1.3'], - ['1.2.x', '1.2.3'], - ['1.2.x || 2.x', '2.1.3'], - ['1.2.x || 2.x', '1.2.3'], - ['x', '1.2.3'], - ['2.*.*', '2.1.3'], - ['1.2.*', '1.2.3'], - ['1.2.* || 2.*', '2.1.3'], - ['1.2.* || 2.*', '1.2.3'], - ['*', '1.2.3'], - ['2', '2.1.2'], - ['2.3', '2.3.1'], - ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 - ['~2.4', '2.4.5'], - ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0, - ['~1', '1.2.3'], // >=1.0.0 <2.0.0 - ['~>1', '1.2.3'], - ['~> 1', '1.2.3'], - ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0, - ['~ 1.0', '1.0.2'], - ['~ 1.0.3', '1.0.12'], - ['>=1', '1.0.0'], - ['>= 1', '1.0.0'], - ['<1.2', '1.1.1'], - ['< 1.2', '1.1.1'], - ['1', '1.0.0beta', true], - ['~v0.5.4-pre', '0.5.5'], - ['~v0.5.4-pre', '0.5.4'], - ['=0.7.x', '0.7.2'], - ['>=0.7.x', '0.7.2'], - ['=0.7.x', '0.7.0-asdf'], - ['>=0.7.x', '0.7.0-asdf'], - ['<=0.7.x', '0.6.2'], - ['~1.2.1 >=1.2.3', '1.2.3'], - ['~1.2.1 =1.2.3', '1.2.3'], - ['~1.2.1 1.2.3', '1.2.3'], - ['~1.2.1 >=1.2.3 1.2.3', '1.2.3'], - ['~1.2.1 1.2.3 >=1.2.3', '1.2.3'], - ['~1.2.1 1.2.3', '1.2.3'], - ['>=1.2.1 1.2.3', '1.2.3'], - ['1.2.3 >=1.2.1', '1.2.3'], - ['>=1.2.3 >=1.2.1', '1.2.3'], - ['>=1.2.1 >=1.2.3', '1.2.3'], - ['<=1.2.3', '1.2.3-beta'], - ['>1.2', '1.3.0-beta'], - ['>=1.2', '1.2.8'], - ['^1.2.3', '1.8.1'], - ['^1.2.3', '1.2.3-beta'], - ['^0.1.2', '0.1.2'], - ['^0.1', '0.1.2'], - ['^1.2', '1.4.2'], - ['^1.2 ^1', '1.4.2'], - ['^1.2', '1.2.0-pre'], - ['^1.2.3', '1.2.3-pre'] - ].forEach(function(v) { - var range = v[0]; - var ver = v[1]; - var loose = v[2]; - t.ok(satisfies(ver, range, loose), range + ' satisfied by ' + ver); - }); - t.end(); -}); - -test('\nnegative range tests', function(t) { - // [range, version] - // version should not be included by range - [['1.0.0 - 2.0.0', '2.2.3'], - ['1.0.0', '1.0.1'], - ['>=1.0.0', '0.0.0'], - ['>=1.0.0', '0.0.1'], - ['>=1.0.0', '0.1.0'], - ['>1.0.0', '0.0.1'], - ['>1.0.0', '0.1.0'], - ['<=2.0.0', '3.0.0'], - ['<=2.0.0', '2.9999.9999'], - ['<=2.0.0', '2.2.9'], - ['<2.0.0', '2.9999.9999'], - ['<2.0.0', '2.2.9'], - ['>=0.1.97', 'v0.1.93', true], - ['>=0.1.97', '0.1.93'], - ['0.1.20 || 1.2.4', '1.2.3'], - ['>=0.2.3 || <0.0.1', '0.0.3'], - ['>=0.2.3 || <0.0.1', '0.2.2'], - ['2.x.x', '1.1.3'], - ['2.x.x', '3.1.3'], - ['1.2.x', '1.3.3'], - ['1.2.x || 2.x', '3.1.3'], - ['1.2.x || 2.x', '1.1.3'], - ['2.*.*', '1.1.3'], - ['2.*.*', '3.1.3'], - ['1.2.*', '1.3.3'], - ['1.2.* || 2.*', '3.1.3'], - ['1.2.* || 2.*', '1.1.3'], - ['2', '1.1.2'], - ['2.3', '2.4.1'], - ['~2.4', '2.5.0'], // >=2.4.0 <2.5.0 - ['~2.4', '2.3.9'], - ['~>3.2.1', '3.3.2'], // >=3.2.1 <3.3.0 - ['~>3.2.1', '3.2.0'], // >=3.2.1 <3.3.0 - ['~1', '0.2.3'], // >=1.0.0 <2.0.0 - ['~>1', '2.2.3'], - ['~1.0', '1.1.0'], // >=1.0.0 <1.1.0 - ['<1', '1.0.0'], - ['>=1.2', '1.1.1'], - ['1', '2.0.0beta', true], - ['~v0.5.4-beta', '0.5.4-alpha'], - ['<1', '1.0.0beta', true], - ['< 1', '1.0.0beta', true], - ['=0.7.x', '0.8.2'], - ['>=0.7.x', '0.6.2'], - ['<=0.7.x', '0.7.2'], - ['<1.2.3', '1.2.3-beta'], - ['=1.2.3', '1.2.3-beta'], - ['>1.2', '1.2.8'], - ['^1.2.3', '2.0.0-alpha'], - ['^1.2.3', '1.2.2'], - ['^1.2', '1.1.9'], - // invalid ranges never satisfied! - ['blerg', '1.2.3'], - ['git+https://user:password0123@github.com/foo', '123.0.0', true], - ['^1.2.3', '2.0.0-pre'] - ].forEach(function(v) { - var range = v[0]; - var ver = v[1]; - var loose = v[2]; - var found = satisfies(ver, range, loose); - t.ok(!found, ver + ' not satisfied by ' + range); - }); - t.end(); -}); - -test('\nincrement versions test', function(t) { - // [version, inc, result] - // inc(version, inc) -> result - [['1.2.3', 'major', '2.0.0'], - ['1.2.3', 'minor', '1.3.0'], - ['1.2.3', 'patch', '1.2.4'], - ['1.2.3tag', 'major', '2.0.0', true], - ['1.2.3-tag', 'major', '2.0.0'], - ['1.2.3', 'fake', null], - ['fake', 'major', null], - ['1.2.3', 'prerelease', '1.2.3-0'], - ['1.2.3-0', 'prerelease', '1.2.3-1'], - ['1.2.3-alpha.0', 'prerelease', '1.2.3-alpha.1'], - ['1.2.3-alpha.1', 'prerelease', '1.2.3-alpha.2'], - ['1.2.3-alpha.2', 'prerelease', '1.2.3-alpha.3'], - ['1.2.3-alpha.0.beta', 'prerelease', '1.2.3-alpha.1.beta'], - ['1.2.3-alpha.1.beta', 'prerelease', '1.2.3-alpha.2.beta'], - ['1.2.3-alpha.2.beta', 'prerelease', '1.2.3-alpha.3.beta'], - ['1.2.3-alpha.10.0.beta', 'prerelease', '1.2.3-alpha.10.1.beta'], - ['1.2.3-alpha.10.1.beta', 'prerelease', '1.2.3-alpha.10.2.beta'], - ['1.2.3-alpha.10.2.beta', 'prerelease', '1.2.3-alpha.10.3.beta'], - ['1.2.3-alpha.10.beta.0', 'prerelease', '1.2.3-alpha.10.beta.1'], - ['1.2.3-alpha.10.beta.1', 'prerelease', '1.2.3-alpha.10.beta.2'], - ['1.2.3-alpha.10.beta.2', 'prerelease', '1.2.3-alpha.10.beta.3'], - ['1.2.3-alpha.9.beta', 'prerelease', '1.2.3-alpha.10.beta'], - ['1.2.3-alpha.10.beta', 'prerelease', '1.2.3-alpha.11.beta'], - ['1.2.3-alpha.11.beta', 'prerelease', '1.2.3-alpha.12.beta'] - ].forEach(function(v) { - var pre = v[0]; - var what = v[1]; - var wanted = v[2]; - var loose = v[3]; - var found = inc(pre, what, loose); - t.equal(found, wanted, 'inc(' + pre + ', ' + what + ') === ' + wanted); - }); - - t.end(); -}); - -test('\nvalid range test', function(t) { - // [range, result] - // validRange(range) -> result - // translate ranges into their canonical form - [['1.0.0 - 2.0.0', '>=1.0.0 <=2.0.0'], - ['1.0.0', '1.0.0'], - ['>=*', '>=0.0.0-0'], - ['', '*'], - ['*', '*'], - ['*', '*'], - ['>=1.0.0', '>=1.0.0'], - ['>1.0.0', '>1.0.0'], - ['<=2.0.0', '<=2.0.0'], - ['1', '>=1.0.0-0 <2.0.0-0'], - ['<=2.0.0', '<=2.0.0'], - ['<=2.0.0', '<=2.0.0'], - ['<2.0.0', '<2.0.0-0'], - ['<2.0.0', '<2.0.0-0'], - ['>= 1.0.0', '>=1.0.0'], - ['>= 1.0.0', '>=1.0.0'], - ['>= 1.0.0', '>=1.0.0'], - ['> 1.0.0', '>1.0.0'], - ['> 1.0.0', '>1.0.0'], - ['<= 2.0.0', '<=2.0.0'], - ['<= 2.0.0', '<=2.0.0'], - ['<= 2.0.0', '<=2.0.0'], - ['< 2.0.0', '<2.0.0-0'], - ['< 2.0.0', '<2.0.0-0'], - ['>=0.1.97', '>=0.1.97'], - ['>=0.1.97', '>=0.1.97'], - ['0.1.20 || 1.2.4', '0.1.20||1.2.4'], - ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1-0'], - ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1-0'], - ['>=0.2.3 || <0.0.1', '>=0.2.3||<0.0.1-0'], - ['||', '||'], - ['2.x.x', '>=2.0.0-0 <3.0.0-0'], - ['1.2.x', '>=1.2.0-0 <1.3.0-0'], - ['1.2.x || 2.x', '>=1.2.0-0 <1.3.0-0||>=2.0.0-0 <3.0.0-0'], - ['1.2.x || 2.x', '>=1.2.0-0 <1.3.0-0||>=2.0.0-0 <3.0.0-0'], - ['x', '*'], - ['2.*.*', '>=2.0.0-0 <3.0.0-0'], - ['1.2.*', '>=1.2.0-0 <1.3.0-0'], - ['1.2.* || 2.*', '>=1.2.0-0 <1.3.0-0||>=2.0.0-0 <3.0.0-0'], - ['*', '*'], - ['2', '>=2.0.0-0 <3.0.0-0'], - ['2.3', '>=2.3.0-0 <2.4.0-0'], - ['~2.4', '>=2.4.0-0 <2.5.0-0'], - ['~2.4', '>=2.4.0-0 <2.5.0-0'], - ['~>3.2.1', '>=3.2.1-0 <3.3.0-0'], - ['~1', '>=1.0.0-0 <2.0.0-0'], - ['~>1', '>=1.0.0-0 <2.0.0-0'], - ['~> 1', '>=1.0.0-0 <2.0.0-0'], - ['~1.0', '>=1.0.0-0 <1.1.0-0'], - ['~ 1.0', '>=1.0.0-0 <1.1.0-0'], - ['^0', '>=0.0.0-0 <1.0.0-0'], - ['^ 1', '>=1.0.0-0 <2.0.0-0'], - ['^0.1', '>=0.1.0-0 <0.2.0-0'], - ['^1.0', '>=1.0.0-0 <2.0.0-0'], - ['^1.2', '>=1.2.0-0 <2.0.0-0'], - ['^0.0.1', '=0.0.1'], - ['^0.0.1-beta', '=0.0.1-beta'], - ['^0.1.2', '>=0.1.2-0 <0.2.0-0'], - ['^1.2.3', '>=1.2.3-0 <2.0.0-0'], - ['^1.2.3-beta.4', '>=1.2.3-beta.4 <2.0.0-0'], - ['<1', '<1.0.0-0'], - ['< 1', '<1.0.0-0'], - ['>=1', '>=1.0.0-0'], - ['>= 1', '>=1.0.0-0'], - ['<1.2', '<1.2.0-0'], - ['< 1.2', '<1.2.0-0'], - ['1', '>=1.0.0-0 <2.0.0-0'], - ['>01.02.03', '>1.2.3', true], - ['>01.02.03', null], - ['~1.2.3beta', '>=1.2.3-beta <1.3.0-0', true], - ['~1.2.3beta', null], - ['^ 1.2 ^ 1', '>=1.2.0-0 <2.0.0-0 >=1.0.0-0 <2.0.0-0'] - ].forEach(function(v) { - var pre = v[0]; - var wanted = v[1]; - var loose = v[2]; - var found = validRange(pre, loose); - - t.equal(found, wanted, 'validRange(' + pre + ') === ' + wanted); - }); - - t.end(); -}); - -test('\ncomparators test', function(t) { - // [range, comparators] - // turn range into a set of individual comparators - [['1.0.0 - 2.0.0', [['>=1.0.0', '<=2.0.0']]], - ['1.0.0', [['1.0.0']]], - ['>=*', [['>=0.0.0-0']]], - ['', [['']]], - ['*', [['']]], - ['*', [['']]], - ['>=1.0.0', [['>=1.0.0']]], - ['>=1.0.0', [['>=1.0.0']]], - ['>=1.0.0', [['>=1.0.0']]], - ['>1.0.0', [['>1.0.0']]], - ['>1.0.0', [['>1.0.0']]], - ['<=2.0.0', [['<=2.0.0']]], - ['1', [['>=1.0.0-0', '<2.0.0-0']]], - ['<=2.0.0', [['<=2.0.0']]], - ['<=2.0.0', [['<=2.0.0']]], - ['<2.0.0', [['<2.0.0-0']]], - ['<2.0.0', [['<2.0.0-0']]], - ['>= 1.0.0', [['>=1.0.0']]], - ['>= 1.0.0', [['>=1.0.0']]], - ['>= 1.0.0', [['>=1.0.0']]], - ['> 1.0.0', [['>1.0.0']]], - ['> 1.0.0', [['>1.0.0']]], - ['<= 2.0.0', [['<=2.0.0']]], - ['<= 2.0.0', [['<=2.0.0']]], - ['<= 2.0.0', [['<=2.0.0']]], - ['< 2.0.0', [['<2.0.0-0']]], - ['<\t2.0.0', [['<2.0.0-0']]], - ['>=0.1.97', [['>=0.1.97']]], - ['>=0.1.97', [['>=0.1.97']]], - ['0.1.20 || 1.2.4', [['0.1.20'], ['1.2.4']]], - ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1-0']]], - ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1-0']]], - ['>=0.2.3 || <0.0.1', [['>=0.2.3'], ['<0.0.1-0']]], - ['||', [[''], ['']]], - ['2.x.x', [['>=2.0.0-0', '<3.0.0-0']]], - ['1.2.x', [['>=1.2.0-0', '<1.3.0-0']]], - ['1.2.x || 2.x', [['>=1.2.0-0', '<1.3.0-0'], ['>=2.0.0-0', '<3.0.0-0']]], - ['1.2.x || 2.x', [['>=1.2.0-0', '<1.3.0-0'], ['>=2.0.0-0', '<3.0.0-0']]], - ['x', [['']]], - ['2.*.*', [['>=2.0.0-0', '<3.0.0-0']]], - ['1.2.*', [['>=1.2.0-0', '<1.3.0-0']]], - ['1.2.* || 2.*', [['>=1.2.0-0', '<1.3.0-0'], ['>=2.0.0-0', '<3.0.0-0']]], - ['1.2.* || 2.*', [['>=1.2.0-0', '<1.3.0-0'], ['>=2.0.0-0', '<3.0.0-0']]], - ['*', [['']]], - ['2', [['>=2.0.0-0', '<3.0.0-0']]], - ['2.3', [['>=2.3.0-0', '<2.4.0-0']]], - ['~2.4', [['>=2.4.0-0', '<2.5.0-0']]], - ['~2.4', [['>=2.4.0-0', '<2.5.0-0']]], - ['~>3.2.1', [['>=3.2.1-0', '<3.3.0-0']]], - ['~1', [['>=1.0.0-0', '<2.0.0-0']]], - ['~>1', [['>=1.0.0-0', '<2.0.0-0']]], - ['~> 1', [['>=1.0.0-0', '<2.0.0-0']]], - ['~1.0', [['>=1.0.0-0', '<1.1.0-0']]], - ['~ 1.0', [['>=1.0.0-0', '<1.1.0-0']]], - ['~ 1.0.3', [['>=1.0.3-0', '<1.1.0-0']]], - ['~> 1.0.3', [['>=1.0.3-0', '<1.1.0-0']]], - ['<1', [['<1.0.0-0']]], - ['< 1', [['<1.0.0-0']]], - ['>=1', [['>=1.0.0-0']]], - ['>= 1', [['>=1.0.0-0']]], - ['<1.2', [['<1.2.0-0']]], - ['< 1.2', [['<1.2.0-0']]], - ['1', [['>=1.0.0-0', '<2.0.0-0']]], - ['1 2', [['>=1.0.0-0', '<2.0.0-0', '>=2.0.0-0', '<3.0.0-0']]], - ['1.2 - 3.4.5', [['>=1.2.0-0', '<=3.4.5']]], - ['1.2.3 - 3.4', [['>=1.2.3', '<3.5.0-0']]] - ].forEach(function(v) { - var pre = v[0]; - var wanted = v[1]; - var found = toComparators(v[0]); - var jw = JSON.stringify(wanted); - t.equivalent(found, wanted, 'toComparators(' + pre + ') === ' + jw); - }); - - t.end(); -}); - -test('\nstrict vs loose version numbers', function(t) { - [['=1.2.3', '1.2.3'], - ['01.02.03', '1.2.3'], - ['1.2.3-beta.01', '1.2.3-beta.1'], - [' =1.2.3', '1.2.3'], - ['1.2.3foo', '1.2.3-foo'] - ].forEach(function(v) { - var loose = v[0]; - var strict = v[1]; - t.throws(function() { - new SemVer(loose); - }); - var lv = new SemVer(loose, true); - t.equal(lv.version, strict); - t.ok(eq(loose, strict, true)); - t.throws(function() { - eq(loose, strict); - }); - t.throws(function() { - new SemVer(strict).compare(loose); - }); - }); - t.end(); -}); - -test('\nstrict vs loose ranges', function(t) { - [['>=01.02.03', '>=1.2.3'], - ['~1.02.03beta', '>=1.2.3-beta <1.3.0-0'] - ].forEach(function(v) { - var loose = v[0]; - var comps = v[1]; - t.throws(function() { - new Range(loose); - }); - t.equal(new Range(loose, true).range, comps); - }); - t.end(); -}); - -test('\nmax satisfying', function(t) { - [[['1.2.3', '1.2.4'], '1.2', '1.2.4'], - [['1.2.4', '1.2.3'], '1.2', '1.2.4'], - [['1.2.3', '1.2.4', '1.2.5', '1.2.6'], '~1.2.3', '1.2.6'], - [['1.1.0', '1.2.0', '1.2.1', '1.3.0', '2.0.0b1', '2.0.0b2', '2.0.0b3', '2.0.0', '2.1.0'], '~2.0.0', '2.0.0', true] - ].forEach(function(v) { - var versions = v[0]; - var range = v[1]; - var expect = v[2]; - var loose = v[3]; - var actual = semver.maxSatisfying(versions, range, loose); - t.equal(actual, expect); - }); - t.end(); -}); diff --git a/node_modules/express3-handlebars/node_modules/semver/test/ltr.js b/node_modules/express3-handlebars/node_modules/semver/test/ltr.js deleted file mode 100644 index a4f503a3c..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/test/ltr.js +++ /dev/null @@ -1,174 +0,0 @@ -var tap = require('tap'); -var test = tap.test; -var semver = require('../semver.js'); -var ltr = semver.ltr; - -test('\nltr tests', function(t) { - // [range, version, loose] - // Version should be less than range - [ - ['~1.2.2', '1.2.1'], - ['~0.6.1-1', '0.6.1-0'], - ['1.0.0 - 2.0.0', '0.0.1'], - ['1.0.0-beta.2', '1.0.0-beta.1'], - ['1.0.0', '0.0.0'], - ['>=2.0.0', '1.1.1'], - ['>=2.0.0', '1.2.9'], - ['>2.0.0', '2.0.0'], - ['0.1.20 || 1.2.4', '0.1.5'], - ['2.x.x', '1.0.0'], - ['1.2.x', '1.1.0'], - ['1.2.x || 2.x', '1.0.0'], - ['2.*.*', '1.0.1'], - ['1.2.*', '1.1.3'], - ['1.2.* || 2.*', '1.1.9999'], - ['2', '1.0.0'], - ['2.3', '2.2.2'], - ['~2.4', '2.3.0'], // >=2.4.0 <2.5.0 - ['~2.4', '2.3.5'], - ['~>3.2.1', '3.2.0'], // >=3.2.1 <3.3.0 - ['~1', '0.2.3'], // >=1.0.0 <2.0.0 - ['~>1', '0.2.4'], - ['~> 1', '0.2.3'], - ['~1.0', '0.1.2'], // >=1.0.0 <1.1.0 - ['~ 1.0', '0.1.0'], - ['>1.2', '1.2.0'], - ['> 1.2', '1.2.1'], - ['1', '0.0.0beta', true], - ['~v0.5.4-pre', '0.5.4-alpha'], - ['~v0.5.4-pre', '0.5.4-alpha'], - ['=0.7.x', '0.6.0'], - ['=0.7.x', '0.6.0-asdf'], - ['>=0.7.x', '0.6.0'], - ['~1.2.2', '1.2.1'], - ['1.0.0 - 2.0.0', '0.2.3'], - ['1.0.0', '0.0.1'], - ['>=2.0.0', '1.0.0'], - ['>=2.0.0', '1.9999.9999'], - ['>=2.0.0', '1.2.9'], - ['>2.0.0', '2.0.0'], - ['>2.0.0', '1.2.9'], - ['2.x.x', '1.1.3'], - ['1.2.x', '1.1.3'], - ['1.2.x || 2.x', '1.1.3'], - ['2.*.*', '1.1.3'], - ['1.2.*', '1.1.3'], - ['1.2.* || 2.*', '1.1.3'], - ['2', '1.9999.9999'], - ['2.3', '2.2.1'], - ['~2.4', '2.3.0'], // >=2.4.0 <2.5.0 - ['~>3.2.1', '2.3.2'], // >=3.2.1 <3.3.0 - ['~1', '0.2.3'], // >=1.0.0 <2.0.0 - ['~>1', '0.2.3'], - ['~1.0', '0.0.0'], // >=1.0.0 <1.1.0 - ['>1', '1.0.0'], - ['2', '1.0.0beta', true], - ['>1', '1.0.0beta', true], - ['> 1', '1.0.0beta', true], - ['=0.7.x', '0.6.2'], - ['>=0.7.x', '0.6.2'] - ].forEach(function(tuple) { - var range = tuple[0]; - var version = tuple[1]; - var loose = tuple[2] || false; - var msg = 'ltr(' + version + ', ' + range + ', ' + loose + ')'; - t.ok(ltr(version, range, loose), msg); - }); - t.end(); -}); - -test('\nnegative ltr tests', function(t) { - // [range, version, loose] - // Version should NOT be greater than range - [ - ['~ 1.0', '1.1.0'], - ['~0.6.1-1', '0.6.1-1'], - ['1.0.0 - 2.0.0', '1.2.3'], - ['1.0.0 - 2.0.0', '2.9.9'], - ['1.0.0', '1.0.0'], - ['>=*', '0.2.4'], - ['', '1.0.0', true], - ['*', '1.2.3'], - ['*', 'v1.2.3-foo'], - ['>=1.0.0', '1.0.0'], - ['>=1.0.0', '1.0.1'], - ['>=1.0.0', '1.1.0'], - ['>1.0.0', '1.0.1'], - ['>1.0.0', '1.1.0'], - ['<=2.0.0', '2.0.0'], - ['<=2.0.0', '1.9999.9999'], - ['<=2.0.0', '0.2.9'], - ['<2.0.0', '1.9999.9999'], - ['<2.0.0', '0.2.9'], - ['>= 1.0.0', '1.0.0'], - ['>= 1.0.0', '1.0.1'], - ['>= 1.0.0', '1.1.0'], - ['> 1.0.0', '1.0.1'], - ['> 1.0.0', '1.1.0'], - ['<= 2.0.0', '2.0.0'], - ['<= 2.0.0', '1.9999.9999'], - ['<= 2.0.0', '0.2.9'], - ['< 2.0.0', '1.9999.9999'], - ['<\t2.0.0', '0.2.9'], - ['>=0.1.97', 'v0.1.97'], - ['>=0.1.97', '0.1.97'], - ['0.1.20 || 1.2.4', '1.2.4'], - ['0.1.20 || >1.2.4', '1.2.4'], - ['0.1.20 || 1.2.4', '1.2.3'], - ['0.1.20 || 1.2.4', '0.1.20'], - ['>=0.2.3 || <0.0.1', '0.0.0'], - ['>=0.2.3 || <0.0.1', '0.2.3'], - ['>=0.2.3 || <0.0.1', '0.2.4'], - ['||', '1.3.4'], - ['2.x.x', '2.1.3'], - ['1.2.x', '1.2.3'], - ['1.2.x || 2.x', '2.1.3'], - ['1.2.x || 2.x', '1.2.3'], - ['x', '1.2.3'], - ['2.*.*', '2.1.3'], - ['1.2.*', '1.2.3'], - ['1.2.* || 2.*', '2.1.3'], - ['1.2.* || 2.*', '1.2.3'], - ['1.2.* || 2.*', '1.2.3'], - ['*', '1.2.3'], - ['2', '2.1.2'], - ['2.3', '2.3.1'], - ['~2.4', '2.4.0'], // >=2.4.0 <2.5.0 - ['~2.4', '2.4.5'], - ['~>3.2.1', '3.2.2'], // >=3.2.1 <3.3.0 - ['~1', '1.2.3'], // >=1.0.0 <2.0.0 - ['~>1', '1.2.3'], - ['~> 1', '1.2.3'], - ['~1.0', '1.0.2'], // >=1.0.0 <1.1.0 - ['~ 1.0', '1.0.2'], - ['>=1', '1.0.0'], - ['>= 1', '1.0.0'], - ['<1.2', '1.1.1'], - ['< 1.2', '1.1.1'], - ['1', '1.0.0beta', true], - ['~v0.5.4-pre', '0.5.5'], - ['~v0.5.4-pre', '0.5.4'], - ['=0.7.x', '0.7.2'], - ['>=0.7.x', '0.7.2'], - ['=0.7.x', '0.7.0-asdf'], - ['>=0.7.x', '0.7.0-asdf'], - ['<=0.7.x', '0.6.2'], - ['>0.2.3 >0.2.4 <=0.2.5', '0.2.5'], - ['>=0.2.3 <=0.2.4', '0.2.4'], - ['1.0.0 - 2.0.0', '2.0.0'], - ['^1', '1.0.0-0'], - ['^3.0.0', '4.0.0'], - ['^1.0.0 || ~2.0.1', '2.0.0'], - ['^0.1.0 || ~3.0.1 || 5.0.0', '3.2.0'], - ['^0.1.0 || ~3.0.1 || 5.0.0', '1.0.0beta', true], - ['^0.1.0 || ~3.0.1 || 5.0.0', '5.0.0-0', true], - ['^0.1.0 || ~3.0.1 || >4 <=5.0.0', '3.5.0'] - ].forEach(function(tuple) { - var range = tuple[0]; - var version = tuple[1]; - var loose = tuple[2] || false; - var msg = '!ltr(' + version + ', ' + range + ', ' + loose + ')'; - t.notOk(ltr(version, range, loose), msg); - }); - t.end(); -}); diff --git a/node_modules/express3-handlebars/node_modules/semver/test/no-module.js b/node_modules/express3-handlebars/node_modules/semver/test/no-module.js deleted file mode 100644 index 96d1cd1fc..000000000 --- a/node_modules/express3-handlebars/node_modules/semver/test/no-module.js +++ /dev/null @@ -1,19 +0,0 @@ -var tap = require('tap'); -var test = tap.test; - -test('no module system', function(t) { - var fs = require('fs'); - var vm = require('vm'); - var head = fs.readFileSync(require.resolve('../head.js'), 'utf8'); - var src = fs.readFileSync(require.resolve('../'), 'utf8'); - var foot = fs.readFileSync(require.resolve('../foot.js'), 'utf8'); - vm.runInThisContext(head + src + foot, 'semver.js'); - - // just some basic poking to see if it did some stuff - t.type(global.semver, 'object'); - t.type(global.semver.SemVer, 'function'); - t.type(global.semver.Range, 'function'); - t.ok(global.semver.satisfies('1.2.3', '1.2')); - t.end(); -}); - diff --git a/node_modules/express3-handlebars/package.json b/node_modules/express3-handlebars/package.json deleted file mode 100644 index 234a58d0b..000000000 --- a/node_modules/express3-handlebars/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "express3-handlebars", - "description": "A Handlebars view engine for Express which doesn't suck.", - "version": "0.5.0", - "homepage": "https://github.com/ericf/express3-handlebars", - "keywords": [ - "express", - "express3", - "handlebars", - "view", - "layout", - "partials" - ], - "author": { - "name": "Eric Ferraiuolo", - "email": "eferraiuolo@gmail.com", - "url": "http://ericf.me/" - }, - "repository": { - "type": "git", - "url": "git://github.com/ericf/express3-handlebars.git" - }, - "bugs": { - "url": "https://github.com/ericf/express3-handlebars/issues" - }, - "engines": { - "node": ">=0.8" - }, - "dependencies": { - "async": "~0.2", - "glob": "3.x", - "handlebars": "1.x", - "semver": "2.x" - }, - "devDependencies": { - "express": "3.x" - }, - "main": "index.js", - "directories": { - "lib": "./lib" - }, - "readme": "Express3 Handlebars\n===================\n\nA [Handlebars][] view engine for [Express][] which doesn't suck.\n\n[![Dependency Status](https://david-dm.org/ericf/express3-handlebars.png)][status]\n\n\n[Express]: https://github.com/visionmedia/express\n[Handlebars]: https://github.com/wycats/handlebars.js\n[status]: https://david-dm.org/ericf/express3-handlebars\n\n\nGoals & Design\n--------------\n\nI created this project out of frustration with the existing Handlebars view\nengines for Express. As of version 3.x, Express got out of the business of being\na generic view engine — this was a great decision — leaving developers to\nimplement the concepts of layouts, partials, and doing file I/O for their\ntemplate engines of choice.\n\n### Goals and Features\n\nAfter building a half-dozen Express apps, I developed requirements and opinions\nabout what a Handlebars view engine should provide and how it should be\nimplemented. The following is that list:\n\n* Add back the concept of \"layout\", which was removed in Express 3.x.\n\n* Add back the concept of \"partials\" via Handlebars' partials mechanism.\n\n* Support a directory of partials; e.g., `{{> foo/bar}}` which exists on the\n file system at `views/partials/foo/bar.handlebars` by default.\n\n* Smart file system I/O and template caching. When in development, templates are\n always loaded from disk. In production, raw files and compiled templates are\n cached, including partials.\n\n* All async and non-blocking. File system I/O is slow and servers should not be\n blocked from handling requests while reading from disk. I/O queuing is used to\n avoid doing unnecessary work.\n\n* Ability to expose precompiled templates and partials to the client, enabling\n template sharing and reuse.\n\n* Ability to use a different Handlebars module/implementation other than the\n Handlebars npm package.\n\n### Package Design\n\nThis package was designed to work great for both the simple and complex use\ncases. I _intentionally_ made sure the full implementation is exposed and is\neasily overrideable.\n\nThe package exports a function which can be invoked with no arguments or with a\n`config` object and it will return a function (closed over sane defaults) which\ncan be registered with an Express app. It's an engine factory function.\n\nThis exported engine factory has two properties which expose the underlying\nimplementation:\n\n* `ExpressHandlebars()`: The constructor function which holds the internal\n implementation on its `prototype`. This produces instance objects which store\n their configuration, `compiled` and `precompiled` templates, and expose an\n `engine()` function which can be registered with an Express app.\n\n* `create()`: A convenience factory function for creating `ExpressHandlebars`\n instances.\n\nAn instance-based approach is used so that multiple `ExpressHandlebars`\ninstances can be created with their own configuration, templates, partials, and\nhelpers.\n\n\nInstallation\n------------\n\nInstall using npm:\n\n```shell\n$ npm install express3-handlebars\n```\n\n\nUsage\n-----\n\nThis view engine uses sane defaults that leverage the \"Express-way\" of\nstructuring an app's views. This makes it trivial to use in basic apps:\n\n### Basic Usage\n\n**Directory Structure:**\n\n```\n.\n├── app.js\n└── views\n ├── home.handlebars\n └── layouts\n └── main.handlebars\n\n2 directories, 3 files\n```\n\n**app.js:**\n\nCreates a super simple Express app which shows the basic way to register a\nHandlebars view engine using this package.\n\n```javascript\nvar express = require('express'),\n exphbs = require('express3-handlebars'),\n\n app = express();\n\napp.engine('handlebars', exphbs({defaultLayout: 'main'}));\napp.set('view engine', 'handlebars');\n\napp.get('/', function (req, res) {\n res.render('home');\n});\n\napp.listen(3000);\n```\n\n**views/layouts/main.handlebars:**\n\nThe main layout is the HTML page wrapper which can be reused for the different\nviews of the app. `{{{body}}}` is used as a placeholder for where the main\ncontent should be rendered.\n\n```html\n\n\n\n \n Example App\n\n\n\n {{{body}}}\n\n\n\n```\n\n**views/home.handlebars:**\n\nThe content for the app's home view which will be rendered into the layout's\n`{{{body}}}`.\n\n```html\n

    Example App: Home

    \n```\n\n#### Running the Example\n\nThe above example is bundled in this package's [examples directory][], where\nit can be run by:\n\n```shell\n$ cd examples/basic/ && node app\n```\n\n### Using Instances\n\nAnother way to use this view engine is to create an instance(s) of\n`ExpressHandlebars`, allowing access to the full API:\n\n```javascript\nvar express = require('express'),\n exphbs = require('express3-handlebars'),\n\n app = express(),\n hbs = exphbs.create({ /* config */ });\n\n// Register `hbs.engine` with the Express app.\napp.engine('handlebars', hbs.engine);\napp.set('view engine', 'handlebars');\n\n// ...still have a reference to `hbs`, on which methods like `loadPartials()`\n// can be called.\n```\n\n**Note:** The [Advanced Usage][] example demonstrates how `ExpressHandlebars`\ninstances can be leveraged.\n\n### Template Caching\n\nThis view engine uses a smart template caching strategy. In development,\ntemplates will always be loaded from disk, i.e., no caching. In production, raw\nfiles and compiled Handlebars templates are aggressively cached.\n\nThe easiest way to control template/view caching is through Express'\n[view cache setting][]:\n\n```javascript\napp.enable('view cache');\n```\n\nExpress enables this setting by default when in production mode, i.e.,\n`process.env.NODE_ENV === \"production\"`.\n\n**Note:** All of the public API methods accept `options.cache`, which gives\ncontrol over caching when calling these methods directly.\n\n### Layouts\n\nA layout is simply a Handlebars template with a `{{{body}}}` placeholder.\nUsually it will be an HTML page wrapper into which views will be rendered.\n\nThis view engine adds back the concept of \"layout\", which was removed in Express\n3.x. It can be configured with a path to the layouts directory, by default it's\nset to `\"views/layouts/\"`.\n\nThere are two ways to set a default layout: configuring the view engine's\n`defaultLayout` property, or setting [Express locals][] `app.locals.layout`.\n\nThe layout into which a view should be rendered can be overridden per-request\nby assigning a different value to the `layout` request local. The following\nwill render the \"home\" view with no layout:\n\n```javascript\napp.get('/', function (req, res, next) {\n res.render('home', {layout: false});\n});\n```\n\n### Helpers\n\nHelper functions, or \"helpers\" are functions that can be\n[registered with Handlebars][] and can be called within a template. Helpers can\nbe used for transforming output, iterating over data, etc. To keep with the\nspirit of *logic-less* templates, helpers are the place where logic should be\ndefined.\n\nHandlebars ships with some [built-in helpers][], such as: `with`, `if`, `each`,\netc. Most application will need to extend this set of helpers to include\napp-specific logic and transformations. Beyond defining global helpers on\n`Handlebars`, this view engine supports `ExpressHandlebars` instance-level\nhelpers via the `helpers` configuration property, and render-level helpers via\n`options.helpers` when calling the `render()` and `renderView()` methods.\n\nThe following example shows helpers being specified at each level:\n\n**app.js:**\n\nCreates a super simple Express app which shows the basic way to register\n`ExpressHandlebars` instance-level helpers, and override one at the\nrender-level.\n\n```javascript\nvar express = require('express'),\n exphbs = require('express3-handlebars'),\n\n app = express(),\n hbs;\n\nhbs = exphbs.create({\n // Specify helpers which are only registered on this instance.\n helpers: {\n foo: function () { return 'FOO!'; }\n bar: function () { return 'BAR!'; }\n }\n});\n\napp.engine('handlebars', hbs.engine);\napp.set('view engine', 'handlebars');\n\napp.get('/', function (req, res, next) {\n res.render('home', {\n showTitle: true,\n\n // Override `foo` helper only for this rendering.\n helpers: {\n foo: function () { return 'foo.'; }\n }\n });\n});\n\napp.listen(3000);\n```\n\n**views/home.handlebars:**\n\nThe app's home view which uses helper functions to help render the contents.\n\n```html\n\n\n\n \n Example App - Home\n\n\n\n \n {{#if showTitle}}\n

    Home

    \n {{/if}}\n\n \n

    {{foo}}

    \n\n \n

    {{bar}}

    \n\n\n\n```\n\n#### More on Helpers\n\nRefer to the [Handlebars website][] for more information on defining helpers:\n\n* [Expression Helpers][]\n* [Block Helpers][]\n\n\n[examples directory]: https://github.com/ericf/express3-handlebars/tree/master/examples\n[view cache setting]: http://expressjs.com/api.html#app-settings\n[Express locals]: http://expressjs.com/api.html#app.locals\n[registered with Handlebars]: https://github.com/wycats/handlebars.js/#registering-helpers\n[built-in helpers]: http://handlebarsjs.com/#builtins\n[Handlebars website]: http://handlebarsjs.com/\n[Expression Helpers]: http://handlebarsjs.com/expressions.html#helpers\n[Block Helpers]: http://handlebarsjs.com/block_helpers.html\n\n\nAPI\n---\n\n### Configuration and Defaults\n\nThere are two main ways to use this package: via its engine factory function, or\ncreating `ExpressHandlebars` instances; both use the same configuration\nproperties and defaults.\n\n```javascript\nvar exphbs = require('express3-handlebars');\n\n// Using the engine factory:\nexphbs({ /* config */ });\n\n// Create an instance:\nexphbs.create({ /* config */ });\n```\n\nThe following is the list of configuration properties and their default values\n(if any):\n\n#### `defaultLayout`\nThe string name or path of a template in the `layoutsDir` to use as the default\nlayout. This is overridden by a `layout` specified in the app or response\n`locals`. **Note:** A falsy value will render without a layout; e.g.,\n`res.render('home', {layout: false});`.\n\n#### `extname=\".handlebars\"`\nThe string name of the file extension used by the templates.\n\n#### `handlebars=require('handlebars')`\nThe Handlebars module/implementation. This allows for the `ExpressHandlebars`\ninstance to use a different Handlebars module/implementation than that provided\nby the Handlebars npm package.\n\n#### `helpers`\nAn object which holds the helper functions used when rendering templates with\nthis `ExpressHandlebars` instance. When rendering a template, a collection of\nhelpers will be generated by merging: `handlebars.helpers` (global), `helpers`\n(instance), and `options.helpers` (render-level). This allows Handlebars'\n`registerHelper()` function to operate as expected, will providing two extra\nlevels over helper overrides.\n\n#### `layoutsDir=\"views/layouts/\"`\nThe string path to the directory where the layout templates reside.\n\n#### `partialsDir=\"views/partials/\"`\nThe string path to the directory where the partials templates reside.\n\n### Properties\n\nThe public API properties are provided via `ExpressHandlebars` instances. In\nadditional to the properties listed in the **Configuration and Defaults**\nsection, the following are additional public properties:\n\n#### `compiled`\nAn object cache which holds compiled Handlebars template functions in the\nformat: `{\"path/to/template\": [Function]}`.\n\n#### `engine`\nA function reference to the `renderView()` method which is bound to `this`\n`ExpressHandlebars` instance. This bound function should be used when\nregistering this view engine with an Express app.\n\n#### `handlebarsVersion`\nThe version number of `handlebars` as a semver. This is unsed internally to\nbranch on certain operations which differ between Handlebars releases.\n\n#### `precompiled`\nAn object cache which holds precompiled Handlebars template strings in the\nformat: `{\"path/to/template\": [String]}`.\n\n### Methods\n\nThe following is the list of public API methods provided via `ExpressHandlebars`\ninstances:\n\n#### `loadPartials(options|callback, [callback])`\n\nRetrieves the partials in the `partialsDir` and passes an object mapping the\npartials in the form `{name: partial}` to the `callback`.\n\nBy default each partial will be a compiled Handlebars template function. Use\n`options.precompiled` to receive the partials as precompiled templates — this is\nuseful for sharing templates with client code.\n\n**Parameters:**\n\n* `[options]`: Optional object containing any of the following properties:\n\n * `[cache]`: Whether cached templates can be used if they have already been\n requested. This is recommended for production to avoid unnecessary file I/O.\n\n * `[precompiled=false]`: Whether precompiled templates should be provided,\n instead of compiled Handlebars template functions.\n\n* `callback`: Function to call once the partials are retrieved.\n\nThe name of each partial corresponds to its location in `partialsDir`. For\nexample, consider the following directory structure:\n\n```\nviews\n└── partials\n ├── foo\n │   └── bar.handlebars\n └── title.handlebars\n\n2 directories, 2 files\n```\n\n`loadPartials()` would produce the following result:\n\n```javascript\nvar hbs = require('express3-handlebars').create();\n\nhbs.loadPartials(function (err, partials) {\n console.log(partials);\n // => { 'foo.bar': [Function],\n // => title: [Function] }\n});\n```\n\n**Note:** The partial name `\"foo.bar\"` would ideally be `\"foo/bar\"`, but this is\nbeing prevented by a [Handlebars bug][]. Once this bug is fixed, a future\nversion will use a \"/\" separator. Templates requiring the partial still use:\n`{{> foo/bar}}`.\n\n#### `loadTemplate(filePath, options|callback, [callback])`\n\nRetrieves the template at the specified `filePath` and passes a compiled\nHandlebars template function to the `callback`.\n\nUse `options.precompiled` to receive a precompiled Handlebars template.\n\n**Parameters:**\n\n* `filePath`: String path to the Handlebars template file.\n\n* `[options]`: Optional object containing any of the following properties:\n\n * `[cache]`: Whether a cached template can be used if it have already been\n requested. This is recommended for production to avoid necessary file I/O.\n\n * `[precompiled=false]`: Whether a precompiled template should be provided,\n instead of a compiled Handlebars template function.\n\n* `callback`: Function to call once the template is retrieved.\n\n#### `loadTemplates(dirPath, options|callback, [callback])`\n\nRetrieves the all the templates in the specified `dirPath` and passes an object\nmapping the compiled templates in the form `{filename: template}` to the\n`callback`.\n\nUse `options.precompiled` to receive precompiled Handlebars templates — this is\nuseful for sharing templates with client code.\n\n**Parameters:**\n\n* `dirPath`: String path to the directory containing Handlebars template files.\n\n* `[options]`: Optional object containing any of the following properties:\n\n * `[cache]`: Whether cached templates can be used if it have already been\n requested. This is recommended for production to avoid necessary file I/O.\n\n * `[precompiled=false]`: Whether precompiled templates should be provided,\n instead of a compiled Handlebars template function.\n\n* `callback`: Function to call once the templates are retrieved.\n\n#### `render(filePath, options|callback, [callback])`\n\nRenders the template at the specified `filePath` using this instance's `helpers`\nand partials, and passes the resulting string to the `callback`.\n\nThe `options` will be used both as the context in which the Handlebars template\nis rendered, and to signal this view engine on how it should behave, e.g.,\n`options.cache = false` will load _always_ load the templates from disk.\n\n**Parameters:**\n\n* `filePath`: String path to the Handlebars template file.\n\n* `[options]`: Optional object which will serve as the context in which the\n Handlebars template is rendered. It may also contain any of the following\n properties which affect this view engine's behavior:\n\n * `[cache]`: Whether a cached template can be used if it have already been\n requested. This is recommended for production to avoid unnecessary file I/O.\n\n * `[helpers]`: Render-level helpers should be merged with (and will override)\n instance and global helper functions.\n\n* `callback`: Function to call once the template is retrieved.\n\n#### `renderView(viewPath, options|callback, [callback])`\n\nRenders the template at the specified `viewPath` as the `{{{body}}}` within the\nlayout specified by the `defaultLayout` or `options.layout`. Rendering will use\nthis instance's `helpers` and partials, and passes the resulting string to the\n`callback`.\n\nThis method is called by Express and is the main entry point into this Express\nview engine implementation. It adds the concept of a \"layout\" and delegates\nrendering to the `render()` method.\n\nThe `options` will be used both as the context in which the Handlebars templates\nare rendered, and to signal this view engine on how it should behave, e.g.,\n`options.cache=false` will load _always_ load the templates from disk.\n\n**Parameters:**\n\n* `viewPath`: String path to the Handlebars template file which should serve as\n the `{{{body}}}` when using a layout.\n\n* `[options]`: Optional object which will serve as the context in which the\n Handlebars templates are rendered. It may also contain any of the following\n properties which affect this view engine's behavior:\n\n * `[cache]`: Whether cached templates can be used if they have already been\n requested. This is recommended for production to avoid unnecessary file I/O.\n\n * `[helpers]`: Render-level helpers should be merged with (and will override)\n instance and global helper functions.\n\n * `[layout]`: Optional string path to the Handlebars template file to be used\n as the \"layout\". This overrides any `defaultLayout` value. Passing a falsy\n value will render with no layout (even if a `defaultLayout` is defined).\n\n* `callback`: Function to call once the template is retrieved.\n\n### Statics\n\nThe following is the list of static API properties and methods provided on the\n`ExpressHandlebars` constructor:\n\n#### `getHandlebarsSemver(handlebars)`\n\nReturns a semver-compatible version string for the specified `handlebars`\nmodule/implementation.\n\nThis utility function is used to compute the value for an `ExpressHandlebars`\ninstance's `handlebarsVersion` property.\n\n\n[Handlebars bug]: https://github.com/wycats/handlebars.js/pull/389\n\n\nExamples\n--------\n\n### [Basic Usage][]\n\nThis example shows the most basic way to use this view engine.\n\n### [Advanced Usage][]\n\nThis example is more comprehensive and shows how to use many of the features of\nthis view engine, including helpers, partials, multiple layouts, etc.\n\nAs noted in the **Package Design** section, this view engine's implementation is\ninstance-based, and more advanced usages can take advantage of this. The\nAdvanced Usage example demonstrates how to use an `ExpressHandlebars` instance\nto share templates with the client, among other features.\n\n\n[Basic Usage]: https://github.com/ericf/express3-handlebars/tree/master/examples/basic\n[Advanced Usage]: https://github.com/ericf/express3-handlebars/tree/master/examples/advanced\n\n\nLicense\n-------\n\nThis software is free to use under the Yahoo! Inc. BSD license.\nSee the [LICENSE file][] for license text and copyright information.\n\n\n[LICENSE file]: https://github.com/ericf/express3-handlebars/blob/master/LICENSE\n", - "readmeFilename": "README.md", - "_id": "express3-handlebars@0.5.0", - "_from": "express3-handlebars@*" -} diff --git a/node_modules/mongodb/.travis.yml b/node_modules/mongodb/.travis.yml deleted file mode 100644 index 7ef2762c4..000000000 --- a/node_modules/mongodb/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.10 - - 0.11 \ No newline at end of file diff --git a/node_modules/mongodb/CONTRIBUTING.md b/node_modules/mongodb/CONTRIBUTING.md deleted file mode 100644 index c23e426c7..000000000 --- a/node_modules/mongodb/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -## Contributing to the driver - -### Bugfixes - -- Before starting to write code, look for existing [tickets](https://jira.mongodb.org/browse/NODE) or [create one](https://jira.mongodb.org/secure/CreateIssue!default.jspa) for your specific issue under the "Node Driver" project. That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. -- Fork the [repo](https://github.com/mongodb/node-mongodb-native) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. -- Follow the general coding style of the rest of the project: - - 2 space tabs - - no trailing whitespace - - comma last - - inline documentation for new methods, class members, etc - - 0 space between conditionals/functions, and their parenthesis and curly braces - - `if(..) {` - - `for(..) {` - - `while(..) {` - - `function(err) {` -- Write tests and make sure they pass (execute `npm test` from the cmd line to run the test suite). - -### Documentation - -To contribute to the [API documentation](http://mongodb.github.com/node-mongodb-native/) just make your changes to the inline documentation of the appropriate [source code](https://github.com/mongodb/node-mongodb-native/tree/master/docs) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. - -If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute `make generate_docs`. Make sure you have the python documentation framework sphinx installed `easy_install sphinx`. The docs are generated under `docs/build'. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the master branch with your changes. diff --git a/node_modules/mongodb/LICENSE b/node_modules/mongodb/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/node_modules/mongodb/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/node_modules/mongodb/Makefile b/node_modules/mongodb/Makefile deleted file mode 100644 index 59d2bfeb8..000000000 --- a/node_modules/mongodb/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -NPM = npm -NODEUNIT = node_modules/nodeunit/bin/nodeunit -DOX = node_modules/dox/bin/dox -name = all - -total: build_native - -test_functional: - node test/runner.js -t functional - -test_ssl: - node test/runner.js -t ssl - -test_replicaset: - node test/runner.js -t replicaset - -test_sharded: - node test/runner.js -t sharded - -test_auth: - node test/runner.js -t auth - -generate_docs: - $(NODE) dev/tools/build-docs.js - make --directory=./docs/sphinx-docs --file=Makefile html - -.PHONY: total diff --git a/node_modules/mongodb/Readme.md b/node_modules/mongodb/Readme.md deleted file mode 100644 index c61fbc0e9..000000000 --- a/node_modules/mongodb/Readme.md +++ /dev/null @@ -1,414 +0,0 @@ -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| apidoc | http://mongodb.github.io/node-mongodb-native/ | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org/ | - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in PyMongo? Please open a -case in our issue management tool, JIRA: - -- Create an account and login . -- Navigate to the NODE project . -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Questions and Bug Reports - - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ - -### Change Log - -http://jira.mongodb.org/browse/NODE - -## Install - -To install the most recent release from npm, run: - - npm install mongodb - -That may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version) - -To install the latest from the repository, run:: - - npm install path/to/node-mongodb-native - -## Live Examples - - -## Introduction - -This is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/. - -A simple example of inserting a document. - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db.collection('test_insert'); - collection.insert({a:2}, function(err, docs) { - - collection.count(function(err, count) { - console.log(format("count = %s", count)); - }); - - // Locate all the entries using find - collection.find().toArray(function(err, results) { - console.dir(results); - // Let's close the db - db.close(); - }); - }); - }) -``` - -## Data types - -To store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code). - -In particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example: - -```javascript - // Get the objectID type - var ObjectID = require('mongodb').ObjectID; - - var idString = '4e4e1638c85e808431000003'; - collection.findOne({_id: new ObjectID(idString)}, console.log) // ok - collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined -``` - -Here are the constructors the non-Javascript BSON primitive types: - -```javascript - // Fetch the library - var mongo = require('mongodb'); - // Create new instances of BSON types - new mongo.Long(numberString) - new mongo.ObjectID(hexString) - new mongo.Timestamp() // the actual unique number is generated on insert. - new mongo.DBRef(collectionName, id, dbName) - new mongo.Binary(buffer) // takes a string or Buffer - new mongo.Code(code, [context]) - new mongo.Symbol(string) - new mongo.MinKey() - new mongo.MaxKey() - new mongo.Double(number) // Force double storage -``` - -### The C/C++ bson parser/serializer - -If you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below - -```javascript - // using native_parser: - MongoClient.connect('mongodb://127.0.0.1:27017/test' - , {db: {native_parser: true}}, function(err, db) {}) -``` - -The C++ parser uses the js objects both for serialization and deserialization. - -## GitHub information - -The source code is available at http://github.com/mongodb/node-mongodb-native. -You can either clone the repository or download a tarball of the latest release. - -Once you have the source you can test the driver by running - - $ make test - -in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass. - -## Examples - -For examples look in the examples/ directory. You can execute the examples using node. - - $ cd examples - $ node queries.js - -## GridStore - -The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition. - -For more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md) - -## Replicasets - -For more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/) - -### Primary Key Factories - -Defining your own primary key factory allows you to generate your own series of id's -(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long "string". - -Simple example below - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - // Custom factory (need to provide a 12 byte array); - CustomPKFactory = function() {} - CustomPKFactory.prototype = new Object(); - CustomPKFactory.createPk = function() { - return new ObjectID("aaaaaaaaaaaa"); - } - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.dropDatabase(function(err, done) { - - db.createCollection('test_custom_key', function(err, collection) { - - collection.insert({'a':1}, function(err, docs) { - - collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}).toArray(function(err, items) { - console.dir(items); - // Let's close the db - db.close(); - }); - }); - }); - }); - }); -``` - -## Documentation - -If this document doesn't answer your questions, see the source of -[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js) -or [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js), -or the documentation at MongoDB for query and update formats. - -### Find - -The find method is actually a factory method to create -Cursor objects. A Cursor lazily uses the connection the first time -you call `nextObject`, `each`, or `toArray`. - -The basic operation on a cursor is the `nextObject` method -that fetches the next matching document from the database. The convenience -methods `each` and `toArray` call `nextObject` until the cursor is exhausted. - -Signatures: - -```javascript - var cursor = collection.find(query, [fields], options); - cursor.sort(fields).limit(n).skip(m). - - cursor.nextObject(function(err, doc) {}); - cursor.each(function(err, doc) {}); - cursor.toArray(function(err, docs) {}); - - cursor.rewind() // reset the cursor to its initial state. -``` - -Useful chainable methods of cursor. These can optionally be options of `find` instead of method calls: - - * `.limit(n).skip(m)` to control paging. - * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes: - * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2. - * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above - * `.sort([['field1', 'desc'], 'field2'])` same as above - * `.sort('field1')` ascending by field1 - -Other options of `find`: - -* `fields` the fields to fetch (to avoid transferring the entire document) -* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors). -* `batchSize` The number of the subset of results to request the database -to return for every request. This should initially be greater than 1 otherwise -the database will automatically close the cursor. The batch size can be set to 1 -with `batchSize(n, function(err){})` after performing the initial query to the database. -* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint). -* `explain` turns this into an explain query. You can also call -`explain()` on any cursor to fetch the explanation. -* `snapshot` prevents documents that are updated while the query is active -from being returned multiple times. See more -[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database). -* `timeout` if false, asks MongoDb not to time out this cursor after an -inactivity period. - -For information on how to create queries, see the -[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying). - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db - .collection('test') - .find({}) - .limit(10) - .toArray(function(err, docs) { - console.dir(docs); - }); - }); -``` - -### Insert - -Signature: - -```javascript - collection.insert(docs, options, [callback]); -``` - -where `docs` can be a single document or an array of documents. - -Useful options: - -* `safe:true` Should always set if you have a callback. - -See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting). - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) { - if (err) console.warn(err.message); - if (err && err.message.indexOf('E11000 ') !== -1) { - // this _id was already inserted in the database - } - }); - }); -``` - -Note that there's no reason to pass a callback to the insert or update commands -unless you use the `safe:true` option. If you don't specify `safe:true`, then -your callback will be called immediately. - -### Update: update and insert (upsert) - -The update operation will update the first document that matches your query -(or all documents that match if you use `multi:true`). -If `safe:true`, `upsert` is not set, and no documents match, your callback will return 0 documents updated. - -See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for -the modifier (`$inc`, `$set`, `$push`, etc.) formats. - -Signature: - -```javascript - collection.update(criteria, objNew, options, [callback]); -``` - -Useful options: - -* `safe:true` Should always set if you have a callback. -* `multi:true` If set, all matching documents are updated, not just the first. -* `upsert:true` Atomically inserts the document if no documents matched. - -Example for `update`: - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) { - if (err) console.warn(err.message); - else console.log('successfully updated'); - }); - }); -``` - -### Find and modify - -`findAndModify` is like `update`, but it also gives the updated document to -your callback. But there are a few key differences between findAndModify and -update: - - 1. The signatures differ. - 2. You can only findAndModify a single item, not multiple items. - -Signature: - -```javascript - collection.findAndModify(query, sort, update, options, callback) -``` - -The sort parameter is used to specify which object to operate on, if more than -one document matches. It takes the same format as the cursor sort (see -Connection.find above). - -See the -[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) -for more details. - -Useful options: - -* `remove:true` set to a true to remove the object before returning -* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove. -* `upsert:true` Atomically inserts the document if no documents matched. - -Example for `findAndModify`: - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) { - if (err) console.warn(err.message); - else console.dir(object); // undefined if no matching object exists. - }); - }); -``` - -### Save - -The `save` method is a shorthand for upsert if the document contains an -`_id`, or an insert if there is no `_id`. - -## Release Notes - -See HISTORY - -## Credits - -1. [10gen](http://github.com/mongodb/mongo-ruby-driver/) -2. [Google Closure Library](http://code.google.com/closure/library/) -3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser) - -## Contributors - -Aaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy - -## License - - Copyright 2009 - 2013 MongoDb 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. - diff --git a/node_modules/mongodb/index.js b/node_modules/mongodb/index.js deleted file mode 100644 index 4f59e9d92..000000000 --- a/node_modules/mongodb/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/mongodb'); diff --git a/node_modules/mongodb/lib/mongodb/admin.js b/node_modules/mongodb/lib/mongodb/admin.js deleted file mode 100644 index 0bd01b5ef..000000000 --- a/node_modules/mongodb/lib/mongodb/admin.js +++ /dev/null @@ -1,339 +0,0 @@ -/*! - * Module dependencies. - */ -var Collection = require('./collection').Collection, - Cursor = require('./cursor').Cursor, - DbCommand = require('./commands/db_command').DbCommand, - utils = require('./utils'); - -/** - * Allows the user to access the admin functionality of MongoDB - * - * @class Represents the Admin methods of MongoDB. - * @param {Object} db Current db instance we wish to perform Admin operations on. - * @return {Function} Constructor for Admin type. - */ -function Admin(db) { - if(!(this instanceof Admin)) return new Admin(db); - this.db = db; -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from buildInfo or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.buildInfo = function(callback) { - this.serverInfo(callback); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverInfo or null if an error occured. - * @return {null} Returns no result - * @api private - */ -Admin.prototype.serverInfo = function(callback) { - this.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err != null) return callback(err, null); - return callback(null, doc.documents[0]); - }); -} - -/** - * Retrieve this db's server status. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverStatus or null if an error occured. - * @return {null} - * @api public - */ -Admin.prototype.serverStatus = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { - if(err == null && doc.documents[0].ok === 1) { - callback(null, doc.documents[0]); - } else { - if(err) return callback(err, false); - return callback(utils.toError(doc.documents[0]), false); - } - }); -}; - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingLevel or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.profilingLevel = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({profile:-1}, function(err, doc) { - doc = doc.documents[0]; - - if(err == null && doc.ok === 1) { - var was = doc.was; - if(was == 0) return callback(null, "off"); - if(was == 1) return callback(null, "slow_only"); - if(was == 2) return callback(null, "all"); - return callback(new Error("Error: illegal profiling level value " + was), null); - } else { - err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - } - }); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ping or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.ping = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - - this.db.executeDbAdminCommand({ping: 1}, callback); -} - -/** - * Authenticate against MongoDB - * - * @param {String} username The user name for the authentication. - * @param {String} password The password for the authentication. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authenticate or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.authenticate = function(username, password, callback) { - this.db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Logout current authenticated user - * - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.logout = function(callback) { - this.db.logout({authdb: 'admin'}, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Add a user to the MongoDB server, if the user exists it will - * overwrite the current password - * - * Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username The user name for the authentication. - * @param {String} password The password for the authentication. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.addUser = function(username, password, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() : {}; - // Set the db name to admin - options.dbName = 'admin'; - // Add user - this.db.addUser(username, password, options, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Remove a user from the MongoDB server - * - * Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username The user name for the authentication. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - options.dbName = 'admin'; - - this.db.removeUser(username, options, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Set the current profiling level of MongoDB - * - * @param {String} level The new profiling level (off, slow_only, all) - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from setProfilingLevel or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.setProfilingLevel = function(level, callback) { - var self = this; - var command = {}; - var profile = 0; - - if(level == "off") { - profile = 0; - } else if(level == "slow_only") { - profile = 1; - } else if(level == "all") { - profile = 2; - } else { - return callback(new Error("Error: illegal profiling level value " + level)); - } - - // Set up the profile number - command['profile'] = profile; - - this.db.executeDbAdminCommand(command, function(err, doc) { - doc = doc.documents[0]; - - if(err == null && doc.ok === 1) - return callback(null, level); - return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - }); -}; - -/** - * Retrive the current profiling information for MongoDB - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingInfo or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.profilingInfo = function(callback) { - try { - new Cursor(this.db, new Collection(this.db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}, {}, {dbName: 'admin'}).toArray(function(err, items) { - return callback(err, items); - }); - } catch (err) { - return callback(err, null); - } -}; - -/** - * Execute a db command against the Admin database - * - * @param {Object} command A command object `{ping:1}`. - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.command = function(command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - // Execute a command - this.db.executeDbAdminCommand(command, options, function(err, doc) { - // Ensure change before event loop executes - return callback != null ? callback(err, doc) : null; - }); -} - -/** - * Validate an existing collection - * - * @param {String} collectionName The name of the collection to validate. - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from validateCollection or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - var self = this; - var command = {validate: collectionName}; - var keys = Object.keys(options); - - // Decorate command with extra options - for(var i = 0; i < keys.length; i++) { - if(options.hasOwnProperty(keys[i])) { - command[keys[i]] = options[keys[i]]; - } - } - - this.db.executeDbCommand(command, function(err, doc) { - if(err != null) return callback(err, null); - doc = doc.documents[0]; - - if(doc.ok === 0) - return callback(new Error("Error with validate command"), null); - if(doc.result != null && doc.result.constructor != String) - return callback(new Error("Error with validation data"), null); - if(doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error("Error: invalid collection " + collectionName), null); - if(doc.valid != null && !doc.valid) - return callback(new Error("Error: invalid collection " + collectionName), null); - - return callback(null, doc); - }); -}; - -/** - * List the available databases - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from listDatabases or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.listDatabases = function(callback) { - // Execute the listAllDatabases command - this.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) { - if(err != null) return callback(err, null); - return callback(null, doc.documents[0]); - }); -} - -/** - * Get ReplicaSet status - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from replSetGetStatus or null if an error occured. - * @return {null} - * @api public - */ -Admin.prototype.replSetGetStatus = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { - if(err == null && doc.documents[0].ok === 1) - return callback(null, doc.documents[0]); - if(err) return callback(err, false); - return callback(utils.toError(doc.documents[0]), false); - }); -}; - -/** - * @ignore - */ -exports.Admin = Admin; diff --git a/node_modules/mongodb/lib/mongodb/aggregation_cursor.js b/node_modules/mongodb/lib/mongodb/aggregation_cursor.js deleted file mode 100644 index 0f424d346..000000000 --- a/node_modules/mongodb/lib/mongodb/aggregation_cursor.js +++ /dev/null @@ -1,257 +0,0 @@ -var ReadPreference = require('./connection/read_preference').ReadPreference - , Readable = require('stream').Readable - , CommandCursor = require('./command_cursor').CommandCursor - , utils = require('./utils') - , shared = require('./collection/shared') - , inherits = require('util').inherits; - -var AggregationCursor = function(collection, serverCapabilities, options) { - var pipe = []; - var self = this; - var results = null; - var _cursor_options = {}; - // Ensure we have options set up - options = options == null ? {} : options; - - // If a pipeline was provided - pipe = Array.isArray(options.pipe) ? options.pipe : pipe; - // Set passed in batchSize if provided - if(typeof options.batchSize == 'number') _cursor_options.batchSize = options.batchSize; - // Get the read Preference - var readPreference = shared._getReadConcern(collection, options); - - // Set up - Readable.call(this, {objectMode: true}); - - // Contains connection - var connection = null; - - // Set the read preference - var _options = { - readPreference: readPreference - }; - - // Actual command - var command = { - aggregate: collection.collectionName - , pipeline: pipe - , cursor: _cursor_options - } - - // If allowDiskUsage is set - if(typeof options.allowDiskUsage == 'boolean') - command.allowDiskUsage = options.allowDiskUsage; - - // Command cursor (if we support one) - var commandCursor = new CommandCursor(collection.db, collection, command); - - // // Internal cursor methods - // this.find = function(selector) { - // pipe.push({$match: selector}); - // return self; - // } - - // this.unwind = function(unwind) { - // pipe.push({$unwind: unwind}); - // return self; - // } - - // this.group = function(group) { - // pipe.push({$group: group}); - // return self; - // } - - // this.project = function(project) { - // pipe.push({$project: project}); - // return self; - // } - - // this.limit = function(limit) { - // pipe.push({$limit: limit}); - // return self; - // } - - // this.geoNear = function(geoNear) { - // pipe.push({$geoNear: geoNear}); - // return self; - // } - - // this.sort = function(sort) { - // pipe.push({$sort: sort}); - // return self; - // } - - // this.withReadPreference = function(read_preference) { - // _options.readPreference = read_preference; - // return self; - // } - - // this.withQueryOptions = function(options) { - // if(options.batchSize) { - // _cursor_options.batchSize = options.batchSize; - // } - - // // Return the cursor - // return self; - // } - - // this.skip = function(skip) { - // pipe.push({$skip: skip}); - // return self; - // } - - // this.allowDiskUsage = function(allowDiskUsage) { - // command.allowDiskUsage = allowDiskUsage; - // return self; - // } - - this.explain = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor explain requires a callback function"); - - // Add explain options - _options.explain = true; - // Execute aggregation pipeline - collection.aggregate(pipe, _options, function(err, results) { - if(err) return callback(err, null); - callback(null, results); - }); - } - - // this.maxTimeMS = function(maxTimeMS) { - // if(typeof maxTimeMS != 'number') { - // throw new Error("maxTimeMS must be a number"); - // } - - // // Save the maxTimeMS - // _options.maxTimeMS = maxTimeMS - // // Set the maxTimeMS on the command cursor - // commandCursor.maxTimeMS(maxTimeMS); - // return self; - // } - - this.get = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor get requires a callback function"); - // Checkout a connection - var _connection = collection.db.serverConfig.checkoutReader(_options.readPreference); - // Fall back - if(!_connection.serverCapabilities.hasAggregationCursor) { - return collection.aggregate(pipe, _options, function(err, results) { - if(err) return callback(err); - callback(null, results); - }); - } - - // Execute get using command Cursor - commandCursor.get({connection: _connection}, callback); - } - - this.getOne = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor getOne requires a callback function"); - // Set the limit to 1 - pipe.push({$limit: 1}); - // For now we have no cursor command so let's just wrap existing results - collection.aggregate(pipe, _options, function(err, results) { - if(err) return callback(err); - callback(null, results[0]); - }); - } - - this.each = function(callback) { - // Checkout a connection if we have none - if(!connection) - connection = collection.db.serverConfig.checkoutReader(_options.readPreference); - - // Fall back - if(!connection.serverCapabilities.hasAggregationCursor) { - collection.aggregate(pipe, _options, function(err, _results) { - if(err) return callback(err); - - while(_results.length > 0) { - callback(null, _results.shift()); - } - - callback(null, null); - }); - } - - // Execute each using command Cursor - commandCursor.each({connection: connection}, callback); - } - - this.next = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor next requires a callback function"); - - // Checkout a connection if we have none - if(!connection) - connection = collection.db.serverConfig.checkoutReader(_options.readPreference); - - // Fall back - if(!connection.serverCapabilities.hasAggregationCursor) { - if(!results) { - // For now we have no cursor command so let's just wrap existing results - return collection.aggregate(pipe, _options, function(err, _results) { - if(err) return callback(err); - results = _results; - - // Ensure we don't issue undefined - var item = results.shift(); - callback(null, item ? item : null); - }); - } - - // Ensure we don't issue undefined - var item = results.shift(); - // Return the item - return callback(null, item ? item : null); - } - - // Execute next using command Cursor - commandCursor.next({connection: connection}, callback); - } - - // - // Close method - // - this.close = function(callback) { - if(typeof callback != 'function') - throw utils.toError("AggregationCursor close requires a callback function"); - - // Checkout a connection if we have none - if(!connection) - connection = collection.db.serverConfig.checkoutReader(_options.readPreference); - - // Fall back - if(!connection.serverCapabilities.hasAggregationCursor) { - return callback(null, null); - } - - // Execute next using command Cursor - commandCursor.close({connection: connection}, callback); - } - - // - // Stream method - // - this._read = function(n) { - self.next(function(err, result) { - if(err) { - self.emit('error', err); - return self.push(null); - } - - self.push(result); - }); - } -} - -// Inherit from Readable -if(Readable != null) { - inherits(AggregationCursor, Readable); -} - -// Exports the Aggregation Framework -exports.AggregationCursor = AggregationCursor; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js deleted file mode 100644 index 39bf2ab4b..000000000 --- a/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js +++ /dev/null @@ -1,62 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils'); - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Execute all four - db._executeQueryCommand(DbCommand.createGetNonceCommand(db), options, function(err, result, connection) { - // console.log("--------------------------------------------- MONGODB-CR 0") - // console.dir(err) - // Execute on all the connections - if(err == null) { - // Nonce used to make authentication request with md5 hash - var nonce = result.documents[0].nonce; - // Execute command - db._executeQueryCommand(DbCommand.createAuthenticationCommand(db, username, password, nonce, authdb), {connection:connection}, function(err, result) { - // console.log("--------------------------------------------- MONGODB-CR 1") - // console.dir(err) - // console.dir(result) - // Count down - numberOfConnections = numberOfConnections - 1; - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result - && Array.isArray(result.documents) - && result.documents.length > 0 - && (result.documents[0].err != null || result.documents[0].errmsg != null)) { - errorObject = utils.toError(result.documents[0]); - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null - && result && Array.isArray(result.documents) && result.documents.length > 0 - && result.documents[0].ok == 1) { // We authenticated correctly save the credentials - db.serverConfig.auth.add('MONGODB-CR', db.databaseName, username, password, authdb); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js deleted file mode 100644 index 47b5155ed..000000000 --- a/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js +++ /dev/null @@ -1,149 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , format = require('util').format; - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - var error = null; - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - - // Start Auth process for a connection - GSSAPIInitialize(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) { - // Adjust number of connections left to connect - numberOfConnections = numberOfConnections - 1; - // If we have an error save it - if(err) error = err; - - // We are done - if(numberOfConnections == 0) { - if(err) return callback(error, false); - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return callback(null, true); - } - }); - } -} - -// -// Initialize step -var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, connection, callback) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, gssapiServiceName); - - // Perform initialization - mongo_auth_process.init(username, password, function(err, context) { - if(err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if(err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, connection, callback) { - // Build the sasl start command - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: payload - , autoAuthorize: 1 - }; - - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - // Get the payload - doc = doc.documents[0]; - var db_payload = doc.payload; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - - // Get the result document - doc = doc.documents[0]; - - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback); - }); - }); -} - -var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) { - // Build final command - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Let's finish the auth process against mongodb - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - - mongo_auth_process.transition(null, function(err, payload) { - if(err) return callback(err, false); - callback(null, true); - }); - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js deleted file mode 100644 index 594181db0..000000000 --- a/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js +++ /dev/null @@ -1,66 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , Binary = require('bson').Binary - , format = require('util').format; - -var authenticate = function(db, username, password, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Create payload - var payload = new Binary(format("\x00%s\x00%s", username, password)); - - // Let's start the sasl process - var command = { - saslStart: 1 - , mechanism: 'PLAIN' - , payload: payload - , autoAuthorize: 1 - }; - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - var connection = connections[i]; - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result.documents[0].err != null || result.documents[0].errmsg != null){ - errorObject = utils.toError(result.documents[0]); - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null && result.documents[0].ok == 1) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('PLAIN', db.databaseName, username, password); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js deleted file mode 100644 index 316fa3a49..000000000 --- a/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js +++ /dev/null @@ -1,135 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , format = require('util').format; - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Set the sspi server name - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - - // Grab all the connections - var connections = db.serverConfig.allRawConnections(); - var error = null; - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - // Start Auth process for a connection - SSIPAuthenticate(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) { - // Adjust number of connections left to connect - numberOfConnections = numberOfConnections - 1; - // If we have an error save it - if(err) error = err; - - // We are done - if(numberOfConnections == 0) { - if(err) return callback(err, false); - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return callback(null, true); - } - }); - } -} - -var SSIPAuthenticate = function(db, username, password, authdb, service_name, connection, callback) { - // -------------------------------------------------------------- - // Async Version - // -------------------------------------------------------------- - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: '' - , autoAuthorize: 1 - }; - - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, service_name); - - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.init(username, password, function(err) { - if(err) return callback(err); - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - if(doc.done) return callback(null, true); - callback(new Error("Authentication failed"), false); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js b/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js deleted file mode 100644 index de680305e..000000000 --- a/node_modules/mongodb/lib/mongodb/auth/mongodb_x509.js +++ /dev/null @@ -1,62 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , Binary = require('bson').Binary - , format = require('util').format; - -var authenticate = function(db, username, password, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Let's start the sasl process - var command = { - authenticate: 1 - , mechanism: 'MONGODB-X509' - , user: username - }; - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - var connection = connections[i]; - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result.documents[0].err != null || result.documents[0].errmsg != null){ - errorObject = utils.toError(result.documents[0]); - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null && result.documents[0].ok == 1) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('MONGODB-X509', db.databaseName, username, password); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/collection.js b/node_modules/mongodb/lib/mongodb/collection.js deleted file mode 100644 index 448996b40..000000000 --- a/node_modules/mongodb/lib/mongodb/collection.js +++ /dev/null @@ -1,625 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var InsertCommand = require('./commands/insert_command').InsertCommand - , QueryCommand = require('./commands/query_command').QueryCommand - , DeleteCommand = require('./commands/delete_command').DeleteCommand - , UpdateCommand = require('./commands/update_command').UpdateCommand - , DbCommand = require('./commands/db_command').DbCommand - , ObjectID = require('bson').ObjectID - , Code = require('bson').Code - , Cursor = require('./cursor').Cursor - , utils = require('./utils') - , shared = require('./collection/shared') - , core = require('./collection/core') - , query = require('./collection/query') - , index = require('./collection/index') - , geo = require('./collection/geo') - , commands = require('./collection/commands') - , aggregation = require('./collection/aggregation'); - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **slaveOk** {Boolean, default:false}, Allow reads from secondaries. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - * @class Represents a Collection - * @param {Object} db db instance. - * @param {String} collectionName collection name. - * @param {Object} [pkFactory] alternative primary key factory. - * @param {Object} [options] additional options for the collection. - * @return {Object} a collection instance. - */ -function Collection (db, collectionName, pkFactory, options) { - if(!(this instanceof Collection)) return new Collection(db, collectionName, pkFactory, options); - - shared.checkCollectionName(collectionName); - - this.db = db; - this.collectionName = collectionName; - this.internalHint = null; - this.opts = options != null && ('object' === typeof options) ? options : {}; - this.slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - this.serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; - this.raw = options == null || options.raw == null ? db.raw : options.raw; - - this.readPreference = options == null || options.readPreference == null ? db.serverConfig.options.readPreference : options.readPreference; - this.readPreference = this.readPreference == null ? 'primary' : this.readPreference; - - - this.pkFactory = pkFactory == null - ? ObjectID - : pkFactory; - - // Server Capabilities - this.serverCapabilities = this.db.serverConfig._serverCapabilities; -} - -/** - * Inserts a single document or a an array of documents into MongoDB. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **continueOnError/keepGoing** {Boolean, default:false}, keep inserting documents even if one document has an error, *mongodb 1.9.1 >*. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **forceServerObjectId** {Boolean, default:false}, let server assign ObjectId instead of the driver - * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Array|Object} docs - * @param {Object} [options] optional options for insert command - * @param {Function} [callback] optional callback for the function, must be provided when using a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.insert = function() { return core.insert; }(); - -/** - * Removes documents specified by `selector` from the db. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **single** {Boolean, default:false}, removes the first document found. - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} [selector] optional select, no selector is equivalent to removing all documents. - * @param {Object} [options] additional options during remove. - * @param {Function} [callback] must be provided if you performing a remove with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.remove = function() { return core.remove; }(); - -/** - * Renames the collection. - * - * Options - * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists. - * - * @param {String} newName the new name of the collection. - * @param {Object} [options] returns option results. - * @param {Function} callback the callback accepting the result - * @return {null} - * @api public - */ -Collection.prototype.rename = function() { return commands.rename; }(); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} [doc] the document to save - * @param {Object} [options] additional options during remove. - * @param {Function} [callback] must be provided if you performing a safe save - * @return {null} - * @api public - */ -Collection.prototype.save = function() { return core.save; }(); - -/** - * Updates documents. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **upsert** {Boolean, default:false}, perform an upsert operation. - * - **multi** {Boolean, default:false}, update all documents matching the selector. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} selector the query to select the document/documents to be updated - * @param {Object} document the fields/vals to be updated, or in the case of an upsert operation, inserted. - * @param {Object} [options] additional options during update. - * @param {Function} [callback] must be provided if you performing an update with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.update = function() { return core.update; }(); - -/** - * The distinct command returns returns a list of distinct values for the given key across a collection. - * - * Options - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {String} key key to run distinct against. - * @param {Object} [query] option query to narrow the returned objects. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from distinct or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.distinct = function() { return commands.distinct; }(); - -/** - * Count number of matching documents in the db to a query. - * - * Options - * - **skip** {Number}, The number of documents to skip for the count. - * - **limit** {Number}, The limit of documents to count. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Object} [query] query to filter by before performing count. - * @param {Object} [options] additional options during count. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the count method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.count = function() { return commands.count; }(); - -/** - * Drop the collection - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the drop method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.drop = function drop(callback) { - this.db.dropCollection(this.collectionName, callback); -}; - -/** - * Find and update a document. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **remove** {Boolean, default:false}, set to true to remove the object before returning. - * - **upsert** {Boolean, default:false}, perform an upsert operation. - * - **new** {Boolean, default:false}, set to true if you want to return the modified object rather than the original. Ignored for remove. - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} query query object to locate the object to modify - * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate - * @param {Object} doc - the fields/vals to be updated - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndModify method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.findAndModify = function() { return core.findAndModify; }(); - -/** - * Find and remove a document - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} query query object to locate the object to modify - * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndRemove method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.findAndRemove = function() { return core.findAndRemove; }(); - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * - * Various argument possibilities - * - callback? - * - selector, callback?, - * - selector, fields, callback? - * - selector, options, callback? - * - selector, fields, options, callback? - * - selector, fields, skip, limit, callback? - * - selector, fields, skip, limit, timeout, callback? - * - * Options - * - **limit** {Number, default:0}, sets the limit of documents returned in the query. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination). - * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * - **explain** {Boolean, default:false}, explain the query instead of returning the data. - * - **snapshot** {Boolean, default:false}, snapshot query. - * - **timeout** {Boolean, default:false}, specify if the cursor can timeout. - * - **tailable** {Boolean, default:false}, specify if the cursor is tailable. - * - **tailableRetryInterval** {Number, default:100}, specify the miliseconds between getMores on tailable cursor. - * - **numberOfRetries** {Number, default:5}, specify the number of times to retry the tailable cursor. - * - **awaitdata** {Boolean, default:false} allow the cursor to wait for data, only applicable for tailable cursor. - * - **oplogReplay** {Boolean, default:false} sets an internal flag, only applicable for tailable cursor. - * - **exhaust** {Boolean, default:false} have the server send all the documents at once as getMore packets, not recommended. - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **returnKey** {Boolean, default:false}, only return the index key. - * - **maxScan** {Number}, Limit the number of items to scan. - * - **min** {Number}, Set index bounds. - * - **max** {Number}, Set index bounds. - * - **showDiskLoc** {Boolean, default:false}, Show disk location of results. - * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler. - * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **numberOfRetries** {Number, default:5}, if using awaidata specifies the number of times to retry on timeout. - * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system - * - * @param {Object|ObjectID} query query object to locate the object to modify - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the find method or null if an error occured. - * @return {Cursor} returns a cursor to the query - * @api public - */ -Collection.prototype.find = function() { return query.find; }(); - -/** - * Finds a single document based on the query - * - * Various argument possibilities - * - callback? - * - selector, callback?, - * - selector, fields, callback? - * - selector, options, callback? - * - selector, fields, options, callback? - * - selector, fields, skip, limit, callback? - * - selector, fields, skip, limit, timeout, callback? - * - * Options - * - **limit** {Number, default:0}, sets the limit of documents returned in the query. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination). - * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * - **explain** {Boolean, default:false}, explain the query instead of returning the data. - * - **snapshot** {Boolean, default:false}, snapshot query. - * - **timeout** {Boolean, default:false}, specify if the cursor can timeout. - * - **tailable** {Boolean, default:false}, specify if the cursor is tailable. - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **returnKey** {Boolean, default:false}, only return the index key. - * - **maxScan** {Number}, Limit the number of items to scan. - * - **min** {Number}, Set index bounds. - * - **max** {Number}, Set index bounds. - * - **showDiskLoc** {Boolean, default:false}, Show disk location of results. - * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler. - * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system - * - * @param {Object|ObjectID} query query object to locate the object to modify - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findOne method or null if an error occured. - * @return {Cursor} returns a cursor to the query - * @api public - */ -Collection.prototype.findOne = function() { return query.findOne; }(); - -/** - * Creates an index on the collection. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the createIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.createIndex = function() { return index.createIndex; }(); - -/** - * Ensures that an index exists, if it does not it creates it - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the ensureIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.ensureIndex = function() { return index.ensureIndex; }(); - -/** - * Retrieves this collections index info. - * - * Options - * - **full** {Boolean, default:false}, returns the full raw index information. - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexInformation method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexInformation = function() { return index.indexInformation; }(); - -/** - * Drops an index from this collection. - * - * @param {String} name - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.dropIndex = function dropIndex (name, callback) { - this.db.dropIndex(this.collectionName, name, callback); -}; - -/** - * Drops all indexes from this collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropAllIndexes method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.dropAllIndexes = function() { return index.dropAllIndexes; }(); - -/** - * Drops all indexes from this collection. - * - * @deprecated - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndexes method or null if an error occured. - * @return {null} - * @api private - */ -Collection.prototype.dropIndexes = function() { return Collection.prototype.dropAllIndexes; }(); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the reIndex method or null if an error occured. - * @return {null} - * @api public -**/ -Collection.prototype.reIndex = function(callback) { - this.db.reIndex(this.collectionName, callback); -} - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * Options - * - **out** {Object}, sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * - **query** {Object}, query filter object. - * - **sort** {Object}, sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * - **limit** {Number}, number of objects to return from collection. - * - **keeptemp** {Boolean, default:false}, keep temporary data. - * - **finalize** {Function | String}, finalize function. - * - **scope** {Object}, can pass in variables that can be access from map/reduce/finalize. - * - **jsMode** {Boolean, default:false}, it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * - **verbose** {Boolean, default:false}, provide statistics on job execution time. - * - **readPreference** {String, only for inline results}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Function|String} map the mapping function. - * @param {Function|String} reduce the reduce function. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the mapReduce method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.mapReduce = function() { return aggregation.mapReduce; }(); - -/** - * Run a group command across a collection - * - * Options - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Object|Array|Function|Code} keys an object, array or function expressing the keys to group by. - * @param {Object} condition an optional condition that must be true for a row to be considered. - * @param {Object} initial initial value of the aggregation counter object. - * @param {Function|Code} reduce the reduce function aggregates (reduces) the objects iterated - * @param {Function|Code} finalize an optional function to be run on each item in the result set just before the item is returned. - * @param {Boolean} command specify if you wish to run using the internal group command or using eval, default is true. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the group method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.group = function() { return aggregation.group; }(); - -/** - * Returns the options of the collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the options method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.options = function() { return commands.options; }(); - -/** - * Returns if the collection is a capped collection - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the isCapped method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.isCapped = function() { return commands.isCapped; }(); - -/** - * Checks if one or more indexes exist on the collection - * - * @param {String|Array} indexNames check if one or more indexes exist on the collection. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexExists method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexExists = function() { return index.indexExists; }(); - -/** - * Execute the geoNear command to search for items in the collection - * - * Options - * - **num** {Number}, max number of results to return. - * - **maxDistance** {Number}, include results up to maxDistance from the point. - * - **distanceMultiplier** {Number}, include a value to multiply the distances with allowing for range conversions. - * - **query** {Object}, filter the results by a query. - * - **spherical** {Boolean, default:false}, perform query using a spherical model. - * - **uniqueDocs** {Boolean, default:false}, the closest location in a document to the center of the search region will always be returned MongoDB > 2.X. - * - **includeLocs** {Boolean, default:false}, include the location data fields in the top level of the results MongoDB > 2.X. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoNear method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.geoNear = function() { return geo.geoNear; }(); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * Options - * - **maxDistance** {Number}, include results up to maxDistance from the point. - * - **search** {Object}, filter the results by a query. - * - **limit** {Number}, max number of results to return. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoHaystackSearch method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.geoHaystackSearch = function() { return geo.geoHaystackSearch; }(); - -/** - * Retrieve all the indexes on the collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexes method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexes = function indexes(callback) { - this.db.indexInformation(this.collectionName, {full:true}, callback); -} - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * - * Options - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Array} array containing all the aggregation framework commands for the execution. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the aggregate method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.aggregate = function() { return aggregation.aggregate; }(); - -/** - * Get all the collection statistics. - * - * Options - * - **scale** {Number}, divide the returned sizes by scale value. - * - **readPreference** {String}, the preferred read preference, require('mongodb').ReadPreference ((ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Objects} [options] options for the stats command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the stats method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.stats = function() { return commands.stats; }(); - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, "hint", { - enumerable: true - , get: function () { - return this.internalHint; - } - , set: function (v) { - this.internalHint = shared.normalizeHintField(v); - } -}); - -/** - * Expose. - */ -exports.Collection = Collection; diff --git a/node_modules/mongodb/lib/mongodb/collection/aggregation.js b/node_modules/mongodb/lib/mongodb/collection/aggregation.js deleted file mode 100644 index e78e96476..000000000 --- a/node_modules/mongodb/lib/mongodb/collection/aggregation.js +++ /dev/null @@ -1,320 +0,0 @@ -var shared = require('./shared') - , utils = require('../utils') - , AggregationCursor = require('../aggregation_cursor').AggregationCursor - , Code = require('bson').Code - , DbCommand = require('../commands/db_command').DbCommand; - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope (scope) { - if (!utils.isObject(scope)) { - return scope; - } - - var keys = Object.keys(scope); - var i = keys.length; - var key; - - while (i--) { - key = keys[i]; - if ('function' == typeof scope[key]) { - scope[key] = new Code(String(scope[key])); - } else { - scope[key] = processScope(scope[key]); - } - } - - return scope; -} - -var pipe = function() { - return new AggregationCursor(this, this.serverCapabilities); -} - -var mapReduce = function mapReduce (map, reduce, options, callback) { - if ('function' === typeof options) callback = options, options = {}; - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if(null == options.out) { - throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - - var mapCommandHash = { - mapreduce: this.collectionName - , map: map - , reduce: reduce - }; - - // Add any other options passed in - for (var name in options) { - if ('scope' == name) { - mapCommandHash[name] = processScope(options[name]); - } else { - mapCommandHash[name] = options[name]; - } - } - - // Set read preference if we set one - var readPreference = shared._getReadConcern(this, options); - - // If we have a read preference and inline is not set as output fail hard - if((readPreference != false && readPreference != 'primary') - && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { - readPreference = 'primary'; - } - - // self - var self = this; - var cmd = DbCommand.createDbCommand(this.db, mapCommandHash); - - this.db._executeQueryCommand(cmd, {read:readPreference}, function (err, result) { - if(err) return callback(err); - if(!result || !result.documents || result.documents.length == 0) - return callback(Error("command failed to return results"), null) - - // Check if we have an error - if(1 != result.documents[0].ok || result.documents[0].err || result.documents[0].errmsg) { - return callback(utils.toError(result.documents[0])); - } - - // Create statistics value - var stats = {}; - if(result.documents[0].timeMillis) stats['processtime'] = result.documents[0].timeMillis; - if(result.documents[0].counts) stats['counts'] = result.documents[0].counts; - if(result.documents[0].timing) stats['timing'] = result.documents[0].timing; - - // invoked with inline? - if(result.documents[0].results) { - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return callback(null, result.documents[0].results); - } - return callback(null, result.documents[0].results, stats); - } - - // The returned collection - var collection = null; - - // If we have an object it's a different db - if(result.documents[0].result != null && typeof result.documents[0].result == 'object') { - var doc = result.documents[0].result; - collection = self.db.db(doc.db).collection(doc.collection); - } else { - // Create a collection object that wraps the result collection - collection = self.db.collection(result.documents[0].result) - } - - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return callback(err, collection); - } - - // Return stats as third set of values - callback(err, collection, stats); - }); -}; - -/** - * Group function helper - * @ignore - */ -var groupFunction = function () { - var c = db[ns].find(condition); - var map = new Map(); - var reduce_function = reduce; - - while (c.hasNext()) { - var obj = c.next(); - var key = {}; - - for (var i = 0, len = keys.length; i < len; ++i) { - var k = keys[i]; - key[k] = obj[k]; - } - - var aggObj = map.get(key); - - if (aggObj == null) { - var newObj = Object.extend({}, key); - aggObj = Object.extend(newObj, initial); - map.put(key, aggObj); - } - - reduce_function(obj, aggObj); - } - - return { "result": map.values() }; -}.toString(); - -var group = function group(keys, condition, initial, reduce, finalize, command, options, callback) { - var args = Array.prototype.slice.call(arguments, 3); - callback = args.pop(); - // Fetch all commands - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if(!(typeof finalize == 'function')) { - command = finalize; - finalize = null; - } - - if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { - keys = Object.keys(keys); - } - - if(typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if(typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - // Execute using the command - if(command) { - var reduceFunction = reduce instanceof Code - ? reduce - : new Code(reduce); - - var selector = { - group: { - 'ns': this.collectionName - , '$reduce': reduceFunction - , 'cond': condition - , 'initial': initial - , 'out': "inline" - } - }; - - // if finalize is defined - if(finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || keys instanceof Code) { - selector.group.$keyf = keys instanceof Code - ? keys - : new Code(keys); - } else { - var hash = {}; - keys.forEach(function (key) { - hash[key] = 1; - }); - selector.group.key = hash; - } - - var cmd = DbCommand.createDbSlaveOkCommand(this.db, selector); - // Set read preference if we set one - var readPreference = shared._getReadConcern(this, options); - // Execute the command - this.db._executeQueryCommand(cmd - , {read:readPreference} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - callback(null, result.retval); - })); - } else { - // Create execution scope - var scope = reduce != null && reduce instanceof Code - ? reduce.scope - : {}; - - scope.ns = this.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - this.db.eval(new Code(groupfn, scope), function (err, results) { - if (err) return callback(err, null); - callback(null, results.result || results); - }); - } -}; - -var aggregate = function(pipeline, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - var self = this; - - // If we have any of the supported options in the options object - var opts = args[args.length - 1]; - options = opts.readPreference - || opts.explain - || opts.cursor - || opts.out - || opts.allowDiskUsage ? args.pop() : {} - // If the callback is the option (as for cursor override it) - if(typeof callback == 'object' && callback != null) options = callback; - - // Convert operations to an array - if(!Array.isArray(args[0])) { - pipeline = []; - // Push all the operations to the pipeline - for(var i = 0; i < args.length; i++) pipeline.push(args[i]); - } - - // Is the user requesting a cursor - if(options.cursor != null && options.out == null) { - // Set the aggregation cursor options - var agg_cursor_options = options.cursor; - agg_cursor_options.pipe = pipeline; - agg_cursor_options.allowDiskUsage = options.allowDiskUsage == null ? false : options.allowDiskUsage; - // Return the aggregation cursor - return new AggregationCursor(this, this.serverCapabilities, agg_cursor_options); - } - - // If out was specified - if(typeof options.out == 'string') { - pipeline.push({$out: options.out}); - } - - // Build the command - var command = { aggregate : this.collectionName, pipeline : pipeline}; - // If we have allowDiskUsage defined - if(options.allowDiskUsage) command.allowDiskUsage = options.allowDiskUsage; - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - // If explain has been specified add it - if(options.explain) command.explain = options.explain; - // Execute the command - this.db.command(command, options, function(err, result) { - if(err) { - callback(err); - } else if(result['err'] || result['errmsg']) { - callback(utils.toError(result)); - } else if(typeof result == 'object' && result['serverPipeline']) { - callback(null, result['serverPipeline']); - } else if(typeof result == 'object' && result['stages']) { - callback(null, result['stages']); - } else { - callback(null, result.result); - } - }); -} - -exports.mapReduce = mapReduce; -exports.group = group; -exports.aggregate = aggregate; -exports.pipe = pipe; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/collection/commands.js b/node_modules/mongodb/lib/mongodb/collection/commands.js deleted file mode 100644 index 046f0095f..000000000 --- a/node_modules/mongodb/lib/mongodb/collection/commands.js +++ /dev/null @@ -1,136 +0,0 @@ -var shared = require('./shared') - , utils = require('../utils') - , DbCommand = require('../commands/db_command').DbCommand; - -var stats = function stats(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - collStats:this.collectionName, - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, callback); -} - -var count = function count(query, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - var skip = options.skip; - var limit = options.limit; - var maxTimeMS = options.maxTimeMS; - - // Final query - var commandObject = { - 'count': this.collectionName - , 'query': query - , 'fields': null - }; - - // Add limit and skip if defined - if(typeof skip == 'number') commandObject.skip = skip; - if(typeof limit == 'number') commandObject.limit = limit; - if(typeof maxTimeMS == 'number') commandObject['$maxTimeMS'] = maxTimeMS; - - // Set read preference if we set one - var readPreference = shared._getReadConcern(this, options); - // Execute the command - this.db._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this.db, commandObject) - , {read: readPreference} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - if(result == null) return callback(new Error("no result returned for count"), null); - callback(null, result.n); - })); -}; - -var distinct = function distinct(key, query, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - var mapCommandHash = { - 'distinct': this.collectionName - , 'query': query - , 'key': key - }; - - // Set read preference if we set one - var readPreference = options['readPreference'] ? options['readPreference'] : false; - // Create the command - var cmd = DbCommand.createDbSlaveOkCommand(this.db, mapCommandHash); - - this.db._executeQueryCommand(cmd, {read:readPreference}, function (err, result) { - if(err) - return callback(err); - if(result.documents[0].ok != 1) - return callback(new Error(result.documents[0].errmsg)); - callback(null, result.documents[0].values); - }); -}; - -var rename = function rename (newName, options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {} - } - - // Get collection class - var Collection = require('../collection').Collection; - // Ensure the new name is valid - shared.checkCollectionName(newName); - - // Execute the command, return the new renamed collection if successful - self.db._executeQueryCommand(DbCommand.createRenameCollectionCommand(self.db, self.collectionName, newName, options) - , utils.handleSingleCommandResultReturn(true, false, function(err, result) { - if(err) return callback(err, null) - try { - if(options.new_collection) - return callback(null, new Collection(self.db, newName, self.db.pkFactory)); - self.collectionName = newName; - callback(null, self); - } catch(err) { - callback(err, null); - } - })); -}; - -var options = function options(callback) { - this.db.collectionsInfo(this.collectionName, function (err, cursor) { - if (err) return callback(err); - cursor.nextObject(function (err, document) { - callback(err, document && document.options || null); - }); - }); -}; - -var isCapped = function isCapped(callback) { - this.options(function(err, document) { - if(err != null) { - callback(err); - } else { - callback(null, document && document.capped); - } - }); -}; - -exports.stats = stats; -exports.count = count; -exports.distinct = distinct; -exports.rename = rename; -exports.options = options; -exports.isCapped = isCapped; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/collection/core.js b/node_modules/mongodb/lib/mongodb/collection/core.js deleted file mode 100644 index 208506e8b..000000000 --- a/node_modules/mongodb/lib/mongodb/collection/core.js +++ /dev/null @@ -1,727 +0,0 @@ -var InsertCommand = require('../commands/insert_command').InsertCommand - , DeleteCommand = require('../commands/delete_command').DeleteCommand - , UpdateCommand = require('../commands/update_command').UpdateCommand - , DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , hasWriteCommands = require('../utils').hasWriteCommands - , shared = require('./shared'); - -/** - * Precompiled regexes - * @ignore - **/ -var eErrorMessages = /No matching object found/; - -// *************************************************** -// Insert function -// *************************************************** -var insert = function insert (docs, options, callback) { - if ('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Get a connection - var connection = this.db.serverConfig.checkoutWriter(); - var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true; - // If we support write commands let's perform the insert using it - if(!useLegacyOps && hasWriteCommands(connection) - && !Buffer.isBuffer(docs) - && (!Array.isArray(docs) && docs.length > 0 && !Buffer.isBuffer(docs[0]))) { - insertWithWriteCommands(this, Array.isArray(docs) ? docs : [docs], options, callback); - return this - } - - // Backwards compatibility - insertAll(this, Array.isArray(docs) ? docs : [docs], options, callback); - return this; -}; - -// -// Uses the new write commands available from 2.6 > -// -var insertWithWriteCommands = function(self, docs, options, callback) { - // Get the intended namespace for the operation - var namespace = self.collectionName; - - // Ensure we have no \x00 bytes in the name causing wrong parsing - if(!!~namespace.indexOf("\x00")) { - return callback(new Error("namespace cannot contain a null character"), null); - } - - // Check if we have passed in continue on error - var continueOnError = typeof options['keepGoing'] == 'boolean' - ? options['keepGoing'] : false; - continueOnError = typeof options['continueOnError'] == 'boolean' - ? options['continueOnError'] : continueOnError; - - // Do we serialzie functions - var serializeFunctions = typeof options.serializeFunctions != 'boolean' - ? self.serializeFunctions : options.serializeFunctions; - - // Checkout a write connection - var connection = self.db.serverConfig.checkoutWriter(); - - // Collect errorOptions - var errorOptions = shared._getWriteConcern(self, options); - - // If we have a write command with no callback and w:0 fail - if(errorOptions.w && errorOptions.w != 0 && callback == null) { - throw new Error("writeConcern requires callback") - } - - // Add the documents and decorate them with id's if they have none - for(var index = 0, len = docs.length; index < len; ++index) { - var doc = docs[index]; - - // Add id to each document if it's not already defined - if (!(Buffer.isBuffer(doc)) - && doc['_id'] == null - && self.db.forceServerObjectId != true - && options.forceServerObjectId != true) { - doc['_id'] = self.pkFactory.createPk(); - } - } - - // Create the write command - var write_command = { - insert: namespace - , writeConcern: errorOptions - , ordered: !continueOnError - , documents: docs - } - - // Execute the write command - self.db.command(write_command - , { connection:connection - , checkKeys: true - , serializeFunctions: serializeFunctions - , writeCommand: true } - , function(err, result) { - if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null); - if(errorOptions.w == 0) return; - if(callback == null) return; - if(err != null) { - // Rewrite for backward compatibility - if(Array.isArray(err.errDetails)) err.code = err.errDetails[0].errCode; - // Return the error - return callback(err, null); - } - - // Result has an error - if(!result.ok && (result.err != null || result.errmsg != null)) { - // Map the error - var error = utils.toError(result); - // Backwards compatibility mapping - if(Array.isArray(error.errDetails)) error.code = error.errDetails[0].errCode; - // Return the error - return callback(error, null); - } - - // Return the results for a whole batch - callback(null, docs) - }); -} - -// -// Uses pre 2.6 OP_INSERT wire protocol -// -var insertAll = function insertAll (self, docs, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Insert options (flags for insert) - var insertFlags = {}; - // If we have a mongodb version >= 1.9.1 support keepGoing attribute - if(options['keepGoing'] != null) { - insertFlags['keepGoing'] = options['keepGoing']; - } - - // If we have a mongodb version >= 1.9.1 support keepGoing attribute - if(options['continueOnError'] != null) { - insertFlags['continueOnError'] = options['continueOnError']; - } - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = self.db.databaseName; - } - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - insertFlags['serializeFunctions'] = options['serializeFunctions']; - } else { - insertFlags['serializeFunctions'] = self.serializeFunctions; - } - - // Get checkKeys value - var checkKeys = typeof options.checkKeys != 'boolean' ? true : options.checkKeys; - - // Pass in options - var insertCommand = new InsertCommand( - self.db - , dbName + "." + self.collectionName, checkKeys, insertFlags); - - // Add the documents and decorate them with id's if they have none - for(var index = 0, len = docs.length; index < len; ++index) { - var doc = docs[index]; - - // Add id to each document if it's not already defined - if (!(Buffer.isBuffer(doc)) - && doc['_id'] == null - && self.db.forceServerObjectId != true - && options.forceServerObjectId != true) { - doc['_id'] = self.pkFactory.createPk(); - } - - insertCommand.add(doc); - } - - // Collect errorOptions - var errorOptions = shared._getWriteConcern(self, options); - // Default command options - var commandOptions = {}; - // If safe is defined check for error message - if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - self.db._executeInsertCommand(insertCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if (err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else if(error[0].jnote || error[0].wnote || error[0].wtimeout) { - callback(utils.toError(error[0])); - } else { - callback(null, docs); - } - }); - } else if(shared._hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute the call without a write concern - var result = self.db._executeInsertCommand(insertCommand, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - - // Otherwise just return - return callback(null, docs); - } -}; - -// *************************************************** -// Remove function -// *************************************************** -var removeWithWriteCommands = function(self, selector, options, callback) { - if ('function' === typeof selector) { - callback = selector; - selector = options = {}; - } else if ('function' === typeof options) { - callback = options; - options = {}; - } - - // Get the intended namespace for the operation - var namespace = self.collectionName; - - // Ensure we have no \x00 bytes in the name causing wrong parsing - if(!!~namespace.indexOf("\x00")) { - return callback(new Error("namespace cannot contain a null character"), null); - } - - // Set default empty selector if none - selector = selector == null ? {} : selector; - - // Check if we have passed in continue on error - var continueOnError = typeof options['keepGoing'] == 'boolean' - ? options['keepGoing'] : false; - continueOnError = typeof options['continueOnError'] == 'boolean' - ? options['continueOnError'] : continueOnError; - - // Do we serialzie functions - var serializeFunctions = typeof options.serializeFunctions != 'boolean' - ? self.serializeFunctions : options.serializeFunctions; - - // Checkout a write connection - var connection = self.db.serverConfig.checkoutWriter(); - - // Figure out the value of top - var limit = options.single == true ? 1 : 0; - var upsert = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Collect errorOptions - var errorOptions = shared._getWriteConcern(self, options); - - // If we have a write command with no callback and w:0 fail - if(errorOptions.w && errorOptions.w != 0 && callback == null) { - throw new Error("writeConcern requires callback") - } - - // Create the write command - var write_command = { - delete: namespace, - writeConcern: errorOptions, - ordered: !continueOnError, - deletes: [{ - q : selector, - limit: limit - }] - } - - // Execute the write command - self.db.command(write_command - , { connection:connection - , checkKeys: true - , serializeFunctions: serializeFunctions - , writeCommand: true } - , function(err, result) { - if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null); - if(errorOptions.w == 0) return; - if(callback == null) return; - if(err != null) { - if(Array.isArray(err.errDetails)) err.code = err.errDetails[0].errCode; - // Return the error - return callback(err, null); - } - - // Result has an error - if(!result.ok && (result.err != null || result.errmsg != null)) { - // Map the error - var error = utils.toError(result); - // Backwards compatibility mapping - if(Array.isArray(error.errDetails)) error.code = error.errDetails[0].errCode; - // Return the error - return callback(error, null); - } - - // Backward compatibility format - var r = backWardsCompatibiltyResults(result, 'remove'); - // Return the results for a whole batch - callback(null, r.n, r) - }); -} - -var remove = function remove(selector, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Get a connection - var connection = this.db.serverConfig.checkoutWriter(); - var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true; - // If we support write commands let's perform the insert using it - if(!useLegacyOps && hasWriteCommands(connection) && !Buffer.isBuffer(selector)) { - return removeWithWriteCommands(this, selector, options, callback); - } - - if ('function' === typeof selector) { - callback = selector; - selector = options = {}; - } else if ('function' === typeof options) { - callback = options; - options = {}; - } - - // Ensure options - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Ensure we have at least an empty selector - selector = selector == null ? {} : selector; - // Set up flags for the command, if we have a single document remove - var flags = 0 | (options.single ? 1 : 0); - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = this.db.databaseName; - } - - // Create a delete command - var deleteCommand = new DeleteCommand( - this.db - , dbName + "." + this.collectionName - , selector - , flags); - - var self = this; - var errorOptions = shared._getWriteConcern(self, options); - // Execute the command, do not add a callback as it's async - if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - var commandOptions = {read:false}; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - // Set safe option - commandOptions['safe'] = true; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - this.db._executeRemoveCommand(deleteCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if(err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else if(error[0].jnote || error[0].wnote || error[0].wtimeout) { - callback(utils.toError(error[0])); - } else { - callback(null, error[0].n); - } - }); - } else if(shared._hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - var result = this.db._executeRemoveCommand(deleteCommand); - // If no callback just return - if (!callback) return; - // If error return error - if (result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(); - } -}; - -// *************************************************** -// Save function -// *************************************************** -var save = function save(doc, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Throw an error if attempting to perform a bulk operation - if(Array.isArray(doc)) throw new Error("doc parameter must be a single document"); - // Extract the id, if we have one we need to do a update command - var id = doc['_id']; - var commandOptions = shared._getWriteConcern(this, options); - - if(id != null) { - commandOptions.upsert = true; - this.update({ _id: id }, doc, commandOptions, callback); - } else { - this.insert(doc, commandOptions, callback && function (err, docs) { - if(err) return callback(err, null); - - if(Array.isArray(docs)) { - callback(err, docs[0]); - } else { - callback(err, docs); - } - }); - } -}; - -// *************************************************** -// Update document function -// *************************************************** -var updateWithWriteCommands = function(self, selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Get the intended namespace for the operation - var namespace = self.collectionName; - - // Ensure we have no \x00 bytes in the name causing wrong parsing - if(!!~namespace.indexOf("\x00")) { - return callback(new Error("namespace cannot contain a null character"), null); - } - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') - return callback(new Error("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') - return callback(new Error("document must be a valid JavaScript object")); - - // Check if we have passed in continue on error - var continueOnError = typeof options['keepGoing'] == 'boolean' - ? options['keepGoing'] : false; - continueOnError = typeof options['continueOnError'] == 'boolean' - ? options['continueOnError'] : continueOnError; - - // Do we serialzie functions - var serializeFunctions = typeof options.serializeFunctions != 'boolean' - ? self.serializeFunctions : options.serializeFunctions; - - // Checkout a write connection - var connection = self.db.serverConfig.checkoutWriter(); - - // Figure out the value of top - var multi = typeof options.multi == 'boolean' ? options.multi : false; - var upsert = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Collect errorOptions - var errorOptions = shared._getWriteConcern(self, options); - - // If we have a write command with no callback and w:0 fail - if(errorOptions.w && errorOptions.w != 0 && callback == null) { - throw new Error("writeConcern requires callback") - } - - // Create the write command - var write_command = { - update: namespace, - writeConcern: errorOptions, - ordered: !continueOnError, - updates: [{ - q : selector, - u: document, - multi: multi, - upsert: upsert - }] - } - - // Check if we have a checkKeys override - var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Execute the write command - self.db.command(write_command - , { connection:connection - , checkKeys: checkKeys - , serializeFunctions: serializeFunctions - , writeCommand: true } - , function(err, result) { - if(errorOptions.w == 0 && typeof callback == 'function') return callback(null, null); - if(errorOptions.w == 0) return; - if(callback == null) return; - if(err != null) { - if(Array.isArray(err.errDetails)) err.code = err.errDetails[0].errCode; - // Return the error - return callback(err, null); - } - - // Result has an error - if(!result.ok && (result.err != null || result.errmsg != null)) { - // Map the error - var error = utils.toError(result); - // Backwards compatibility mapping - if(Array.isArray(error.errDetails)) error.code = error.errDetails[0].errCode; - // Return the error - return callback(error, null); - } - - // Backward compatibility format - var r = backWardsCompatibiltyResults(result, 'update'); - // Return the results for a whole batch - callback(null, r.n, r) - }); -} - -var backWardsCompatibiltyResults = function(result, op) { - // Upserted - var upsertedValue = null; - var finalResult = null; - var updatedExisting = true; - - // We have a single document upserted result - if(Array.isArray(result.upserted) || result.upserted != null) { - updatedExisting = false; - upsertedValue = result.upserted; - } - - // Final result - if(op == 'remove' || op == 'insert') { - finalResult = {ok: true, n: result.n} - } else { - finalResult = {ok: true, n: result.n, updatedExisting: updatedExisting} - } - - if(upsertedValue != null) finalResult.upserted = upsertedValue; - return finalResult; -} - -var update = function update(selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Get a connection - var connection = this.db.serverConfig.checkoutWriter(); - var useLegacyOps = options.useLegacyOps == null || options.useLegacyOps == false ? false : true; - // If we support write commands let's perform the insert using it - if(!useLegacyOps && hasWriteCommands(connection) && !Buffer.isBuffer(selector) && !Buffer.isBuffer(document)) { - return updateWithWriteCommands(this, selector, document, options, callback); - } - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = this.db.databaseName; - } - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') return callback(new Error("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') return callback(new Error("document must be a valid JavaScript object")); - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = this.serializeFunctions; - } - - // Build the options command - var updateCommand = new UpdateCommand( - this.db - , dbName + "." + this.collectionName - , selector - , document - , options); - - var self = this; - // Unpack the error options if any - var errorOptions = shared._getWriteConcern(this, options); - // If safe is defined check for error message - if(shared._hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - var commandOptions = {read:false}; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - this.db._executeUpdateCommand(updateCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if(err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else if(error[0].jnote || error[0].wnote || error[0].wtimeout) { - callback(utils.toError(error[0])); - } else { - callback(null, error[0].n, error[0]); - } - }); - } else if(shared._hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute update - var result = this.db._executeUpdateCommand(updateCommand); - // If no callback just return - if (!callback) return; - // If error return error - if (result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(); - } -}; - -// *************************************************** -// findAndModify function -// *************************************************** -var findAndModify = function findAndModify (query, sort, doc, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - var self = this; - - var queryObject = { - 'findandmodify': this.collectionName - , 'query': query - , 'sort': utils.formattedOrderClause(sort) - }; - - queryObject.new = options.new ? 1 : 0; - queryObject.remove = options.remove ? 1 : 0; - queryObject.upsert = options.upsert ? 1 : 0; - - if (options.fields) { - queryObject.fields = options.fields; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - // Checkout a write connection - options.connection = self.db.serverConfig.checkoutWriter(); - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = this.serializeFunctions; - } - - // No check on the documents - options.checkKeys = false - - // Execute the command - this.db.command(queryObject - , options, function(err, result) { - if(err) return callback(err, null); - return callback(null, result.value, result); - }); -} - -// *************************************************** -// findAndRemove function -// *************************************************** -var findAndRemove = function(query, sort, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - // Add the remove option - options['remove'] = true; - // Execute the callback - this.findAndModify(query, sort, null, options, callback); -} - -// Map methods -exports.insert = insert; -exports.remove = remove; -exports.save = save; -exports.update = update; -exports.findAndModify = findAndModify; -exports.findAndRemove = findAndRemove; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/collection/geo.js b/node_modules/mongodb/lib/mongodb/collection/geo.js deleted file mode 100644 index d2d3f9e12..000000000 --- a/node_modules/mongodb/lib/mongodb/collection/geo.js +++ /dev/null @@ -1,78 +0,0 @@ -var shared = require('./shared') - , utils = require('../utils'); - -var geoNear = function geoNear(x, y, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - geoNear:this.collectionName, - near: [x, y] - } - - // Decorate object if any with known properties - if(options['num'] != null) commandObject['num'] = options['num']; - if(options['maxDistance'] != null) commandObject['maxDistance'] = options['maxDistance']; - if(options['distanceMultiplier'] != null) commandObject['distanceMultiplier'] = options['distanceMultiplier']; - if(options['query'] != null) commandObject['query'] = options['query']; - if(options['spherical'] != null) commandObject['spherical'] = options['spherical']; - if(options['uniqueDocs'] != null) commandObject['uniqueDocs'] = options['uniqueDocs']; - if(options['includeLocs'] != null) commandObject['includeLocs'] = options['includeLocs']; - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, function (err, res) { - if (err) { - callback(err); - } else if (res.err || res.errmsg) { - callback(utils.toError(res)); - } else { - // should we only be returning res.results here? Not sure if the user - // should see the other return information - callback(null, res); - } - }); -} - -var geoHaystackSearch = function geoHaystackSearch(x, y, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - geoSearch:this.collectionName, - near: [x, y] - } - - // Decorate object if any with known properties - if(options['maxDistance'] != null) commandObject['maxDistance'] = options['maxDistance']; - if(options['query'] != null) commandObject['search'] = options['query']; - if(options['search'] != null) commandObject['search'] = options['search']; - if(options['limit'] != null) commandObject['limit'] = options['limit']; - - // Ensure we have the right read preference inheritance - options.readPreference = shared._getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, function (err, res) { - if (err) { - callback(err); - } else if (res.err || res.errmsg) { - callback(utils.toError(res)); - } else { - // should we only be returning res.results here? Not sure if the user - // should see the other return information - callback(null, res); - } - }); -} - -exports.geoNear = geoNear; -exports.geoHaystackSearch = geoHaystackSearch; diff --git a/node_modules/mongodb/lib/mongodb/collection/index.js b/node_modules/mongodb/lib/mongodb/collection/index.js deleted file mode 100644 index dda9cc887..000000000 --- a/node_modules/mongodb/lib/mongodb/collection/index.js +++ /dev/null @@ -1,72 +0,0 @@ -var _getWriteConcern = require('./shared')._getWriteConcern; - -var createIndex = function createIndex (fieldOrSpec, options, callback) { - // Clean up call - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Collect errorOptions - var errorOptions = _getWriteConcern(this, options); - // Execute create index - this.db.createIndex(this.collectionName, fieldOrSpec, options, callback); -}; - -var indexExists = function indexExists(indexes, callback) { - this.indexInformation(function(err, indexInformation) { - // If we have an error return - if(err != null) return callback(err, null); - // Let's check for the index names - if(Array.isArray(indexes)) { - for(var i = 0; i < indexes.length; i++) { - if(indexInformation[indexes[i]] == null) { - return callback(null, false); - } - } - - // All keys found return true - return callback(null, true); - } else { - return callback(null, indexInformation[indexes] != null); - } - }); -} - -var dropAllIndexes = function dropIndexes (callback) { - this.db.dropIndex(this.collectionName, '*', function (err, result) { - if(err) return callback(err, false); - callback(null, true); - }); -}; - -var indexInformation = function indexInformation (options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - // Call the index information - this.db.indexInformation(this.collectionName, options, callback); -}; - -var ensureIndex = function ensureIndex (fieldOrSpec, options, callback) { - // Clean up call - if (typeof callback === 'undefined' && typeof options === 'function') { - callback = options; - options = {}; - } - - if (options == null) { - options = {}; - } - - // Execute create index - this.db.ensureIndex(this.collectionName, fieldOrSpec, options, callback); -}; - -exports.createIndex = createIndex; -exports.indexExists = indexExists; -exports.dropAllIndexes = dropAllIndexes; -exports.indexInformation = indexInformation; -exports.ensureIndex = ensureIndex; diff --git a/node_modules/mongodb/lib/mongodb/collection/query.js b/node_modules/mongodb/lib/mongodb/collection/query.js deleted file mode 100644 index 6f6efc76d..000000000 --- a/node_modules/mongodb/lib/mongodb/collection/query.js +++ /dev/null @@ -1,153 +0,0 @@ -var ObjectID = require('bson').ObjectID - , Scope = require('../scope').Scope - , shared = require('./shared') - , utils = require('../utils'); - -var testForFields = { - limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 - , numberOfRetries: 1, awaitdata: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 - , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1 -}; - -// -// Find method -// -var find = function find () { - var options - , args = Array.prototype.slice.call(arguments, 0) - , has_callback = typeof args[args.length - 1] === 'function' - , has_weird_callback = typeof args[0] === 'function' - , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) - , len = args.length - , selector = len >= 1 ? args[0] : {} - , fields = len >= 2 ? args[1] : undefined; - - if(len === 1 && has_weird_callback) { - // backwards compat for callback?, options case - selector = {}; - options = args[0]; - } - - if(len === 2 && !Array.isArray(fields)) { - var fieldKeys = Object.getOwnPropertyNames(fields); - var is_option = false; - - for(var i = 0; i < fieldKeys.length; i++) { - if(testForFields[fieldKeys[i]] != null) { - is_option = true; - break; - } - } - - if(is_option) { - options = fields; - fields = undefined; - } else { - options = {}; - } - } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { - var newFields = {}; - // Rewrite the array - for(var i = 0; i < fields.length; i++) { - newFields[fields[i]] = 1; - } - // Set the fields - fields = newFields; - } - - if(3 === len) { - options = args[2]; - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Validate correctness of the field selector - var object = fields; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { - selector = {_id:selector}; - } - - // If it's a serialized fields field we need to just let it through - // user be warned it better be good - if(options && options.fields && !(Buffer.isBuffer(options.fields))) { - fields = {}; - - if(Array.isArray(options.fields)) { - if(!options.fields.length) { - fields['_id'] = 1; - } else { - for (var i = 0, l = options.fields.length; i < l; i++) { - fields[options.fields[i]] = 1; - } - } - } else { - fields = options.fields; - } - } - - if (!options) options = {}; - options.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; - options.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; - options.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.raw; - options.hint = options.hint != null ? shared.normalizeHintField(options.hint) : this.internalHint; - options.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; - // If we have overridden slaveOk otherwise use the default db setting - options.slaveOk = options.slaveOk != null ? options.slaveOk : this.db.slaveOk; - - // Set option - var o = options; - // Support read/readPreference - if(o["read"] != null) o["readPreference"] = o["read"]; - // Set the read preference - o.read = o["readPreference"] ? o.readPreference : this.readPreference; - // Adjust slave ok if read preference is secondary or secondary only - if(o.read == "secondary" || o.read == "secondaryOnly") options.slaveOk = true; - - // Set the selector - o.selector = selector; - - // Create precursor - var scope = new Scope(this, {}, fields, o); - // Callback for backward compatibility - if(callback) return callback(null, scope.find(selector)); - // Return the pre cursor object - return scope.find(selector); -}; - -var findOne = function findOne () { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - var cursor = this.find.apply(this, args).limit(-1).batchSize(1); - - // Return the item - cursor.nextObject(function(err, item) { - if(err != null) return callback(utils.toError(err), null); - callback(null, item); - }); -}; - - -exports.find = find; -exports.findOne = findOne; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/collection/shared.js b/node_modules/mongodb/lib/mongodb/collection/shared.js deleted file mode 100644 index 77eae039f..000000000 --- a/node_modules/mongodb/lib/mongodb/collection/shared.js +++ /dev/null @@ -1,120 +0,0 @@ -// *************************************************** -// Write concerns -// *************************************************** -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = {w:1}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(self.opts.w != null || typeof self.opts.j == 'boolean' || typeof self.opts.journal == 'boolean' || typeof self.opts.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.opts); - } else if(typeof self.opts.safe == "boolean") { - finalOptions = {w: (self.opts.safe ? 1 : 0)}; - } else if(self.db.safe.w != null || typeof self.db.safe.j == 'boolean' || typeof self.db.safe.journal == 'boolean' || typeof self.db.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.safe); - } else if(self.db.options.w != null || typeof self.db.options.j == 'boolean' || typeof self.db.options.journal == 'boolean' || typeof self.db.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.options); - } else if(typeof self.db.safe == "boolean") { - finalOptions = {w: (self.db.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -var _getReadConcern = function(self, options) { - if(options.readPreference) return options.readPreference; - if(self.readPreference) return self.readPreference; - if(self.db.readPreference) return self.readPreference; - return 'primary'; -} - -/** - * @ignore - */ -var checkCollectionName = function checkCollectionName (collectionName) { - if('string' !== typeof collectionName) { - throw Error("collection name must be a String"); - } - - if(!collectionName || collectionName.indexOf('..') != -1) { - throw Error("collection names cannot be empty"); - } - - if(collectionName.indexOf('$') != -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { - throw Error("collection names must not contain '$'"); - } - - if(collectionName.match(/^\.|\.$/) != null) { - throw Error("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the colletion name - if(!!~collectionName.indexOf("\x00")) { - throw new Error("collection names cannot contain a null character"); - } -}; - - -/** - * Normalizes a `hint` argument. - * - * @param {String|Object|Array} hint - * @return {Object} - * @api private - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if(typeof hint == 'string') { - finalHint = hint; - } else if(Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if(hint != null && typeof hint == 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -exports._getWriteConcern = _getWriteConcern; -exports._hasWriteConcern = _hasWriteConcern; -exports._getReadConcern = _getReadConcern; -exports.checkCollectionName = checkCollectionName; -exports.normalizeHintField = normalizeHintField; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/command_cursor.js b/node_modules/mongodb/lib/mongodb/command_cursor.js deleted file mode 100644 index e973e2c37..000000000 --- a/node_modules/mongodb/lib/mongodb/command_cursor.js +++ /dev/null @@ -1,309 +0,0 @@ -var Long = require('bson').Long - , GetMoreCommand = require('./commands/get_more_command').GetMoreCommand; - -var CommandCursor = function(db, collection, command, options) { - // Ensure empty options if no options passed - options = options || {}; - - // Default cursor id is 0 - var cursorId = Long.fromInt(0); - var zeroCursor = Long.fromInt(0); - var state = 'init'; - - // Hardcode batch size - command.cursor.batchSize = 1; - - // BatchSize - var batchSize = command.cursor.batchSize || 0; - var raw = options.raw || false; - var readPreference = options.readPreference || 'primary'; - - // Checkout a connection - var connection = db.serverConfig.checkoutReader(readPreference); - // MaxTimeMS - var maxTimeMS = options.maxTimeMS; - - // Contains all the items - var items = null; - - // Execute getmore - var getMore = function(callback) { - // Resolve more of the cursor using the getMore command - var getMoreCommand = new GetMoreCommand(db - , db.databaseName + "." + collection.collectionName - , batchSize - , cursorId - ); - - // Set up options - var command_options = { connection:connection }; - - // Execute the getMore Command - db._executeQueryCommand(getMoreCommand, command_options, function(err, result) { - if(err) { - items = []; - state = 'closed'; - return callback(err); - } - - // Return all the documents - callback(null, result); - }); - } - - var exhaustGetMore = function(callback) { - getMore(function(err, result) { - if(err) { - items = []; - state = 'closed'; - return callback(err, null); - } - - // Add the items - items = items.concat(result.documents); - - // Set the cursor id - cursorId = result.cursorId; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // If the cursor is done - if(result.cursorId.equals(zeroCursor)) { - return callback(null, items); - } - - // Check the cursor id - exhaustGetMore(callback); - }); - } - - var exhaustGetMoreEach = function(callback) { - getMore(function(err, result) { - if(err) { - items = []; - state = 'closed'; - return callback(err, null); - } - - // Add the items - items = result.documents; - - // Emit all the items in the first batch - while(items.length > 0) { - callback(null, items.shift()); - } - - // Set the cursor id - cursorId = result.cursorId; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // If the cursor is done - if(result.cursorId.equals(zeroCursor)) { - state = "closed"; - return callback(null, null); - } - - // Check the cursor id - exhaustGetMoreEach(callback); - }); - } - - // - // Get all the elements - // - this.get = function(options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Set the connection to the passed in one if it's provided - connection = options.connection ? options.connection : connection; - - // Command options - var _options = {connection:connection}; - if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS; - - // Execute the internal command first - db.command(command, _options, function(err, result) { - if(err) { - state = 'closed'; - return callback(err, null); - } - - // Retrieve the cursor id - cursorId = result.cursor.id; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // Validate cursorId - if(cursorId.equals(zeroCursor)) { - return callback(null, result.cursor.firstBatch); - }; - - // Add to the items - items = result.cursor.firstBatch; - // Execute the getMore - exhaustGetMore(callback); - }); - } - - // - // Iterate over all the items - // - this.each = function(options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // If it's a closed cursor return error - if(this.isClosed()) return callback(new Error("cursor is closed")); - // Set the connection to the passed in one if it's provided - connection = options.connection ? options.connection : connection; - - // Command options - var _options = {connection:connection}; - if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS; - - // Execute the internal command first - db.command(command, _options, function(err, result) { - if(err) { - state = 'closed'; - return callback(err, null); - } - - // Get all the items - items = result.cursor.firstBatch; - - // Emit all the items in the first batch - while(items.length > 0) { - callback(null, items.shift()); - } - - // Retrieve the cursor id - cursorId = result.cursor.id; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // If no cursor we just finish up the current batch of items - if(cursorId.equals(zeroCursor)) { - state = 'closed'; - return callback(null, null); - } - - // Emit each until no more getMore's - exhaustGetMoreEach(callback); - }); - } - - // - // Get the next object - // - this.next = function(options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // If it's a closed cursor return error - if(this.isClosed()) return callback(new Error("cursor is closed")); - - // Set the connection to the passed in one if it's provided - connection = options.connection ? options.connection : connection; - - // Command options - var _options = {connection:connection}; - if(typeof maxTimeMS == 'number') _options.maxTimeMS = maxTimeMS; - - // Execute the internal command first - if(!items) { - db.command(command, _options, function(err, result) { - if(err) { - state = 'closed'; - return callback(err, null); - } - - // Retrieve the cursor id - cursorId = result.cursor.id; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - // Get the first batch results - items = result.cursor.firstBatch; - // We have items return the first one - if(items.length > 0) { - callback(null, items.shift()); - } else { - state = 'closed'; - callback(null, null); - } - }); - } else if(items.length > 0) { - callback(null, items.shift()); - } else if(items.length == 0 && cursorId.equals(zeroCursor)) { - state = 'closed'; - callback(null, null); - } else { - // Execute a getMore - getMore(function(err, result) { - if(err) { - state = 'closed'; - return callback(err, null); - } - - // Set the cursor id - cursorId = result.cursorId; - if(typeof cursorId == 'number') cursorId = Long.fromNumber(cursorId); - - // Add the items - items = items.concat(result.documents); - // If no more items - if(items.length == 0) { - state = 'closed'; - return callback(null, null); - } - - // Return the item - return callback(null, items.shift()); - }) - } - } - - // Validate if the cursor is closed - this.isClosed = function() { - return state == 'closed'; - } - - // Allow us to set the MaxTimeMS - this.maxTimeMS = function(_maxTimeMS) { - maxTimeMS = _maxTimeMS; - } - - // Close the cursor sending a kill cursor command if needed - this.close = function(options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Close the cursor if not needed - if(cursorId instanceof Long && cursorId.greaterThan(Long.fromInt(0))) { - try { - var command = new KillCursorCommand(this.db, [cursorId]); - // Added an empty callback to ensure we don't throw any null exceptions - db._executeQueryCommand(command, {connection:connection}); - } catch(err) {} - } - - // Null out the connection - connection = null; - // Reset cursor id - cursorId = Long.fromInt(0); - // Set to closed status - state = 'closed'; - // Clear out all the items - items = null; - - if(callback) { - callback(null, null); - } - } -} - -exports.CommandCursor = CommandCursor; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/commands/base_command.js b/node_modules/mongodb/lib/mongodb/commands/base_command.js deleted file mode 100644 index 955858283..000000000 --- a/node_modules/mongodb/lib/mongodb/commands/base_command.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - Base object used for common functionality -**/ -var BaseCommand = exports.BaseCommand = function BaseCommand() { -}; - -var id = 1; -BaseCommand.prototype.getRequestId = function getRequestId() { - if (!this.requestId) this.requestId = id++; - return this.requestId; -}; - -BaseCommand.prototype.setMongosReadPreference = function setMongosReadPreference(readPreference, tags) {} - -BaseCommand.prototype.updateRequestId = function() { - this.requestId = id++; - return this.requestId; -}; - -// OpCodes -BaseCommand.OP_REPLY = 1; -BaseCommand.OP_MSG = 1000; -BaseCommand.OP_UPDATE = 2001; -BaseCommand.OP_INSERT = 2002; -BaseCommand.OP_GET_BY_OID = 2003; -BaseCommand.OP_QUERY = 2004; -BaseCommand.OP_GET_MORE = 2005; -BaseCommand.OP_DELETE = 2006; -BaseCommand.OP_KILL_CURSORS = 2007; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/commands/db_command.js b/node_modules/mongodb/lib/mongodb/commands/db_command.js deleted file mode 100644 index 1f5b065ad..000000000 --- a/node_modules/mongodb/lib/mongodb/commands/db_command.js +++ /dev/null @@ -1,253 +0,0 @@ -var QueryCommand = require('./query_command').QueryCommand, - InsertCommand = require('./insert_command').InsertCommand, - inherits = require('util').inherits, - utils = require('../utils'), - crypto = require('crypto'); - -/** - Db Command -**/ -var DbCommand = exports.DbCommand = function(dbInstance, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) { - QueryCommand.call(this); - this.collectionName = collectionName; - this.queryOptions = queryOptions; - this.numberToSkip = numberToSkip; - this.numberToReturn = numberToReturn; - this.query = query; - this.returnFieldSelector = returnFieldSelector; - this.db = dbInstance; - - // Set the slave ok bit - if(this.db && this.db.slaveOk) { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Make sure we don't get a null exception - options = options == null ? {} : options; - - // Allow for overriding the BSON checkKeys function - this.checkKeys = typeof options['checkKeys'] == 'boolean' ? options["checkKeys"] : true; - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(DbCommand, QueryCommand); - -// Constants -DbCommand.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; -DbCommand.SYSTEM_INDEX_COLLECTION = "system.indexes"; -DbCommand.SYSTEM_PROFILE_COLLECTION = "system.profile"; -DbCommand.SYSTEM_USER_COLLECTION = "system.users"; -DbCommand.SYSTEM_COMMAND_COLLECTION = "$cmd"; -DbCommand.SYSTEM_JS_COLLECTION = "system.js"; - -// New commands -DbCommand.NcreateIsMasterCommand = function(db, databaseName) { - return new DbCommand(db, databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null); -}; - -// Provide constructors for different db commands -DbCommand.createIsMasterCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null); -}; - -DbCommand.createCollectionInfoCommand = function(db, selector) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_NAMESPACE_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, 0, selector, null); -}; - -DbCommand.createGetNonceCommand = function(db, options) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'getnonce':1}, null); -}; - -DbCommand.createAuthenticationCommand = function(db, username, password, nonce, authdb) { - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password); - var key = md5.digest('hex'); - // Creat selector - var selector = {'authenticate':1, 'user':username, 'nonce':nonce, 'key':key}; - // Create db command - return new DbCommand(db, authdb + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NONE, 0, -1, selector, null); -}; - -DbCommand.createLogoutCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'logout':1}, null); -}; - -DbCommand.createCreateCollectionCommand = function(db, collectionName, options) { - var selector = {'create':collectionName}; - // Modify the options to ensure correct behaviour - for(var name in options) { - if(options[name] != null && options[name].constructor != Function) selector[name] = options[name]; - } - // Execute the command - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, selector, null); -}; - -DbCommand.createDropCollectionCommand = function(db, collectionName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'drop':collectionName}, null); -}; - -DbCommand.createRenameCollectionCommand = function(db, fromCollectionName, toCollectionName, options) { - var renameCollection = db.databaseName + "." + fromCollectionName; - var toCollection = db.databaseName + "." + toCollectionName; - var dropTarget = options && options.dropTarget ? options.dropTarget : false; - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}, null); -}; - -DbCommand.createGetLastErrorCommand = function(options, db) { - - if (typeof db === 'undefined') { - db = options; - options = {}; - } - // Final command - var command = {'getlasterror':1}; - // If we have an options Object let's merge in the fields (fsync/wtimeout/w) - if('object' === typeof options) { - for(var name in options) { - command[name] = options[name] - } - } - - // Special case for w == 1, remove the w - if(1 == command.w) { - delete command.w; - } - - // Execute command - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command, null); -}; - -DbCommand.createGetLastStatusCommand = DbCommand.createGetLastErrorCommand; - -DbCommand.createGetPreviousErrorsCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'getpreverror':1}, null); -}; - -DbCommand.createResetErrorHistoryCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'reseterror':1}, null); -}; - -DbCommand.createCreateIndexCommand = function(db, collectionName, fieldOrSpec, options) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if('string' == typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - - } else if(utils.isArray(fieldOrSpec)) { - - fieldOrSpec.forEach(function(f) { - if('string' == typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if(utils.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if(utils.isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - - } else if(utils.isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - // Generate the index name - var indexName = typeof options.name == 'string' - ? options.name - : indexes.join("_"); - - var selector = { - 'ns': db.databaseName + "." + collectionName, - 'key': fieldHash, - 'name': indexName - } - - // Ensure we have a correct finalUnique - var finalUnique = options == null || 'object' === typeof options - ? false - : options; - - // Set up options - options = options == null || typeof options == 'boolean' - ? {} - : options; - - // Add all the options - var keys = Object.keys(options); - for(var i = 0; i < keys.length; i++) { - selector[keys[i]] = options[keys[i]]; - } - - if(selector['unique'] == null) - selector['unique'] = finalUnique; - - var name = db.databaseName + "." + DbCommand.SYSTEM_INDEX_COLLECTION; - var cmd = new InsertCommand(db, name, false); - return cmd.add(selector); -}; - -DbCommand.logoutCommand = function(db, command_hash, options) { - var dbName = options != null && options['authdb'] != null ? options['authdb'] : db.databaseName; - return new DbCommand(db, dbName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null); -} - -DbCommand.createDropIndexCommand = function(db, collectionName, indexName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'deleteIndexes':collectionName, 'index':indexName}, null); -}; - -DbCommand.createReIndexCommand = function(db, collectionName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'reIndex':collectionName}, null); -}; - -DbCommand.createDropDatabaseCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'dropDatabase':1}, null); -}; - -DbCommand.createDbCommand = function(db, command_hash, options, auth_db) { - var db_name = (auth_db ? auth_db : db.databaseName) + "." + DbCommand.SYSTEM_COMMAND_COLLECTION; - options = options == null ? {checkKeys: false} : options; - return new DbCommand(db, db_name, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null, options); -}; - -DbCommand.createAdminDbCommand = function(db, command_hash) { - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null); -}; - -DbCommand.createAdminDbCommandSlaveOk = function(db, command_hash) { - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null); -}; - -DbCommand.createDbSlaveOkCommand = function(db, command_hash, options) { - options = options == null ? {checkKeys: false} : options; - var dbName = options.dbName ? options.dbName : db.databaseName; - return new DbCommand(db, dbName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null, options); -}; diff --git a/node_modules/mongodb/lib/mongodb/commands/delete_command.js b/node_modules/mongodb/lib/mongodb/commands/delete_command.js deleted file mode 100644 index 61a37edfd..000000000 --- a/node_modules/mongodb/lib/mongodb/commands/delete_command.js +++ /dev/null @@ -1,129 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var DeleteCommand = exports.DeleteCommand = function(db, collectionName, selector, flags) { - BaseCommand.call(this); - - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("delete raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.flags = flags; - this.collectionName = collectionName; - this.selector = selector; - this.db = db; -}; - -inherits(DeleteCommand, BaseCommand); - -DeleteCommand.OP_DELETE = 2006; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - int32 ZERO; // 0 - reserved for future use - mongo.BSON selector; // query object. See below for details. -} -*/ -DeleteCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.selector, false, true) + (4 * 4); - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (DeleteCommand.OP_DELETE >> 24) & 0xff; - _command[_index + 2] = (DeleteCommand.OP_DELETE >> 16) & 0xff; - _command[_index + 1] = (DeleteCommand.OP_DELETE >> 8) & 0xff; - _command[_index] = DeleteCommand.OP_DELETE & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the flags - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(this.selector)) { - documentLength = this.selector.length; - // Copy the data into the current buffer - this.selector.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(this.selector, false, _command, _index) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/commands/get_more_command.js b/node_modules/mongodb/lib/mongodb/commands/get_more_command.js deleted file mode 100644 index 1b6b1727a..000000000 --- a/node_modules/mongodb/lib/mongodb/commands/get_more_command.js +++ /dev/null @@ -1,88 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits, - binaryutils = require('../utils'); - -/** - Get More Document Command -**/ -var GetMoreCommand = exports.GetMoreCommand = function(db, collectionName, numberToReturn, cursorId) { - BaseCommand.call(this); - - this.collectionName = collectionName; - this.numberToReturn = numberToReturn; - this.cursorId = cursorId; - this.db = db; -}; - -inherits(GetMoreCommand, BaseCommand); - -GetMoreCommand.OP_GET_MORE = 2005; - -GetMoreCommand.prototype.toBinary = function() { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 8 + (4 * 4); - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index++] = totalLengthOfCommand & 0xff; - _command[_index++] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index++] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index++] = (totalLengthOfCommand >> 24) & 0xff; - - // Write the request ID - _command[_index++] = this.requestId & 0xff; - _command[_index++] = (this.requestId >> 8) & 0xff; - _command[_index++] = (this.requestId >> 16) & 0xff; - _command[_index++] = (this.requestId >> 24) & 0xff; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the op_code for the command - _command[_index++] = GetMoreCommand.OP_GET_MORE & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 8) & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 16) & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 24) & 0xff; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Number of documents to return - _command[_index++] = this.numberToReturn & 0xff; - _command[_index++] = (this.numberToReturn >> 8) & 0xff; - _command[_index++] = (this.numberToReturn >> 16) & 0xff; - _command[_index++] = (this.numberToReturn >> 24) & 0xff; - - // Encode the cursor id - var low_bits = this.cursorId.getLowBits(); - // Encode low bits - _command[_index++] = low_bits & 0xff; - _command[_index++] = (low_bits >> 8) & 0xff; - _command[_index++] = (low_bits >> 16) & 0xff; - _command[_index++] = (low_bits >> 24) & 0xff; - - var high_bits = this.cursorId.getHighBits(); - // Encode high bits - _command[_index++] = high_bits & 0xff; - _command[_index++] = (high_bits >> 8) & 0xff; - _command[_index++] = (high_bits >> 16) & 0xff; - _command[_index++] = (high_bits >> 24) & 0xff; - // Return command - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/commands/insert_command.js b/node_modules/mongodb/lib/mongodb/commands/insert_command.js deleted file mode 100644 index c6e51e957..000000000 --- a/node_modules/mongodb/lib/mongodb/commands/insert_command.js +++ /dev/null @@ -1,161 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var InsertCommand = exports.InsertCommand = function(db, collectionName, checkKeys, options) { - BaseCommand.call(this); - - this.collectionName = collectionName; - this.documents = []; - this.checkKeys = checkKeys == null ? true : checkKeys; - this.db = db; - this.flags = 0; - this.serializeFunctions = false; - - // Ensure valid options hash - options = options == null ? {} : options; - - // Check if we have keepGoing set -> set flag if it's the case - if(options['keepGoing'] != null && options['keepGoing']) { - // This will finish inserting all non-index violating documents even if it returns an error - this.flags = 1; - } - - // Check if we have keepGoing set -> set flag if it's the case - if(options['continueOnError'] != null && options['continueOnError']) { - // This will finish inserting all non-index violating documents even if it returns an error - this.flags = 1; - } - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(InsertCommand, BaseCommand); - -// OpCodes -InsertCommand.OP_INSERT = 2002; - -InsertCommand.prototype.add = function(document) { - if(Buffer.isBuffer(document)) { - var object_size = document[0] | document[1] << 8 | document[2] << 16 | document[3] << 24; - if(object_size != document.length) { - var error = new Error("insert raw message size does not match message header size [" + document.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.documents.push(document); - return this; -}; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - BSON[] documents; // one or more documents to insert into the collection -} -*/ -InsertCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + (4 * 4); - // var docLength = 0 - for(var i = 0; i < this.documents.length; i++) { - if(Buffer.isBuffer(this.documents[i])) { - totalLengthOfCommand += this.documents[i].length; - } else { - // Calculate size of document - totalLengthOfCommand += this.db.bson.calculateObjectSize(this.documents[i], this.serializeFunctions, true); - } - } - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (InsertCommand.OP_INSERT >> 24) & 0xff; - _command[_index + 2] = (InsertCommand.OP_INSERT >> 16) & 0xff; - _command[_index + 1] = (InsertCommand.OP_INSERT >> 8) & 0xff; - _command[_index] = InsertCommand.OP_INSERT & 0xff; - // Adjust index - _index = _index + 4; - // Write flags if any - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write all the bson documents to the buffer at the index offset - for(var i = 0; i < this.documents.length; i++) { - // Document binary length - var documentLength = 0 - var object = this.documents[i]; - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - // Serialize the document straight to the buffer - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - - return _command; -}; diff --git a/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js b/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js deleted file mode 100644 index d8ccb0c3a..000000000 --- a/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js +++ /dev/null @@ -1,98 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits, - binaryutils = require('../utils'); - -/** - Insert Document Command -**/ -var KillCursorCommand = exports.KillCursorCommand = function(db, cursorIds) { - BaseCommand.call(this); - - this.cursorIds = cursorIds; - this.db = db; -}; - -inherits(KillCursorCommand, BaseCommand); - -KillCursorCommand.OP_KILL_CURSORS = 2007; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - int32 numberOfCursorIDs; // number of cursorIDs in message - int64[] cursorIDs; // array of cursorIDs to close -} -*/ -KillCursorCommand.prototype.toBinary = function() { - // Calculate total length of the document - var totalLengthOfCommand = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (KillCursorCommand.OP_KILL_CURSORS >> 24) & 0xff; - _command[_index + 2] = (KillCursorCommand.OP_KILL_CURSORS >> 16) & 0xff; - _command[_index + 1] = (KillCursorCommand.OP_KILL_CURSORS >> 8) & 0xff; - _command[_index] = KillCursorCommand.OP_KILL_CURSORS & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Number of cursors to kill - var numberOfCursors = this.cursorIds.length; - _command[_index + 3] = (numberOfCursors >> 24) & 0xff; - _command[_index + 2] = (numberOfCursors >> 16) & 0xff; - _command[_index + 1] = (numberOfCursors >> 8) & 0xff; - _command[_index] = numberOfCursors & 0xff; - // Adjust index - _index = _index + 4; - - // Encode all the cursors - for(var i = 0; i < this.cursorIds.length; i++) { - // Encode the cursor id - var low_bits = this.cursorIds[i].getLowBits(); - // Encode low bits - _command[_index + 3] = (low_bits >> 24) & 0xff; - _command[_index + 2] = (low_bits >> 16) & 0xff; - _command[_index + 1] = (low_bits >> 8) & 0xff; - _command[_index] = low_bits & 0xff; - // Adjust index - _index = _index + 4; - - var high_bits = this.cursorIds[i].getHighBits(); - // Encode high bits - _command[_index + 3] = (high_bits >> 24) & 0xff; - _command[_index + 2] = (high_bits >> 16) & 0xff; - _command[_index + 1] = (high_bits >> 8) & 0xff; - _command[_index] = high_bits & 0xff; - // Adjust index - _index = _index + 4; - } - - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/commands/query_command.js b/node_modules/mongodb/lib/mongodb/commands/query_command.js deleted file mode 100644 index 121820698..000000000 --- a/node_modules/mongodb/lib/mongodb/commands/query_command.js +++ /dev/null @@ -1,283 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var QueryCommand = exports.QueryCommand = function(db, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) { - BaseCommand.call(this); - - // Validate correctness off the selector - var object = query, - object_size; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - object = returnFieldSelector; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Make sure we don't get a null exception - options = options == null ? {} : options; - // Set up options - this.collectionName = collectionName; - this.queryOptions = queryOptions; - this.numberToSkip = numberToSkip; - this.numberToReturn = numberToReturn; - - // Ensure we have no null query - query = query == null ? {} : query; - // Wrap query in the $query parameter so we can add read preferences for mongos - this.query = query; - this.returnFieldSelector = returnFieldSelector; - this.db = db; - - // Force the slave ok flag to be set if we are not using primary read preference - if(this.db && this.db.slaveOk) { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // If checkKeys set - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(QueryCommand, BaseCommand); - -QueryCommand.OP_QUERY = 2004; - -/* - * Adds the read prefrence to the current command - */ -QueryCommand.prototype.setMongosReadPreference = function(readPreference, tags) { - // If we have readPreference set to true set to secondary prefered - if(readPreference == true) { - readPreference = 'secondaryPreferred'; - } else if(readPreference == 'false') { - readPreference = 'primary'; - } - - // Force the slave ok flag to be set if we are not using primary read preference - if(readPreference != false && readPreference != 'primary') { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Backward compatibility, ensure $query only set on read preference so 1.8.X works - if((readPreference != null || tags != null) && this.query['$query'] == null) { - this.query = {'$query': this.query}; - } - - // If we have no readPreference set and no tags, check if the slaveOk bit is set - if(readPreference == null && tags == null) { - // If we have a slaveOk bit set the read preference for MongoS - if(this.queryOptions & QueryCommand.OPTS_SLAVE) { - this.query['$readPreference'] = {mode: 'secondary'} - } else { - this.query['$readPreference'] = {mode: 'primary'} - } - } - - // Build read preference object - if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') { - this.query['$readPreference'] = readPreference.toObject(); - } else if(readPreference != null) { - // Add the read preference - this.query['$readPreference'] = {mode: readPreference}; - - // If we have tags let's add them - if(tags != null) { - this.query['$readPreference']['tags'] = tags; - } - } -} - -/* -struct { - MsgHeader header; // standard message header - int32 opts; // query options. See below for details. - cstring fullCollectionName; // "dbname.collectionname" - int32 numberToSkip; // number of documents to skip when returning results - int32 numberToReturn; // number of documents to return in the first OP_REPLY - BSON query ; // query object. See below for details. - [ BSON returnFieldSelector; ] // OPTIONAL : selector indicating the fields to return. See below for details. -} -*/ -QueryCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Total length of the command - var totalLengthOfCommand = 0; - // Calculate total length of the document - if(Buffer.isBuffer(this.query)) { - totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.query.length + (4 * 4); - } else { - totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.db.bson.calculateObjectSize(this.query, this.serializeFunctions, true) + (4 * 4); - } - - // Calculate extra fields size - if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) { - if(Object.keys(this.returnFieldSelector).length > 0) { - totalLengthOfCommand += this.db.bson.calculateObjectSize(this.returnFieldSelector, this.serializeFunctions, true); - } - } else if(Buffer.isBuffer(this.returnFieldSelector)) { - totalLengthOfCommand += this.returnFieldSelector.length; - } - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (QueryCommand.OP_QUERY >> 24) & 0xff; - _command[_index + 2] = (QueryCommand.OP_QUERY >> 16) & 0xff; - _command[_index + 1] = (QueryCommand.OP_QUERY >> 8) & 0xff; - _command[_index] = QueryCommand.OP_QUERY & 0xff; - // Adjust index - _index = _index + 4; - - // Write the query options - _command[_index + 3] = (this.queryOptions >> 24) & 0xff; - _command[_index + 2] = (this.queryOptions >> 16) & 0xff; - _command[_index + 1] = (this.queryOptions >> 8) & 0xff; - _command[_index] = this.queryOptions & 0xff; - // Adjust index - _index = _index + 4; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the number of documents to skip - _command[_index + 3] = (this.numberToSkip >> 24) & 0xff; - _command[_index + 2] = (this.numberToSkip >> 16) & 0xff; - _command[_index + 1] = (this.numberToSkip >> 8) & 0xff; - _command[_index] = this.numberToSkip & 0xff; - // Adjust index - _index = _index + 4; - - // Write the number of documents to return - _command[_index + 3] = (this.numberToReturn >> 24) & 0xff; - _command[_index + 2] = (this.numberToReturn >> 16) & 0xff; - _command[_index + 1] = (this.numberToReturn >> 8) & 0xff; - _command[_index] = this.numberToReturn & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - var object = this.query; - - // Serialize the selector - if(Buffer.isBuffer(object)) { - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - // Serialize the document straight to the buffer - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - // Push field selector if available - if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) { - if(Object.keys(this.returnFieldSelector).length > 0) { - var documentLength = this.db.bson.serializeWithBufferAndIndex(this.returnFieldSelector, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - } if(this.returnFieldSelector != null && Buffer.isBuffer(this.returnFieldSelector)) { - // Document binary length - var documentLength = 0 - var object = this.returnFieldSelector; - - // Serialize the selector - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - - // Return finished command - return _command; -}; - -// Constants -QueryCommand.OPTS_NONE = 0; -QueryCommand.OPTS_TAILABLE_CURSOR = 2; -QueryCommand.OPTS_SLAVE = 4; -QueryCommand.OPTS_OPLOG_REPLAY = 8; -QueryCommand.OPTS_NO_CURSOR_TIMEOUT = 16; -QueryCommand.OPTS_AWAIT_DATA = 32; -QueryCommand.OPTS_EXHAUST = 64; -QueryCommand.OPTS_PARTIAL = 128; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/commands/update_command.js b/node_modules/mongodb/lib/mongodb/commands/update_command.js deleted file mode 100644 index daa3cba48..000000000 --- a/node_modules/mongodb/lib/mongodb/commands/update_command.js +++ /dev/null @@ -1,189 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Update Document Command -**/ -var UpdateCommand = exports.UpdateCommand = function(db, collectionName, spec, document, options) { - BaseCommand.call(this); - - var object = spec; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("update spec raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - var object = document; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("update document raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.collectionName = collectionName; - this.spec = spec; - this.document = document; - this.db = db; - this.serializeFunctions = false; - this.checkKeys = typeof options.checkKeys != 'boolean' ? false : options.checkKeys; - - // Generate correct flags - var db_upsert = 0; - var db_multi_update = 0; - db_upsert = options != null && options['upsert'] != null ? (options['upsert'] == true ? 1 : 0) : db_upsert; - db_multi_update = options != null && options['multi'] != null ? (options['multi'] == true ? 1 : 0) : db_multi_update; - - // Flags - this.flags = parseInt(db_multi_update.toString() + db_upsert.toString(), 2); - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(UpdateCommand, BaseCommand); - -UpdateCommand.OP_UPDATE = 2001; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - int32 flags; // bit vector. see below - BSON spec; // the query to select the document - BSON document; // the document data to update with or insert -} -*/ -UpdateCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.spec, false, true) + - this.db.bson.calculateObjectSize(this.document, this.serializeFunctions, true) + (4 * 4); - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (UpdateCommand.OP_UPDATE >> 24) & 0xff; - _command[_index + 2] = (UpdateCommand.OP_UPDATE >> 16) & 0xff; - _command[_index + 1] = (UpdateCommand.OP_UPDATE >> 8) & 0xff; - _command[_index] = UpdateCommand.OP_UPDATE & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the update flags - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - var object = this.spec; - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, false) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - // Document binary length - var documentLength = 0 - var object = this.document; - - // Serialize the document - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(object, false, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - return _command; -}; - -// Constants -UpdateCommand.DB_UPSERT = 0; -UpdateCommand.DB_MULTI_UPDATE = 1; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/connection/base.js b/node_modules/mongodb/lib/mongodb/connection/base.js deleted file mode 100644 index 8fbeabfc5..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/base.js +++ /dev/null @@ -1,504 +0,0 @@ -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , utils = require('../utils') - , mongodb_cr_authenticate = require('../auth/mongodb_cr.js').authenticate - , mongodb_gssapi_authenticate = require('../auth/mongodb_gssapi.js').authenticate - , mongodb_sspi_authenticate = require('../auth/mongodb_sspi.js').authenticate - , mongodb_plain_authenticate = require('../auth/mongodb_plain.js').authenticate - , mongodb_x509_authenticate = require('../auth/mongodb_x509.js').authenticate; - -var id = 0; - -/** - * Internal class for callback storage - * @ignore - */ -var CallbackStore = function() { - // Make class an event emitter - EventEmitter.call(this); - // Add a info about call variable - this._notReplied = {}; - this.id = id++; -} - -/** - * @ignore - */ -inherits(CallbackStore, EventEmitter); - -CallbackStore.prototype.notRepliedToIds = function() { - return Object.keys(this._notReplied); -} - -CallbackStore.prototype.callbackInfo = function(id) { - return this._notReplied[id]; -} - -/** - * Internal class for holding non-executed commands - * @ignore - */ -var NonExecutedOperationStore = function(config) { - var commands = { - read: [] - , write_reads: [] - , write: [] - }; - - // Execute all callbacks - var fireCallbacksWithError = function(error, commands) { - while(commands.length > 0) { - var command = commands.shift(); - if(typeof command.callback == 'function') { - command.callback(error); - } - } - } - - this.count = function() { - return commands.read.length - + commands.write_reads.length - + commands.write.length; - } - - this.write = function(op) { - commands.write.push(op); - } - - this.read_from_writer = function(op) { - commands.write_reads.push(op); - } - - this.read = function(op) { - commands.read.push(op); - } - - this.validateBufferLimit = function(numberToFailOn) { - if(numberToFailOn == -1 || numberToFailOn == null) - return true; - - // Error passed back - var error = utils.toError("No connection operations buffering limit of " + numberToFailOn + " reached"); - - // If we have passed the number of items to buffer we need to fail - if(numberToFailOn < this.count()) { - // Fail all of the callbacks - fireCallbacksWithError(error, commands.read); - fireCallbacksWithError(error, commands.write_reads); - fireCallbacksWithError(error, commands.write); - } - - // Return false - return false; - } - - this.execute_queries = function(executeInsertCommand) { - var connection = config.checkoutReader(); - if(connection == null || connection instanceof Error) return; - - // Write out all the queries - while(commands.read.length > 0) { - // Get the next command - var command = commands.read.shift(); - command.options.connection = connection; - // Execute the next command - command.executeQueryCommand(command.db, command.db_command, command.options, command.callback); - } - } - - this.execute_writes = function() { - var connection = config.checkoutWriter(); - if(connection == null || connection instanceof Error) return; - - // Write out all the queries to the primary - while(commands.write_reads.length > 0) { - // Get the next command - var command = commands.write_reads.shift(); - command.options.connection = connection; - // Execute the next command - command.executeQueryCommand(command.db, command.db_command, command.options, command.callback); - } - - // Execute all write operations - while(commands.write.length > 0) { - // Get the next command - var command = commands.write.shift(); - // Set the connection - command.options.connection = connection; - // Execute the next command - command.executeInsertCommand(command.db, command.db_command, command.options, command.callback); - } - } -} - -/** - * Internal class for authentication storage - * @ignore - */ -var AuthStore = function() { - var _auths = []; - - this.add = function(authMechanism, dbName, username, password, authdbName, gssapiServiceName) { - // Check for duplicates - if(!this.contains(dbName)) { - // Base config - var config = { - 'username':username - , 'password':password - , 'db': dbName - , 'authMechanism': authMechanism - , 'gssapiServiceName': gssapiServiceName - }; - - // Add auth source if passed in - if(typeof authdbName == 'string') { - config['authdb'] = authdbName; - } - - // Push the config - _auths.push(config); - } - } - - this.contains = function(dbName) { - for(var i = 0; i < _auths.length; i++) { - if(_auths[i].db == dbName) return true; - } - - return false; - } - - this.remove = function(dbName) { - var newAuths = []; - - // Filter out all the login details - for(var i = 0; i < _auths.length; i++) { - if(_auths[i].db != dbName) newAuths.push(_auths[i]); - } - - // Set the filtered list - _auths = newAuths; - } - - this.get = function(index) { - return _auths[index]; - } - - this.length = function() { - return _auths.length; - } - - this.toArray = function() { - return _auths.slice(0); - } -} - -/** - * Internal class for storing db references - * @ignore - */ -var DbStore = function() { - var _dbs = []; - - this.add = function(db) { - var found = false; - - // Only add if it does not exist already - for(var i = 0; i < _dbs.length; i++) { - if(db.databaseName == _dbs[i].databaseName) found = true; - } - - // Only add if it does not already exist - if(!found) { - _dbs.push(db); - } - } - - this.reset = function() { - _dbs = []; - } - - this.db = function() { - return _dbs; - } - - this.fetch = function(databaseName) { - // Only add if it does not exist already - for(var i = 0; i < _dbs.length; i++) { - if(databaseName == _dbs[i].databaseName) - return _dbs[i]; - } - - return null; - } - - this.emit = function(event, message, object, reset, filterDb, rethrow_if_no_listeners) { - var emitted = false; - - // Not emitted and we have enabled rethrow, let process.uncaughtException - // deal with the issue - if(!emitted && rethrow_if_no_listeners) { - return process.nextTick(function() { - throw message; - }) - } - - // Emit the events - for(var i = 0; i < _dbs.length; i++) { - if(_dbs[i].listeners(event).length > 0) { - if(filterDb == null || filterDb.databaseName !== _dbs[i].databaseName - || filterDb.tag !== _dbs[i].tag) { - _dbs[i].emit(event, message, object == null ? _dbs[i] : object); - emitted = true; - } - } - } - - // Emit error message - if(message - && event == 'error' - && !emitted - && rethrow_if_no_listeners - && object && object.db) { - process.nextTick(function() { - object.db.emit(event, message, null); - }) - } - } -} - -var Base = function Base() { - EventEmitter.call(this); - - // Callback store is part of connection specification - if(Base._callBackStore == null) { - Base._callBackStore = new CallbackStore(); - } - - // Create a new callback store - this._callBackStore = new CallbackStore(); - // All commands not being executed - this._commandsStore = new NonExecutedOperationStore(this); - // Create a new auth store - this.auth = new AuthStore(); - // Contains all the dbs attached to this server config - this._dbStore = new DbStore(); -} - -/** - * @ignore - */ -inherits(Base, EventEmitter); - -/** - * @ignore - */ -Base.prototype._apply_auths = function(db, callback) { - _apply_auths_serially(this, db, this.auth.toArray(), callback); -} - -var _apply_auths_serially = function(self, db, auths, callback) { - if(auths.length == 0) return callback(null, null); - // Get the first auth - var auth = auths.shift(); - var connections = self.allRawConnections(); - var connectionsLeft = connections.length; - var options = {}; - - if(auth.authMechanism == 'GSSAPI') { - // We have the kerberos library, execute auth process - if(process.platform == 'win32') { - mongodb_sspi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } else { - mongodb_gssapi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } - } else if(auth.authMechanism == 'MONGODB-CR') { - mongodb_cr_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } else if(auth.authMechanism == 'PLAIN') { - mongodb_plain_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } else if(auth.authMechanism == 'MONGODB-X509') { - mongodb_x509_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } -} - -/** - * Fire all the errors - * @ignore - */ -Base.prototype.__executeAllCallbacksWithError = function(err) { - // Check all callbacks - var keys = Object.keys(this._callBackStore._notReplied); - // For each key check if it's a callback that needs to be returned - for(var j = 0; j < keys.length; j++) { - var info = this._callBackStore._notReplied[keys[j]]; - // Execute callback with error - this._callBackStore.emit(keys[j], err, null); - // Remove the key - delete this._callBackStore._notReplied[keys[j]]; - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[keys[j]]; - } - } -} - -/** - * Fire all the errors - * @ignore - */ -Base.prototype.__executeAllServerSpecificErrorCallbacks = function(host, port, err) { - // Check all callbacks - var keys = Object.keys(this._callBackStore._notReplied); - // For each key check if it's a callback that needs to be returned - for(var j = 0; j < keys.length; j++) { - var info = this._callBackStore._notReplied[keys[j]]; - - if(info.connection) { - // Unpack the connection settings - var _host = info.connection.socketOptions.host; - var _port = info.connection.socketOptions.port; - // If the server matches execute the callback with the error - if(_port == port && _host == host) { - this._callBackStore.emit(keys[j], err, null); - // Remove the key - delete this._callBackStore._notReplied[keys[j]]; - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[keys[j]]; - } - } - } - } -} - -/** - * Register a handler - * @ignore - * @api private - */ -Base.prototype._registerHandler = function(db_command, raw, connection, exhaust, callback) { - // Check if we have exhausted - if(typeof exhaust == 'function') { - callback = exhaust; - exhaust = false; - } - - // Add the callback to the list of handlers - this._callBackStore.once(db_command.getRequestId(), callback); - // Add the information about the reply - this._callBackStore._notReplied[db_command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, connection:connection, exhaust:exhaust}; -} - -/** - * Re-Register a handler, on the cursor id f.ex - * @ignore - * @api private - */ -Base.prototype._reRegisterHandler = function(newId, object, callback) { - // Add the callback to the list of handlers - this._callBackStore.once(newId, object.callback.listener); - // Add the information about the reply - this._callBackStore._notReplied[newId] = object.info; -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._flushAllCallHandlers = function(err) { - var keys = Object.keys(this._callBackStore._notReplied); - - for(var i = 0; i < keys.length; i++) { - this._callHandler(keys[i], null, err); - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._callHandler = function(id, document, err) { - var self = this; - - // If there is a callback peform it - if(this._callBackStore.listeners(id).length >= 1) { - // Get info object - var info = this._callBackStore._notReplied[id]; - // Delete the current object - delete this._callBackStore._notReplied[id]; - // Call the handle directly don't emit - var callback = this._callBackStore.listeners(id)[0].listener; - // Remove the listeners - this._callBackStore.removeAllListeners(id); - // Force key deletion because it nulling it not deleting in 0.10.X - if(this._callBackStore._events) { - delete this._callBackStore._events[id]; - } - - try { - // Execute the callback if one was provided - if(typeof callback == 'function') callback(err, document, info.connection); - } catch(err) { - self._emitAcrossAllDbInstances(self, null, "error", utils.toError(err), self, true, true); - } - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._hasHandler = function(id) { - return this._callBackStore.listeners(id).length >= 1; -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._removeHandler = function(id) { - // Remove the information - if(this._callBackStore._notReplied[id] != null) delete this._callBackStore._notReplied[id]; - // Remove the callback if it's registered - this._callBackStore.removeAllListeners(id); - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[id]; - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._findHandler = function(id) { - var info = this._callBackStore._notReplied[id]; - // Return the callback - return {info:info, callback:(this._callBackStore.listeners(id).length >= 1) ? this._callBackStore.listeners(id)[0] : null} -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._emitAcrossAllDbInstances = function(server, filterDb, event, message, object, resetConnection, rethrow_if_no_listeners) { - if(resetConnection) { - var dbs = this._dbStore.db(); - - for(var i = 0; i < dbs.length; i++) { - if(typeof dbs[i].openCalled != 'undefined') - dbs[i].openCalled = false; - } - } - - // Fire event - this._dbStore.emit(event, message, object, resetConnection, filterDb, rethrow_if_no_listeners); -} - -exports.Base = Base; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/connection/connection.js b/node_modules/mongodb/lib/mongodb/connection/connection.js deleted file mode 100644 index 45f69ad7a..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/connection.js +++ /dev/null @@ -1,541 +0,0 @@ -var utils = require('./connection_utils'), - inherits = require('util').inherits, - net = require('net'), - EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits, - binaryutils = require('../utils'), - tls = require('tls'); - -var Connection = exports.Connection = function(id, socketOptions) { - var self = this; - // Set up event emitter - EventEmitter.call(this); - // Store all socket options - this.socketOptions = socketOptions ? socketOptions : {host:'localhost', port:27017, domainSocket:false}; - // Set keep alive default if not overriden - if(this.socketOptions.keepAlive == null && (process.platform !== "sunos" || process.platform !== "win32")) this.socketOptions.keepAlive = 100; - // Id for the connection - this.id = id; - // State of the connection - this.connected = false; - // Set if this is a domain socket - this.domainSocket = this.socketOptions.domainSocket; - - // Supported min and max wire protocol - this.minWireVersion = 0; - this.maxWireVersion = 2; - - // - // Connection parsing state - // - this.maxBsonSize = socketOptions.maxBsonSize ? socketOptions.maxBsonSize : Connection.DEFAULT_MAX_BSON_SIZE; - this.maxMessageSizeBytes = socketOptions.maxMessageSizeBytes ? socketOptions.maxMessageSizeBytes : Connection.DEFAULT_MAX_MESSAGE_SIZE; - // Contains the current message bytes - this.buffer = null; - // Contains the current message size - this.sizeOfMessage = 0; - // Contains the readIndex for the messaage - this.bytesRead = 0; - // Contains spill over bytes from additional messages - this.stubBuffer = 0; - - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[], end:[]}; - - // Just keeps list of events we allow - resetHandlers(this, false); - // Bson object - this.maxBsonSettings = { - disableDriverBSONSizeCheck: this.socketOptions['disableDriverBSONSizeCheck'] || false - , maxBsonSize: this.maxBsonSize - , maxMessageSizeBytes: this.maxMessageSizeBytes - } - - // Allow setting the socketTimeoutMS on all connections - // to work around issues such as secondaries blocking due to compaction - Object.defineProperty(this, "socketTimeoutMS", { - enumerable: true - , get: function () { return self.socketOptions.socketTimeoutMS; } - , set: function (value) { - // Set the socket timeoutMS value - self.socketOptions.socketTimeoutMS = value; - // Set the physical connection timeout - self.connection.setTimeout(self.socketOptions.socketTimeoutMS); - } - }); -} - -// Set max bson size -Connection.DEFAULT_MAX_BSON_SIZE = 1024 * 1024 * 4; -// Set default to max bson to avoid overflow or bad guesses -Connection.DEFAULT_MAX_MESSAGE_SIZE = Connection.DEFAULT_MAX_BSON_SIZE; - -// Inherit event emitter so we can emit stuff wohoo -inherits(Connection, EventEmitter); - -Connection.prototype.start = function() { - var self = this; - - // If we have a normal connection - if(this.socketOptions.ssl) { - // Create new connection instance - if(this.domainSocket) { - this.connection = net.createConnection(this.socketOptions.host); - } else { - this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host); - } - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("opened connection", this.socketOptions); - } - - // Set options on the socket - this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout); - // Work around for 0.4.X - if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay); - // Set keep alive if defined - if(process.version.indexOf("v0.4") == -1) { - if(this.socketOptions.keepAlive > 0) { - this.connection.setKeepAlive(true, this.socketOptions.keepAlive); - } else { - this.connection.setKeepAlive(false); - } - } - - // Check if the driver should validate the certificate - var validate_certificates = this.socketOptions.sslValidate == true ? true : false; - - // Create options for the tls connection - var tls_options = { - socket: this.connection - , rejectUnauthorized: false - } - - // If we wish to validate the certificate we have provided a ca store - if(validate_certificates) { - tls_options.ca = this.socketOptions.sslCA; - } - - // If we have a certificate to present - if(this.socketOptions.sslCert) { - tls_options.cert = this.socketOptions.sslCert; - tls_options.key = this.socketOptions.sslKey; - } - - // If the driver has been provided a private key password - if(this.socketOptions.sslPass) { - tls_options.passphrase = this.socketOptions.sslPass; - } - - // Contains the cleartext stream - var cleartext = null; - // Attempt to establish a TLS connection to the server - try { - cleartext = tls.connect(this.socketOptions.port, this.socketOptions.host, tls_options, function() { - // If we have a ssl certificate validation error return an error - if(cleartext.authorizationError && validate_certificates) { - // Emit an error - return self.emit("error", cleartext.authorizationError, self, {ssl:true}); - } - - // Connect to the server - connectHandler(self)(); - }) - } catch(err) { - return self.emit("error", "SSL connection failed", self, {ssl:true}); - } - - // Save the output stream - this.writeSteam = cleartext; - - // Set up data handler for the clear stream - cleartext.on("data", createDataHandler(this)); - // Do any handling of end event of the stream - cleartext.on("end", endHandler(this)); - cleartext.on("error", errorHandler(this)); - - // Handle any errors - this.connection.on("error", errorHandler(this)); - // Handle timeout - this.connection.on("timeout", timeoutHandler(this)); - // Handle drain event - this.connection.on("drain", drainHandler(this)); - // Handle the close event - this.connection.on("close", closeHandler(this)); - } else { - // Create new connection instance - if(this.domainSocket) { - this.connection = net.createConnection(this.socketOptions.host); - } else { - this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host); - } - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("opened connection", this.socketOptions); - } - - // Set options on the socket - this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout); - // Work around for 0.4.X - if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay); - // Set keep alive if defined - if(process.version.indexOf("v0.4") == -1) { - if(this.socketOptions.keepAlive > 0) { - this.connection.setKeepAlive(true, this.socketOptions.keepAlive); - } else { - this.connection.setKeepAlive(false); - } - } - - // Set up write stream - this.writeSteam = this.connection; - // Add handlers - this.connection.on("error", errorHandler(this)); - // Add all handlers to the socket to manage it - this.connection.on("connect", connectHandler(this)); - // this.connection.on("end", endHandler(this)); - this.connection.on("data", createDataHandler(this)); - this.connection.on("timeout", timeoutHandler(this)); - this.connection.on("drain", drainHandler(this)); - this.connection.on("close", closeHandler(this)); - } -} - -// Check if the sockets are live -Connection.prototype.isConnected = function() { - return this.connected && !this.connection.destroyed && this.connection.writable && this.connection.readable; -} - -// Validate if the driver supports this server -Connection.prototype.isCompatible = function() { - if(this.serverCapabilities == null) return true; - // Is compatible with backward server - if(this.serverCapabilities.minWireVersion == 0 - && this.serverCapabilities.maxWireVersion ==0) return true; - - // Check if we overlap - if(this.serverCapabilities.minWireVersion >= this.minWireVersion - && this.serverCapabilities.maxWireVersion <= this.maxWireVersion) return true; - - // Not compatible - return false; -} - -// Write the data out to the socket -Connection.prototype.write = function(command, callback) { - try { - // If we have a list off commands to be executed on the same socket - if(Array.isArray(command)) { - for(var i = 0; i < command.length; i++) { - try { - // Pass in the bson validation settings (validate early) - var binaryCommand = command[i].toBinary(this.maxBsonSettings) - - if(this.logger != null && this.logger.doDebug) - this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]}); - - this.writeSteam.write(binaryCommand); - } catch(err) { - return callback(err, null); - } - } - } else { - try { - // Pass in the bson validation settings (validate early) - var binaryCommand = command.toBinary(this.maxBsonSettings) - // Do we have a logger active log the event - if(this.logger != null && this.logger.doDebug) - this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]}); - // Write the binary command out to socket - this.writeSteam.write(binaryCommand); - } catch(err) { - return callback(err, null) - } - } - } catch (err) { - if(typeof callback === 'function') callback(err); - } -} - -// Force the closure of the connection -Connection.prototype.close = function() { - // clear out all the listeners - resetHandlers(this, true); - // Add a dummy error listener to catch any weird last moment errors (and ignore them) - this.connection.on("error", function() {}) - // destroy connection - this.connection.destroy(); - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("closed connection", this.connection); - } -} - -// Reset all handlers -var resetHandlers = function(self, clearListeners) { - self.eventHandlers = {error:[], connect:[], close:[], end:[], timeout:[], parseError:[], message:[]}; - - // If we want to clear all the listeners - if(clearListeners && self.connection != null) { - var keys = Object.keys(self.eventHandlers); - // Remove all listeners - for(var i = 0; i < keys.length; i++) { - self.connection.removeAllListeners(keys[i]); - } - } -} - -// -// Handlers -// - -// Connect handler -var connectHandler = function(self) { - return function(data) { - // Set connected - self.connected = true; - // Now that we are connected set the socket timeout - self.connection.setTimeout(self.socketOptions.socketTimeoutMS != null ? self.socketOptions.socketTimeoutMS : self.socketOptions.timeout); - // Emit the connect event with no error - self.emit("connect", null, self); - } -} - -var createDataHandler = exports.Connection.createDataHandler = function(self) { - // We need to handle the parsing of the data - // and emit the messages when there is a complete one - return function(data) { - // Parse until we are done with the data - while(data.length > 0) { - // If we still have bytes to read on the current message - if(self.bytesRead > 0 && self.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; - // Check if the current chunk contains the rest of the message - if(remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(self.buffer, self.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - self.bytesRead = self.bytesRead + data.length; - - // Reset state of buffer - data = new Buffer(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - try { - var emitBuffer = self.buffer; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Emit the buffer - self.emit("message", emitBuffer, self); - } catch(err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if(self.stubBuffer != null && self.stubBuffer.length > 0) { - - // If we have enough bytes to determine the message size let's do it - if(self.stubBuffer.length + data.length > 4) { - // Prepad the data - var newData = new Buffer(self.stubBuffer.length + data.length); - self.stubBuffer.copy(newData, 0); - data.copy(newData, self.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - - } else { - - // Add the the bytes to the stub buffer - var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); - // Copy existing stub buffer - self.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, self.stubBuffer.length); - // Exit parsing loop - data = new Buffer(0); - } - } else { - if(data.length > 4) { - // Retrieve the message size - var sizeOfMessage = binaryutils.decodeUInt32(data, 0); - // If we have a negative sizeOfMessage emit error and return - if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonSize) { - var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ - sizeOfMessage: sizeOfMessage, - bytesRead: self.bytesRead, - stubBuffer: self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage > data.length) { - self.buffer = new Buffer(sizeOfMessage); - // Copy all the data into the buffer - data.copy(self.buffer, 0); - // Update bytes read - self.bytesRead = data.length; - // Update sizeOfMessage - self.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage == data.length) { - try { - var emitBuffer = data; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - // Emit the message - self.emit("message", emitBuffer, self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonSize) { - var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:0, - buffer:null, - stubBuffer:null}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - - // Clear out the state of the parser - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else { - try { - var emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - self.emit("message", emitBuffer, self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - - } - } else { - // Create a buffer that contains the space for the non-complete message - self.stubBuffer = new Buffer(data.length) - // Copy the data to the stub buffer - data.copy(self.stubBuffer, 0); - // Exit parsing loop - data = new Buffer(0); - } - } - } - } - } -} - -var endHandler = function(self) { - return function() { - // Set connected to false - self.connected = false; - // Emit end event - self.emit("end", {err: 'connection received Fin packet from [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } -} - -var timeoutHandler = function(self) { - return function() { - // Set connected to false - self.connected = false; - // Emit timeout event - self.emit("timeout", {err: 'connection to [' + self.socketOptions.host + ':' + self.socketOptions.port + '] timed out'}, self); - } -} - -var drainHandler = function(self) { - return function() { - } -} - -var errorHandler = function(self) { - return function(err) { - self.connection.destroy(); - // Set connected to false - self.connected = false; - // Emit error - self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } -} - -var closeHandler = function(self) { - return function(hadError) { - // If we have an error during the connection phase - if(hadError && !self.connected) { - // Set disconnected - self.connected = false; - // Emit error - self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } else { - // Set disconnected - self.connected = false; - // Emit close - self.emit("close", {err: 'connection closed to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } - } -} - -// Some basic defaults -Connection.DEFAULT_PORT = 27017; - - - - - - - diff --git a/node_modules/mongodb/lib/mongodb/connection/connection_pool.js b/node_modules/mongodb/lib/mongodb/connection/connection_pool.js deleted file mode 100644 index 3d9e7c5dd..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/connection_pool.js +++ /dev/null @@ -1,295 +0,0 @@ -var utils = require('./connection_utils'), - inherits = require('util').inherits, - net = require('net'), - timers = require('timers'), - EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits, - MongoReply = require("../responses/mongo_reply").MongoReply, - Connection = require("./connection").Connection; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) { - if(typeof host !== 'string') { - throw new Error("host must be specified [" + host + "]"); - } - - // Set up event emitter - EventEmitter.call(this); - - // Keep all options for the socket in a specific collection allowing the user to specify the - // Wished upon socket connection parameters - this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {}; - this.socketOptions.host = host; - this.socketOptions.port = port; - this.socketOptions.domainSocket = false; - this.bson = bson; - // PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc) - this.poolSize = poolSize; - this.minPoolSize = Math.floor(this.poolSize / 2) + 1; - - // Check if the host is a socket - if(host.match(/^\//)) { - this.socketOptions.domainSocket = true; - } else if(typeof port === 'string') { - try { - port = parseInt(port, 10); - } catch(err) { - new Error("port must be specified or valid integer[" + port + "]"); - } - } else if(typeof port !== 'number') { - throw new Error("port must be specified [" + port + "]"); - } - - // Set default settings for the socket options - utils.setIntegerParameter(this.socketOptions, 'timeout', 0); - // Delay before writing out the data to the server - utils.setBooleanParameter(this.socketOptions, 'noDelay', true); - // Delay before writing out the data to the server - utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0); - // Set the encoding of the data read, default is binary == null - utils.setStringParameter(this.socketOptions, 'encoding', null); - // Allows you to set a throttling bufferSize if you need to stop overflows - utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0); - - // Internal structures - this.openConnections = []; - // Assign connection id's - this.connectionId = 0; - - // Current index for selection of pool connection - this.currentConnectionIndex = 0; - // The pool state - this._poolState = 'disconnected'; - // timeout control - this._timeout = false; - // Time to wait between connections for the pool - this._timeToWait = 10; -} - -inherits(ConnectionPool, EventEmitter); - -ConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) { - if(maxBsonSize == null){ - maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxBsonSize = maxBsonSize; - this.openConnections[i].maxBsonSettings.maxBsonSize = maxBsonSize; - } -} - -ConnectionPool.prototype.setMaxMessageSizeBytes = function(maxMessageSizeBytes) { - if(maxMessageSizeBytes == null){ - maxMessageSizeBytes = Connection.DEFAULT_MAX_MESSAGE_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxMessageSizeBytes = maxMessageSizeBytes; - this.openConnections[i].maxBsonSettings.maxMessageSizeBytes = maxMessageSizeBytes; - } -} - -// Start a function -var _connect = function(_self) { - // return new function() { - // Create a new connection instance - var connection = new Connection(_self.connectionId++, _self.socketOptions); - // Set logger on pool - connection.logger = _self.logger; - // Connect handler - connection.on("connect", function(err, connection) { - // Add connection to list of open connections - _self.openConnections.push(connection); - // If the number of open connections is equal to the poolSize signal ready pool - if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') { - // Set connected - _self._poolState = 'connected'; - // Emit pool ready - _self.emit("poolReady"); - } else if(_self.openConnections.length < _self.poolSize) { - // Wait a little bit of time to let the close event happen if the server closes the connection - // so we don't leave hanging connections around - if(typeof _self._timeToWait == 'number') { - setTimeout(function() { - // If we are still connecting (no close events fired in between start another connection) - if(_self._poolState == 'connecting') { - _connect(_self); - } - }, _self._timeToWait); - } else { - processor(function() { - // If we are still connecting (no close events fired in between start another connection) - if(_self._poolState == 'connecting') { - _connect(_self); - } - }); - } - } - }); - - var numberOfErrors = 0 - - // Error handler - connection.on("error", function(err, connection, error_options) { - numberOfErrors++; - // If we are already disconnected ignore the event - if(_self._poolState != 'disconnected' && _self.listeners("error").length > 0) { - _self.emit("error", err, connection, error_options); - } - - // Close the connection - connection.close(); - // Set pool as disconnected - _self._poolState = 'disconnected'; - // Stop the pool - _self.stop(); - }); - - // Close handler - connection.on("close", function() { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("close").length > 0) { - _self.emit("close"); - } - - // Set disconnected - _self._poolState = 'disconnected'; - // Stop - _self.stop(); - }); - - // Timeout handler - connection.on("timeout", function(err, connection) { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("timeout").length > 0) { - _self.emit("timeout", err); - } - - // Close the connection - connection.close(); - // Set disconnected - _self._poolState = 'disconnected'; - _self.stop(); - }); - - // Parse error, needs a complete shutdown of the pool - connection.on("parseError", function() { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("parseError").length > 0) { - _self.emit("parseError", new Error("parseError occured")); - } - - // Set disconnected - _self._poolState = 'disconnected'; - _self.stop(); - }); - - connection.on("message", function(message) { - _self.emit("message", message); - }); - - // Start connection in the next tick - connection.start(); - // }(); -} - - -// Start method, will throw error if no listeners are available -// Pass in an instance of the listener that contains the api for -// finding callbacks for a given message etc. -ConnectionPool.prototype.start = function() { - var markerDate = new Date().getTime(); - var self = this; - - if(this.listeners("poolReady").length == 0) { - throw "pool must have at least one listener ready that responds to the [poolReady] event"; - } - - // Set pool state to connecting - this._poolState = 'connecting'; - this._timeout = false; - - _connect(self); -} - -// Restart a connection pool (on a close the pool might be in a wrong state) -ConnectionPool.prototype.restart = function() { - // Close all connections - this.stop(false); - // Now restart the pool - this.start(); -} - -// Stop the connections in the pool -ConnectionPool.prototype.stop = function(removeListeners) { - removeListeners = removeListeners == null ? true : removeListeners; - // Set disconnected - this._poolState = 'disconnected'; - - // Clear all listeners if specified - if(removeListeners) { - this.removeAllEventListeners(); - } - - // Close all connections - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].close(); - } - - // Clean up - this.openConnections = []; -} - -// Check the status of the connection -ConnectionPool.prototype.isConnected = function() { - // return this._poolState === 'connected'; - return this.openConnections.length > 0 && this.openConnections[0].isConnected(); -} - -// Checkout a connection from the pool for usage, or grab a specific pool instance -ConnectionPool.prototype.checkoutConnection = function(id) { - var index = (this.currentConnectionIndex++ % (this.openConnections.length)); - var connection = this.openConnections[index]; - return connection; -} - -ConnectionPool.prototype.getAllConnections = function() { - return this.openConnections; -} - -// Remove all non-needed event listeners -ConnectionPool.prototype.removeAllEventListeners = function() { - this.removeAllListeners("close"); - this.removeAllListeners("error"); - this.removeAllListeners("timeout"); - this.removeAllListeners("connect"); - this.removeAllListeners("end"); - this.removeAllListeners("parseError"); - this.removeAllListeners("message"); - this.removeAllListeners("poolReady"); -} - - - - - - - - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/lib/mongodb/connection/connection_utils.js b/node_modules/mongodb/lib/mongodb/connection/connection_utils.js deleted file mode 100644 index 591092495..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/connection_utils.js +++ /dev/null @@ -1,23 +0,0 @@ -exports.setIntegerParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "number" && object[field] !== parseInt(object[field], 10)) { - throw "object field [" + field + "] must be a numeric integer value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} - -exports.setBooleanParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "boolean") { - throw "object field [" + field + "] must be a boolean value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} - -exports.setStringParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "string") { - throw "object field [" + field + "] must be a string value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/connection/mongos.js b/node_modules/mongodb/lib/mongodb/connection/mongos.js deleted file mode 100644 index 01a9c3232..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/mongos.js +++ /dev/null @@ -1,537 +0,0 @@ -var ReadPreference = require('./read_preference').ReadPreference - , Base = require('./base').Base - , Server = require('./server').Server - , format = require('util').format - , timers = require('timers') - , utils = require('../utils') - , inherits = require('util').inherits; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * Mongos constructor provides a connection to a mongos proxy including failover to additional servers - * - * Options - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **ha** {Boolean, default:true}, turn on high availability, attempts to reconnect to down proxies - * - **haInterval** {Number, default:2000}, time between each replicaset status check. - * - * @class Represents a Mongos connection with failover to backup proxies - * @param {Array} list of mongos server objects - * @param {Object} [options] additional options for the mongos connection - */ -var Mongos = function Mongos(servers, options) { - // Set up basic - if(!(this instanceof Mongos)) - return new Mongos(servers, options); - - // Set up event emitter - Base.call(this); - - // Throw error on wrong setup - if(servers == null || !Array.isArray(servers) || servers.length == 0) - throw new Error("At least one mongos proxy must be in the array"); - - // Ensure we have at least an empty options object - this.options = options == null ? {} : options; - // Set default connection pool options - this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {}; - // Enabled ha - this.haEnabled = this.options['ha'] == null ? true : this.options['ha']; - this._haInProgress = false; - // How often are we checking for new servers in the replicaset - this.mongosStatusCheckInterval = this.options['haInterval'] == null ? 1000 : this.options['haInterval']; - // Save all the server connections - this.servers = servers; - // Servers we need to attempt reconnect with - this.downServers = {}; - // Servers that are up - this.upServers = {}; - // Up servers by ping time - this.upServersByUpTime = {}; - // Emit open setup - this.emitOpen = this.options.emitOpen || true; - // Just contains the current lowest ping time and server - this.lowestPingTimeServer = null; - this.lowestPingTime = 0; - // Connection timeout - this._connectTimeoutMS = this.socketOptions.connectTimeoutMS - ? this.socketOptions.connectTimeoutMS - : 1000; - - // Add options to servers - for(var i = 0; i < this.servers.length; i++) { - var server = this.servers[i]; - server._callBackStore = this._callBackStore; - server.auto_reconnect = false; - // Default empty socket options object - var socketOptions = {host: server.host, port: server.port}; - // If a socket option object exists clone it - if(this.socketOptions != null) { - var keys = Object.keys(this.socketOptions); - for(var k = 0; k < keys.length;k++) socketOptions[keys[i]] = this.socketOptions[keys[i]]; - } - - // Set socket options - server.socketOptions = socketOptions; - } - - // Allow setting the socketTimeoutMS on all connections - // to work around issues such as secondaries blocking due to compaction - utils.setSocketTimeoutProperty(this, this.socketOptions); -} - -/** - * @ignore - */ -inherits(Mongos, Base); - -/** - * @ignore - */ -Mongos.prototype.isMongos = function() { - return true; -} - -/** - * @ignore - */ -Mongos.prototype.connect = function(db, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - - // Keep reference to parent - this.db = db; - // Set server state to connecting - this._serverState = 'connecting'; - // Number of total servers that need to initialized (known servers) - this._numberOfServersLeftToInitialize = this.servers.length; - // Connect handler - var connectHandler = function(_server) { - return function(err, result) { - self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1; - - // Add the server to the list of servers that are up - if(!err) { - self.upServers[format("%s:%s", _server.host, _server.port)] = _server; - } - - // We are done connecting - if(self._numberOfServersLeftToInitialize == 0) { - // Start ha function if it exists - if(self.haEnabled) { - // Setup the ha process - if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId); - self._replicasetTimeoutId = setInterval(self.mongosCheckFunction, self.mongosStatusCheckInterval); - } - - // Set the mongos to connected - self._serverState = "connected"; - - // Emit the open event - if(self.emitOpen) - self._emitAcrossAllDbInstances(self, null, "open", null, null, null); - - self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null); - // Callback - callback(null, self.db); - } - } - }; - - // Error handler - var errorOrCloseHandler = function(_server) { - return function(err, result) { - // Emit left event, signaling mongos left the ha - self.emit('left', 'mongos', _server); - // Execute all the callbacks with errors - self.__executeAllCallbacksWithError(err); - // Check if we have the server - var found = false; - - // Get the server name - var server_name = format("%s:%s", _server.host, _server.port); - // Add the downed server - self.downServers[server_name] = _server; - // Remove the current server from the list - delete self.upServers[server_name]; - - // Emit close across all the attached db instances - if(Object.keys(self.upServers).length == 0) { - self._emitAcrossAllDbInstances(self, null, "close", new Error("mongos disconnected, no valid proxies contactable over tcp"), null, null); - } - } - } - - // Mongo function - this.mongosCheckFunction = function() { - // Set as not waiting for check event - self._haInProgress = true; - - // Servers down - var numberOfServersLeft = Object.keys(self.downServers).length; - - // Check downed servers - if(numberOfServersLeft > 0) { - for(var name in self.downServers) { - // Pop a downed server - var downServer = self.downServers[name]; - // Set up the connection options for a Mongos - var options = { - auto_reconnect: false, - returnIsMasterResults: true, - slaveOk: true, - poolSize: downServer.poolSize, - socketOptions: { - connectTimeoutMS: self._connectTimeoutMS, - socketTimeoutMS: self._socketTimeoutMS - } - } - - // Create a new server object - var newServer = new Server(downServer.host, downServer.port, options); - // Setup the connection function - var connectFunction = function(_db, _server, _options, _callback) { - return function() { - // Attempt to connect - _server.connect(_db, _options, function(err, result) { - numberOfServersLeft = numberOfServersLeft - 1; - - if(err) { - return _callback(err, _server); - } else { - // Set the new server settings - _server._callBackStore = self._callBackStore; - - // Add server event handlers - _server.on("close", errorOrCloseHandler(_server)); - _server.on("timeout", errorOrCloseHandler(_server)); - _server.on("error", errorOrCloseHandler(_server)); - - // Get a read connection - var _connection = _server.checkoutReader(); - // Get the start time - var startTime = new Date().getTime(); - - // Execute ping command to mark each server with the expected times - self.db.command({ping:1} - , {failFast:true, connection:_connection}, function(err, result) { - // Get the start time - var endTime = new Date().getTime(); - // Mark the server with the ping time - _server.runtimeStats['pingMs'] = endTime - startTime; - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - // Callback - return _callback(null, _server); - }); - } - }); - } - } - - // Attempt to connect to the database - connectFunction(self.db, newServer, options, function(err, _server) { - // If we have an error - if(err) { - self.downServers[format("%s:%s", _server.host, _server.port)] = _server; - } - - // Connection function - var connectionFunction = function(_auth, _connection, _callback) { - var pending = _auth.length(); - - for(var j = 0; j < pending; j++) { - // Get the auth object - var _auth = _auth.get(j); - // Unpack the parameter - var username = _auth.username; - var password = _auth.password; - var options = { - authMechanism: _auth.authMechanism - , authSource: _auth.authdb - , connection: _connection - }; - - // If we have changed the service name - if(_auth.gssapiServiceName) - options.gssapiServiceName = _auth.gssapiServiceName; - - // Hold any error - var _error = null; - // Authenticate against the credentials - self.db.authenticate(username, password, options, function(err, result) { - _error = err != null ? err : _error; - // Adjust the pending authentication - pending = pending - 1; - // Finished up - if(pending == 0) _callback(_error ? _error : null, _error ? false : true); - }); - } - } - - // Run auths against the connections - if(self.auth.length() > 0) { - var connections = _server.allRawConnections(); - var pendingAuthConn = connections.length; - - // No connections we are done - if(connections.length == 0) { - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - } - } - - // Final error object - var finalError = null; - // Go over all the connections - for(var j = 0; j < connections.length; j++) { - - // Execute against all the connections - connectionFunction(self.auth, connections[j], function(err, result) { - // Pending authentication - pendingAuthConn = pendingAuthConn - 1 ; - - // Save error if any - finalError = err ? err : finalError; - - // If we are done let's finish up - if(pendingAuthConn == 0) { - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - } - - if(!err) { - add_server(self, _server); - } - - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - } - }); - } - } else { - if(!err) { - add_server(self, _server); - } - - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - } - } - })(); - } - } else { - self._haInProgress = false; - } - } - - // Connect all the server instances - for(var i = 0; i < this.servers.length; i++) { - // Get the connection - var server = this.servers[i]; - server.mongosInstance = this; - // Add server event handlers - server.on("close", errorOrCloseHandler(server)); - server.on("timeout", errorOrCloseHandler(server)); - server.on("error", errorOrCloseHandler(server)); - - // Configuration - var options = { - slaveOk: true, - poolSize: server.poolSize, - socketOptions: { connectTimeoutMS: self._connectTimeoutMS }, - returnIsMasterResults: true - } - - // Connect the instance - server.connect(self.db, options, connectHandler(server)); - } -} - -/** - * @ignore - * Add a server to the list of up servers and sort them by ping time - */ -var add_server = function(self, _server) { - // Emit a new server joined - self.emit('joined', "mongos", null, _server); - // Get the server url - var server_key = format("%s:%s", _server.host, _server.port); - // Push to list of valid server - self.upServers[server_key] = _server; - // Remove the server from the list of downed servers - delete self.downServers[server_key]; - - // Sort the keys by ping time - var keys = Object.keys(self.upServers); - var _upServersSorted = {}; - var _upServers = [] - - // Get all the servers - for(var name in self.upServers) { - _upServers.push(self.upServers[name]); - } - - // Sort all the server - _upServers.sort(function(a, b) { - return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs']; - }); - - // Rebuild the upServer - for(var i = 0; i < _upServers.length; i++) { - _upServersSorted[format("%s:%s", _upServers[i].host, _upServers[i].port)] = _upServers[i]; - } - - // Set the up servers - self.upServers = _upServersSorted; -} - -/** - * @ignore - * Just return the currently picked active connection - */ -Mongos.prototype.allServerInstances = function() { - return this.servers; -} - -/** - * Always ourselves - * @ignore - */ -Mongos.prototype.setReadPreference = function() {} - -/** - * @ignore - */ -Mongos.prototype.allRawConnections = function() { - // Neeed to build a complete list of all raw connections, start with master server - var allConnections = []; - // Get all connected connections - for(var name in this.upServers) { - allConnections = allConnections.concat(this.upServers[name].allRawConnections()); - } - // Return all the conections - return allConnections; -} - -/** - * @ignore - */ -Mongos.prototype.isConnected = function() { - return Object.keys(this.upServers).length > 0; -} - -/** - * @ignore - */ -Mongos.prototype.isAutoReconnect = function() { - return true; -} - -/** - * @ignore - */ -Mongos.prototype.canWrite = Mongos.prototype.isConnected; - -/** - * @ignore - */ -Mongos.prototype.canRead = Mongos.prototype.isConnected; - -/** - * @ignore - */ -Mongos.prototype.isDestroyed = function() { - return this._serverState == 'destroyed'; -} - -/** - * @ignore - */ -Mongos.prototype.checkoutWriter = function() { - // Checkout a writer - var keys = Object.keys(this.upServers); - // console.dir("============================ checkoutWriter :: " + keys.length) - if(keys.length == 0) return null; - // console.log("=============== checkoutWriter :: " + this.upServers[keys[0]].checkoutWriter().socketOptions.port) - return this.upServers[keys[0]].checkoutWriter(); -} - -/** - * @ignore - */ -Mongos.prototype.checkoutReader = function(read) { - // console.log("=============== checkoutReader :: read :: " + read); - // If read is set to null default to primary - read = read || 'primary' - // If we have a read preference object unpack it - if(read != null && typeof read == 'object' && read['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!read.isValid()) throw new Error("Illegal readPreference mode specified, " + read.mode); - } else if(!ReadPreference.isValid(read)) { - throw new Error("Illegal readPreference mode specified, " + read); - } - - // Checkout a writer - var keys = Object.keys(this.upServers); - if(keys.length == 0) return null; - // console.log("=============== checkoutReader :: " + this.upServers[keys[0]].checkoutWriter().socketOptions.port) - // console.dir(this._commandsStore.commands) - return this.upServers[keys[0]].checkoutWriter(); -} - -/** - * @ignore - */ -Mongos.prototype.close = function(callback) { - var self = this; - // Set server status as disconnected - this._serverState = 'destroyed'; - // Number of connections to close - var numberOfConnectionsToClose = self.servers.length; - // If we have a ha process running kill it - if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId); - self._replicasetTimeoutId = null; - - // Emit close event - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }); - - // Flush out any remaining call handlers - self._flushAllCallHandlers(utils.toError("Connection Closed By Application")); - - // Close all the up servers - for(var name in this.upServers) { - this.upServers[name].close(function(err, result) { - numberOfConnectionsToClose = numberOfConnectionsToClose - 1; - - // Callback if we have one defined - if(numberOfConnectionsToClose == 0 && typeof callback == 'function') { - callback(null); - } - }); - } -} - -/** - * @ignore - * Return the used state - */ -Mongos.prototype._isUsed = function() { - return this._used; -} - -exports.Mongos = Mongos; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/connection/read_preference.js b/node_modules/mongodb/lib/mongodb/connection/read_preference.js deleted file mode 100644 index 6845171a3..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/read_preference.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * A class representation of the Read Preference. - * - * Read Preferences - * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). - * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. - * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. - * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. - * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. - * - * @class Represents a Read Preference. - * @param {String} the read preference type - * @param {Object} tags - * @return {ReadPreference} - */ -var ReadPreference = function(mode, tags) { - if(!(this instanceof ReadPreference)) - return new ReadPreference(mode, tags); - this._type = 'ReadPreference'; - this.mode = mode; - this.tags = tags; -} - -/** - * @ignore - */ -ReadPreference.isValid = function(_mode) { - return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED - || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED - || _mode == ReadPreference.NEAREST - || _mode == true || _mode == false); -} - -/** - * @ignore - */ -ReadPreference.prototype.isValid = function(mode) { - var _mode = typeof mode == 'string' ? mode : this.mode; - return ReadPreference.isValid(_mode); -} - -/** - * @ignore - */ -ReadPreference.prototype.toObject = function() { - var object = {mode:this.mode}; - - if(this.tags != null) { - object['tags'] = this.tags; - } - - return object; -} - -/** - * @ignore - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest' - -/** - * @ignore - */ -exports.ReadPreference = ReadPreference; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js deleted file mode 100644 index e3e8f3214..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js +++ /dev/null @@ -1,414 +0,0 @@ -var DbCommand = require('../../commands/db_command').DbCommand - , format = require('util').format; - -var HighAvailabilityProcess = function(replset, options) { - this.replset = replset; - this.options = options; - this.server = null; - this.state = HighAvailabilityProcess.INIT; - this.selectedIndex = 0; -} - -HighAvailabilityProcess.INIT = 'init'; -HighAvailabilityProcess.RUNNING = 'running'; -HighAvailabilityProcess.STOPPED = 'stopped'; - -HighAvailabilityProcess.prototype.start = function() { - var self = this; - if(this.replset._state - && Object.keys(this.replset._state.addresses).length == 0) { - if(this.server) this.server.close(); - this.state = HighAvailabilityProcess.STOPPED; - return; - } - - if(this.server) this.server.close(); - // Start the running - this._haProcessInProcess = false; - this.state = HighAvailabilityProcess.RUNNING; - - // Get all possible reader servers - var candidate_servers = this.replset._state.getAllReadServers(); - if(candidate_servers.length == 0) { - return; - } - - // Select a candidate server for the connection - var server = candidate_servers[this.selectedIndex % candidate_servers.length]; - this.selectedIndex = this.selectedIndex + 1; - - // Unpack connection options - var connectTimeoutMS = self.options.connectTimeoutMS || 10000; - var socketTimeoutMS = self.options.socketTimeoutMS || 30000; - - // Just ensure we don't have a full cycle dependency - var Db = require('../../db').Db - var Server = require('../server').Server; - - // Set up a new server instance - var newServer = new Server(server.host, server.port, { - auto_reconnect: false - , returnIsMasterResults: true - , poolSize: 1 - , socketOptions: { - connectTimeoutMS: connectTimeoutMS, - socketTimeoutMS: socketTimeoutMS, - keepAlive: 100 - } - , ssl: this.options.ssl - , sslValidate: this.options.sslValidate - , sslCA: this.options.sslCA - , sslCert: this.options.sslCert - , sslKey: this.options.sslKey - , sslPass: this.options.sslPass - }); - - // Create new dummy db for app - self.db = new Db('local', newServer, {w:1}); - - // Set up the event listeners - newServer.once("error", _handle(this, newServer)); - newServer.once("close", _handle(this, newServer)); - newServer.once("timeout", _handle(this, newServer)); - newServer.name = format("%s:%s", server.host, server.port); - - // Let's attempt a connection over here - newServer.connect(self.db, function(err, result, _server) { - if(self.state == HighAvailabilityProcess.STOPPED) { - _server.close(); - } - - if(err) { - // Close the server - _server.close(); - // Check if we can even do HA (is there anything running) - if(Object.keys(self.replset._state.addresses).length == 0) { - return; - } - - // Let's boot the ha timeout settings - setTimeout(function() { - self.start(); - }, self.options.haInterval); - } else { - self.server = _server; - // Let's boot the ha timeout settings - setTimeout(_timeoutHandle(self), self.options.haInterval); - } - }); -} - -HighAvailabilityProcess.prototype.stop = function() { - this.state = HighAvailabilityProcess.STOPPED; - if(this.server) this.server.close(); -} - -var _timeoutHandle = function(self) { - return function() { - if(self.state == HighAvailabilityProcess.STOPPED) { - // Stop all server instances - for(var name in self.replset._state.addresses) { - self.replset._state.addresses[name].close(); - delete self.replset._state.addresses[name]; - } - - // Finished pinging - return; - } - - // If the server is connected - if(self.server.isConnected() && !self._haProcessInProcess) { - // Start HA process - self._haProcessInProcess = true; - // Execute is master command - self.db._executeQueryCommand(DbCommand.createIsMasterCommand(self.db), - {failFast:true, connection: self.server.checkoutReader()} - , function(err, res) { - if(err) { - self.server.close(); - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // Master document - var master = res.documents[0]; - var hosts = master.hosts || []; - var reconnect_servers = []; - var state = self.replset._state; - - // We are in recovery mode, let's remove the current server - if(!master.ismaster - && !master.secondary - && state.addresses[master.me]) { - self.server.close(); - state.addresses[master.me].close(); - delete state.secondaries[master.me]; - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // For all the hosts let's check that we have connections - for(var i = 0; i < hosts.length; i++) { - var host = hosts[i]; - // Check if we need to reconnect to a server - if(state.addresses[host] == null) { - reconnect_servers.push(host); - } else if(state.addresses[host] && !state.addresses[host].isConnected()) { - state.addresses[host].close(); - delete state.secondaries[host]; - reconnect_servers.push(host); - } - - if((master.primary && state.master == null) - || (master.primary && state.master.name != master.primary)) { - - // Locate the primary and set it - if(state.addresses[master.primary]) { - if(state.master) state.master.close(); - delete state.secondaries[master.primary]; - state.master = state.addresses[master.primary]; - } - - // Set up the changes - if(state.master != null && state.master.isMasterDoc != null) { - state.master.isMasterDoc.ismaster = true; - state.master.isMasterDoc.secondary = false; - } else if(state.master != null) { - state.master.isMasterDoc = master; - state.master.isMasterDoc.ismaster = true; - state.master.isMasterDoc.secondary = false; - } - - // Execute any waiting commands (queries or writes) - self.replset._commandsStore.execute_queries(); - self.replset._commandsStore.execute_writes(); - } - } - - // Let's reconnect to any server needed - if(reconnect_servers.length > 0) { - _reconnect_servers(self, reconnect_servers); - } else { - self._haProcessInProcess = false - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - }); - } else if(!self.server.isConnected()) { - setTimeout(function() { - return self.start(); - }, self.options.haInterval); - } else { - setTimeout(_timeoutHandle(self), self.options.haInterval); - } - } -} - -var _reconnect_servers = function(self, reconnect_servers) { - if(reconnect_servers.length == 0) { - self._haProcessInProcess = false - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // Unpack connection options - var connectTimeoutMS = self.options.connectTimeoutMS || 10000; - var socketTimeoutMS = self.options.socketTimeoutMS || 0; - - // Server class - var Db = require('../../db').Db - var Server = require('../server').Server; - // Get the host - var host = reconnect_servers.shift(); - // Split it up - var _host = host.split(":")[0]; - var _port = parseInt(host.split(":")[1], 10); - - // Set up a new server instance - var newServer = new Server(_host, _port, { - auto_reconnect: false - , returnIsMasterResults: true - , poolSize: self.options.poolSize - , socketOptions: { - connectTimeoutMS: connectTimeoutMS, - socketTimeoutMS: socketTimeoutMS - } - , ssl: self.options.ssl - , sslValidate: self.options.sslValidate - , sslCA: self.options.sslCA - , sslCert: self.options.sslCert - , sslKey: self.options.sslKey - , sslPass: self.options.sslPass - }); - - // Create new dummy db for app - var db = new Db('local', newServer, {w:1}); - var state = self.replset._state; - - // Set up the event listeners - newServer.once("error", _repl_set_handler("error", self.replset, newServer)); - newServer.once("close", _repl_set_handler("close", self.replset, newServer)); - newServer.once("timeout", _repl_set_handler("timeout", self.replset, newServer)); - - // Set shared state - newServer.name = host; - newServer._callBackStore = self.replset._callBackStore; - newServer.replicasetInstance = self.replset; - newServer.enableRecordQueryStats(self.replset.recordQueryStats); - - // Let's attempt a connection over here - newServer.connect(db, function(err, result, _server) { - if(self.state == HighAvailabilityProcess.STOPPED) { - _server.close(); - } - - // If we connected let's check what kind of server we have - if(!err) { - _apply_auths(self, db, _server, function(err, result) { - if(err) { - _server.close(); - // Process the next server - return setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - } - var doc = _server.isMasterDoc; - // Fire error on any unknown callbacks for this server - self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err); - - if(doc.ismaster) { - // Emit primary added - self.replset.emit('joined', "primary", doc, _server); - - // If it was a secondary remove it - if(state.secondaries[doc.me]) { - delete state.secondaries[doc.me]; - } - - // Override any server in list of addresses - state.addresses[doc.me] = _server; - // Set server as master - state.master = _server; - // Execute any waiting writes - self.replset._commandsStore.execute_writes(); - } else if(doc.secondary) { - // Emit secondary added - self.replset.emit('joined', "secondary", doc, _server); - // Add the secondary to the state - state.secondaries[doc.me] = _server; - // Override any server in list of addresses - state.addresses[doc.me] = _server; - // Execute any waiting reads - self.replset._commandsStore.execute_queries(); - } else { - _server.close(); - } - - // Set any tags on the instance server - _server.name = doc.me; - _server.tags = doc.tags; - // Process the next server - setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - }); - } else { - _server.close(); - self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err); - - setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - } - }); -} - -var _apply_auths = function(self, _db, _server, _callback) { - if(self.replset.auth.length() == 0) return _callback(null); - // Apply any authentication needed - if(self.replset.auth.length() > 0) { - var pending = self.replset.auth.length(); - var connections = _server.allRawConnections(); - var pendingAuthConn = connections.length; - - // Connection function - var connectionFunction = function(_auth, _connection, __callback) { - var pending = _auth.length(); - - for(var j = 0; j < pending; j++) { - // Get the auth object - var _auth = _auth.get(j); - // Unpack the parameter - var username = _auth.username; - var password = _auth.password; - var options = { - authMechanism: _auth.authMechanism - , authSource: _auth.authdb - , connection: _connection - }; - - // If we have changed the service name - if(_auth.gssapiServiceName) - options.gssapiServiceName = _auth.gssapiServiceName; - - // Hold any error - var _error = null; - - // Authenticate against the credentials - _db.authenticate(username, password, options, function(err, result) { - _error = err != null ? err : _error; - // Adjust the pending authentication - pending = pending - 1; - // Finished up - if(pending == 0) __callback(_error ? _error : null, _error ? false : true); - }); - } - } - - // Final error object - var finalError = null; - // Iterate over all the connections - for(var i = 0; i < connections.length; i++) { - connectionFunction(self.replset.auth, connections[i], function(err, result) { - // Pending authentication - pendingAuthConn = pendingAuthConn - 1 ; - - // Save error if any - finalError = err ? err : finalError; - - // If we are done let's finish up - if(pendingAuthConn == 0) { - _callback(null); - } - }); - } - } -} - -var _handle = function(self, server) { - return function(err) { - server.close(); - } -} - -var _repl_set_handler = function(event, self, server) { - var ReplSet = require('./repl_set').ReplSet; - - return function(err, doc) { - server.close(); - - // The event happened to a primary - // Remove it from play - if(self._state.isPrimary(server)) { - self._state.master == null; - self._serverState = ReplSet.REPLSET_READ_ONLY; - } else if(self._state.isSecondary(server)) { - delete self._state.secondaries[server.name]; - } - - // Unpack variables - var host = server.socketOptions.host; - var port = server.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } -} - -exports.HighAvailabilityProcess = HighAvailabilityProcess; diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js deleted file mode 100644 index a5658e3b0..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js +++ /dev/null @@ -1,126 +0,0 @@ -var PingStrategy = require('./strategies/ping_strategy').PingStrategy - , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy - , ReadPreference = require('../read_preference').ReadPreference; - -var Options = function(options) { - options = options || {}; - this._options = options; - this.ha = options.ha || true; - this.haInterval = options.haInterval || 2000; - this.reconnectWait = options.reconnectWait || 1000; - this.retries = options.retries || 30; - this.rs_name = options.rs_name; - this.socketOptions = options.socketOptions || {}; - this.readPreference = options.readPreference; - this.readSecondary = options.read_secondary; - this.poolSize = options.poolSize == null ? 5 : options.poolSize; - this.strategy = options.strategy || 'ping'; - this.secondaryAcceptableLatencyMS = options.secondaryAcceptableLatencyMS || 15; - this.connectArbiter = options.connectArbiter || false; - this.connectWithNoPrimary = options.connectWithNoPrimary || false; - this.logger = options.logger; - this.ssl = options.ssl || false; - this.sslValidate = options.sslValidate || false; - this.sslCA = options.sslCA; - this.sslCert = options.sslCert; - this.sslKey = options.sslKey; - this.sslPass = options.sslPass; - this.emitOpen = options.emitOpen || true; -} - -Options.prototype.init = function() { - if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) { - throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate"); - } - - // Make sure strategy is one of the two allowed - if(this.strategy != null && (this.strategy != 'ping' && this.strategy != 'statistical' && this.strategy != 'none')) - throw new Error("Only ping or statistical strategies allowed"); - - if(this.strategy == null) this.strategy = 'ping'; - - // Set logger if strategy exists - if(this.strategyInstance) this.strategyInstance.logger = this.logger; - - // Unpack read Preference - var readPreference = this.readPreference; - // Validate correctness of Read preferences - if(readPreference != null) { - if(readPreference != ReadPreference.PRIMARY && readPreference != ReadPreference.PRIMARY_PREFERRED - && readPreference != ReadPreference.SECONDARY && readPreference != ReadPreference.SECONDARY_PREFERRED - && readPreference != ReadPreference.NEAREST && typeof readPreference != 'object' && readPreference['_type'] != 'ReadPreference') { - throw new Error("Illegal readPreference mode specified, " + readPreference); - } - - this.readPreference = readPreference; - } else { - this.readPreference = null; - } - - // Ensure read_secondary is set correctly - if(this.readSecondary != null) - this.readSecondary = this.readPreference == ReadPreference.PRIMARY - || this.readPreference == false - || this.readPreference == null ? false : true; - - // Ensure correct slave set - if(this.readSecondary) this.slaveOk = true; - - // Set up logger if any set - this.logger = this.logger != null - && (typeof this.logger.debug == 'function') - && (typeof this.logger.error == 'function') - && (typeof this.logger.debug == 'function') - ? this.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Connection timeout - this.connectTimeoutMS = this.socketOptions.connectTimeoutMS - ? this.socketOptions.connectTimeoutMS - : 1000; - - // Socket connection timeout - this.socketTimeoutMS = this.socketOptions.socketTimeoutMS - ? this.socketOptions.socketTimeoutMS - : 30000; -} - -Options.prototype.decorateAndClean = function(servers, callBackStore) { - var self = this; - - // var de duplicate list - var uniqueServers = {}; - // De-duplicate any servers in the seed list - for(var i = 0; i < servers.length; i++) { - var server = servers[i]; - // If server does not exist set it - if(uniqueServers[server.host + ":" + server.port] == null) { - uniqueServers[server.host + ":" + server.port] = server; - } - } - - // Let's set the deduplicated list of servers - var finalServers = []; - // Add the servers - for(var key in uniqueServers) { - finalServers.push(uniqueServers[key]); - } - - finalServers.forEach(function(server) { - // Ensure no server has reconnect on - server.options.auto_reconnect = false; - // Set up ssl options - server.ssl = self.ssl; - server.sslValidate = self.sslValidate; - server.sslCA = self.sslCA; - server.sslCert = self.sslCert; - server.sslKey = self.sslKey; - server.sslPass = self.sslPass; - server.poolSize = self.poolSize; - // Set callback store - server._callBackStore = callBackStore; - }); - - return finalServers; -} - -exports.Options = Options; diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js deleted file mode 100644 index c2d1df4ff..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js +++ /dev/null @@ -1,811 +0,0 @@ -var ReadPreference = require('../read_preference').ReadPreference - , DbCommand = require('../../commands/db_command').DbCommand - , inherits = require('util').inherits - , format = require('util').format - , timers = require('timers') - , Server = require('../server').Server - , utils = require('../../utils') - , PingStrategy = require('./strategies/ping_strategy').PingStrategy - , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy - , Options = require('./options').Options - , ReplSetState = require('./repl_set_state').ReplSetState - , HighAvailabilityProcess = require('./ha').HighAvailabilityProcess - , Base = require('../base').Base; - -var STATE_STARTING_PHASE_1 = 0; -var STATE_PRIMARY = 1; -var STATE_SECONDARY = 2; -var STATE_RECOVERING = 3; -var STATE_FATAL_ERROR = 4; -var STATE_STARTING_PHASE_2 = 5; -var STATE_UNKNOWN = 6; -var STATE_ARBITER = 7; -var STATE_DOWN = 8; -var STATE_ROLLBACK = 9; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../../utils').processor(); - -/** - * ReplSet constructor provides replicaset functionality - * - * Options - * - **ha** {Boolean, default:true}, turn on high availability. - * - **haInterval** {Number, default:2000}, time between each replicaset status check. - * - **reconnectWait** {Number, default:1000}, time to wait in miliseconds before attempting reconnect. - * - **retries** {Number, default:30}, number of times to attempt a replicaset reconnect. - * - **rs_name** {String}, the name of the replicaset to connect to. - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strategy** {String, default:'ping'}, selection strategy for reads choose between (ping, statistical and none, default is ping) - * - **secondaryAcceptableLatencyMS** {Number, default:15}, sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * - **connectWithNoPrimary** {Boolean, default:false}, sets if the driver should connect even if no primary is available - * - **connectArbiter** {Boolean, default:false}, sets if the driver should connect to arbiters or not. - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **poolSize** {Number, default:5}, number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support) - * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * - * @class Represents a - Replicaset Configuration - * @param {Array} list of server objects participating in the replicaset. - * @param {Object} [options] additional options for the replicaset connection. - */ -var ReplSet = exports.ReplSet = function(servers, options) { - // Set up basic - if(!(this instanceof ReplSet)) - return new ReplSet(servers, options); - - // Set up event emitter - Base.call(this); - - // Ensure we have a list of servers - if(!Array.isArray(servers)) throw Error("The parameter must be an array of servers and contain at least one server"); - // Ensure no Mongos's - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) throw new Error("list of servers must be of type Server"); - } - - // Save the options - this.options = new Options(options); - // Ensure basic validation of options - this.options.init(); - - // Server state - this._serverState = ReplSet.REPLSET_DISCONNECTED; - // Add high availability process - this._haProcess = new HighAvailabilityProcess(this, this.options); - - // Let's iterate over all the provided server objects and decorate them - this.servers = this.options.decorateAndClean(servers, this._callBackStore); - // Throw error if no seed servers - if(this.servers.length == 0) throw new Error("No valid seed servers in the array"); - - // Let's set up our strategy object for picking secondaries - if(this.options.strategy == 'ping') { - // Create a new instance - this.strategyInstance = new PingStrategy(this, this.options.secondaryAcceptableLatencyMS); - } else if(this.options.strategy == 'statistical') { - // Set strategy as statistical - this.strategyInstance = new StatisticsStrategy(this); - // Add enable query information - this.enableRecordQueryStats(true); - } - - this.emitOpen = this.options.emitOpen || true; - // Set up a clean state - this._state = new ReplSetState(this); - // Current round robin selected server - this._currentServerChoice = 0; - // Ensure up the server callbacks - for(var i = 0; i < this.servers.length; i++) { - this.servers[i]._callBackStore = this._callBackStore; - this.servers[i].name = format("%s:%s", this.servers[i].host, this.servers[i].port) - this.servers[i].replicasetInstance = this; - this.servers[i].options.auto_reconnect = false; - this.servers[i].inheritReplSetOptionsFrom(this); - } - - // Allow setting the socketTimeoutMS on all connections - // to work around issues such as secondaries blocking due to compaction - utils.setSocketTimeoutProperty(this, this.options.socketOptions); -} - -/** - * @ignore - */ -inherits(ReplSet, Base); - -// Replicaset states -ReplSet.REPLSET_CONNECTING = 'connecting'; -ReplSet.REPLSET_DISCONNECTED = 'disconnected'; -ReplSet.REPLSET_CONNECTED = 'connected'; -ReplSet.REPLSET_RECONNECTING = 'reconnecting'; -ReplSet.REPLSET_DESTROYED = 'destroyed'; -ReplSet.REPLSET_READ_ONLY = 'readonly'; - -ReplSet.prototype.isAutoReconnect = function() { - return true; -} - -ReplSet.prototype.canWrite = function() { - return this._state.master && this._state.master.isConnected(); -} - -ReplSet.prototype.canRead = function(read) { - if((read == ReadPreference.PRIMARY - || read == null || read == false) && (this._state.master == null || !this._state.master.isConnected())) return false; - return Object.keys(this._state.secondaries).length > 0; -} - -/** - * @ignore - */ -ReplSet.prototype.enableRecordQueryStats = function(enable) { - // Set the global enable record query stats - this.recordQueryStats = enable; - - // Enable all the servers - for(var i = 0; i < this.servers.length; i++) { - this.servers[i].enableRecordQueryStats(enable); - } -} - -/** - * @ignore - */ -ReplSet.prototype.setReadPreference = function(preference) { - this.options.readPreference = preference; -} - -ReplSet.prototype.connect = function(parent, options, callback) { - if(this._serverState != ReplSet.REPLSET_DISCONNECTED) - return callback(new Error("in process of connection")); - - // If no callback throw - if(!(typeof callback == 'function')) - throw new Error("cannot call ReplSet.prototype.connect with no callback function"); - - var self = this; - // Save db reference - this.options.db = parent; - // Set replicaset as connecting - this._serverState = ReplSet.REPLSET_CONNECTING - // Copy all the servers to our list of seeds - var candidateServers = this.servers.slice(0); - // Pop the first server - var server = candidateServers.pop(); - server.name = format("%s:%s", server.host, server.port); - // Set up the options - var opts = { - returnIsMasterResults: true, - eventReceiver: server - } - - // Register some event listeners - this.once("fullsetup", function(err, db, replset) { - // Set state to connected - self._serverState = ReplSet.REPLSET_CONNECTED; - // Stop any process running - if(self._haProcess) self._haProcess.stop(); - // Start the HA process - self._haProcess.start(); - - // Emit fullsetup - processor(function() { - if(self.emitOpen) - self._emitAcrossAllDbInstances(self, null, "open", null, null, null); - - self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null); - }); - - // If we have a strategy defined start it - if(self.strategyInstance) { - self.strategyInstance.start(); - } - - // Finishing up the call - callback(err, db, replset); - }); - - // Errors - this.once("connectionError", function(err, result) { - callback(err, result); - }); - - // Attempt to connect to the server - server.connect(this.options.db, opts, _connectHandler(this, candidateServers, server)); -} - -ReplSet.prototype.close = function(callback) { - var self = this; - // Set as destroyed - this._serverState = ReplSet.REPLSET_DESTROYED; - // Stop the ha - this._haProcess.stop(); - - // If we have a strategy stop it - if(this.strategyInstance) { - this.strategyInstance.stop(); - } - - // Kill all servers available - for(var name in this._state.addresses) { - this._state.addresses[name].close(); - } - - // Clean out the state - this._state = new ReplSetState(this); - - // Emit close event - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }); - - // Flush out any remaining call handlers - self._flushAllCallHandlers(utils.toError("Connection Closed By Application")); - - // Callback - if(typeof callback == 'function') - return callback(null, null); -} - -/** - * Creates a new server for the `replset` based on `host`. - * - * @param {String} host - host:port pair (localhost:27017) - * @param {ReplSet} replset - the ReplSet instance - * @return {Server} - * @ignore - */ -var createServer = function(self, host, options) { - // copy existing socket options to new server - var socketOptions = {} - if(options.socketOptions) { - var keys = Object.keys(options.socketOptions); - for(var k = 0; k < keys.length; k++) { - socketOptions[keys[k]] = options.socketOptions[keys[k]]; - } - } - - var parts = host.split(/:/); - if(1 === parts.length) { - parts[1] = Connection.DEFAULT_PORT; - } - - socketOptions.host = parts[0]; - socketOptions.port = parseInt(parts[1], 10); - - var serverOptions = { - readPreference: options.readPreference, - socketOptions: socketOptions, - poolSize: options.poolSize, - logger: options.logger, - auto_reconnect: false, - ssl: options.ssl, - sslValidate: options.sslValidate, - sslCA: options.sslCA, - sslCert: options.sslCert, - sslKey: options.sslKey, - sslPass: options.sslPass - } - - var server = new Server(socketOptions.host, socketOptions.port, serverOptions); - // Set up shared state - server._callBackStore = self._callBackStore; - server.replicasetInstance = self; - server.enableRecordQueryStats(self.recordQueryStats); - // Set up event handlers - server.on("close", _handler("close", self, server)); - server.on("error", _handler("error", self, server)); - server.on("timeout", _handler("timeout", self, server)); - return server; -} - -var _handler = function(event, self, server) { - return function(err, doc) { - // The event happened to a primary - // Remove it from play - if(self._state.isPrimary(server)) { - // Emit that the primary left the replicaset - self.emit('left', 'primary', server); - // Get the current master - var current_master = self._state.master; - self._state.master = null; - self._serverState = ReplSet.REPLSET_READ_ONLY; - - if(current_master != null) { - // Unpack variables - var host = current_master.socketOptions.host; - var port = current_master.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } - } else if(self._state.isSecondary(server)) { - // Emit that a secondary left the replicaset - self.emit('left', 'secondary', server); - // Delete from the list - delete self._state.secondaries[server.name]; - } - - // If there is no more connections left and the setting is not destroyed - // set to disconnected - if(Object.keys(self._state.addresses).length == 0 - && self._serverState != ReplSet.REPLSET_DESTROYED) { - self._serverState = ReplSet.REPLSET_DISCONNECTED; - - // Emit close across all the attached db instances - self._dbStore.emit("close", new Error("replicaset disconnected, no valid servers contactable over tcp"), null, true); - } - - // Unpack variables - var host = server.socketOptions.host; - var port = server.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } -} - -var locateNewServers = function(self, state, candidateServers, ismaster) { - // Retrieve the host - var hosts = ismaster.hosts; - // In candidate servers - var inCandidateServers = function(name, candidateServers) { - for(var i = 0; i < candidateServers.length; i++) { - if(candidateServers[i].name == name) return true; - } - - return false; - } - - // New servers - var newServers = []; - if(Array.isArray(hosts)) { - // Let's go over all the hosts - for(var i = 0; i < hosts.length; i++) { - if(!state.contains(hosts[i]) - && !inCandidateServers(hosts[i], candidateServers)) { - newServers.push(createServer(self, hosts[i], self.options)); - } - } - } - - // Return list of possible new servers - return newServers; -} - -var _connectHandler = function(self, candidateServers, instanceServer) { - return function(err, doc) { - // If we have an error add to the list - if(err) { - self._state.errors[instanceServer.name] = instanceServer; - } else { - delete self._state.errors[instanceServer.name]; - } - - if(!err) { - var ismaster = doc.documents[0] - - // Error the server if - if(!ismaster.ismaster - && !ismaster.secondary) { - self._state.errors[instanceServer.name] = instanceServer; - } - } - - - // No error let's analyse the ismaster command - if(!err && self._state.errors[instanceServer.name] == null) { - var ismaster = doc.documents[0] - - // If no replicaset name exists set the current one - if(self.options.rs_name == null) { - self.options.rs_name = ismaster.setName; - } - - // If we have a member that is not part of the set let's finish up - if(typeof ismaster.setName == 'string' && ismaster.setName != self.options.rs_name) { - return self.emit("connectionError", new Error("Replicaset name " + ismaster.setName + " does not match specified name " + self.options.rs_name)); - } - - // Add the error handlers - instanceServer.on("close", _handler("close", self, instanceServer)); - instanceServer.on("error", _handler("error", self, instanceServer)); - instanceServer.on("timeout", _handler("timeout", self, instanceServer)); - - // Set any tags on the instance server - instanceServer.name = ismaster.me; - instanceServer.tags = ismaster.tags; - - // Add the server to the list - self._state.addServer(instanceServer, ismaster); - - // Check if we have more servers to add (only check when done with initial set) - if(candidateServers.length == 0) { - // Get additional new servers that are not currently in set - var new_servers = locateNewServers(self, self._state, candidateServers, ismaster); - - // Locate any new servers that have not errored out yet - for(var i = 0; i < new_servers.length; i++) { - if(self._state.errors[new_servers[i].name] == null) { - candidateServers.push(new_servers[i]) - } - } - } - } - - // If the candidate server list is empty and no valid servers - if(candidateServers.length == 0 && - !self._state.hasValidServers()) { - return self.emit("connectionError", new Error("No valid replicaset instance servers found")); - } else if(candidateServers.length == 0) { - if(!self.options.connectWithNoPrimary && (self._state.master == null || !self._state.master.isConnected())) { - return self.emit("connectionError", new Error("No primary found in set")); - } - return self.emit("fullsetup", null, self.options.db, self); - } - - // Let's connect the next server - var nextServer = candidateServers.pop(); - - // Set up the options - var opts = { - returnIsMasterResults: true, - eventReceiver: nextServer - } - - // Attempt to connect to the server - nextServer.connect(self.options.db, opts, _connectHandler(self, candidateServers, nextServer)); - } -} - -ReplSet.prototype.isDestroyed = function() { - return this._serverState == ReplSet.REPLSET_DESTROYED; -} - -ReplSet.prototype.isConnected = function(read) { - var isConnected = false; - - if(read == null || read == ReadPreference.PRIMARY || read == false) - isConnected = this._state.master != null && this._state.master.isConnected(); - - if((read == ReadPreference.PRIMARY_PREFERRED || read == ReadPreference.SECONDARY_PREFERRED || read == ReadPreference.NEAREST) - && ((this._state.master != null && this._state.master.isConnected()) - || (this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0))) { - isConnected = true; - } else if(read == ReadPreference.SECONDARY) { - isConnected = this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0; - } - - // No valid connection return false - return isConnected; -} - -ReplSet.prototype.isMongos = function() { - return false; -} - -ReplSet.prototype.checkoutWriter = function() { - if(this._state.master) return this._state.master.checkoutWriter(); - return new Error("no writer connection available"); -} - -ReplSet.prototype.processIsMaster = function(_server, _ismaster) { - // Server in recovery mode, remove it from available servers - if(!_ismaster.ismaster && !_ismaster.secondary) { - // Locate the actual server - var server = this._state.addresses[_server.name]; - // Close the server, simulating the closing of the connection - // to get right removal semantics - if(server) server.close(); - // Execute any callback errors - _handler(null, this, server)(new Error("server is in recovery mode")); - } -} - -ReplSet.prototype.allRawConnections = function() { - var connections = []; - - for(var name in this._state.addresses) { - connections = connections.concat(this._state.addresses[name].allRawConnections()); - } - - return connections; -} - -/** - * @ignore - */ -ReplSet.prototype.allServerInstances = function() { - var self = this; - // If no state yet return empty - if(!self._state) return []; - // Close all the servers (concatenate entire list of servers first for ease) - var allServers = self._state.master != null ? [self._state.master] : []; - - // Secondary keys - var keys = Object.keys(self._state.secondaries); - // Add all secondaries - for(var i = 0; i < keys.length; i++) { - allServers.push(self._state.secondaries[keys[i]]); - } - - // Return complete list of all servers - return allServers; -} - -/** - * @ignore - */ -ReplSet.prototype.checkoutReader = function(readPreference, tags) { - var connection = null; - - // If we have a read preference object unpack it - if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!readPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + readPreference.mode); - // Set the tag - tags = readPreference.tags; - readPreference = readPreference.mode; - } else if(typeof readPreference == 'object' && readPreference['_type'] != 'ReadPreference') { - return new Error("read preferences must be either a string or an instance of ReadPreference"); - } - - // Set up our read Preference, allowing us to override the readPreference - var finalReadPreference = readPreference != null ? readPreference : this.options.readPreference; - - // Ensure we unpack a reference - if(finalReadPreference != null && typeof finalReadPreference == 'object' && finalReadPreference['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!finalReadPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + finalReadPreference.mode); - // Set the tag - tags = finalReadPreference.tags; - readPreference = finalReadPreference.mode; - } - - // Finalize the read preference setup - finalReadPreference = finalReadPreference == true ? ReadPreference.SECONDARY_PREFERRED : finalReadPreference; - finalReadPreference = finalReadPreference == null ? ReadPreference.PRIMARY : finalReadPreference; - - // If we are reading from a primary - if(finalReadPreference == 'primary') { - // If we provide a tags set send an error - if(typeof tags == 'object' && tags != null) { - return new Error("PRIMARY cannot be combined with tags"); - } - - // If we provide a tags set send an error - if(this._state.master == null) { - return new Error("No replica set primary available for query with ReadPreference PRIMARY"); - } - - // Checkout a writer - return this.checkoutWriter(); - } - - // If we have specified to read from a secondary server grab a random one and read - // from it, otherwise just pass the primary connection - if((this.options.readSecondary || finalReadPreference == ReadPreference.SECONDARY_PREFERRED || finalReadPreference == ReadPreference.SECONDARY) && Object.keys(this._state.secondaries).length > 0) { - // If we have tags, look for servers matching the specific tag - if(this.strategyInstance != null) { - // Only pick from secondaries - var _secondaries = []; - for(var key in this._state.secondaries) { - _secondaries.push(this._state.secondaries[key]); - } - - if(finalReadPreference == ReadPreference.SECONDARY) { - // Check out the nearest from only the secondaries - connection = this.strategyInstance.checkoutConnection(tags, _secondaries); - } else { - connection = this.strategyInstance.checkoutConnection(tags, _secondaries); - // No candidate servers that match the tags, error - if(connection == null || connection instanceof Error) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - return new Error("No replica set members available for query"); - } - } - } - } else if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - return new Error("No replica set members available for query"); - } - } else { - connection = _roundRobin(this, tags); - } - } else if(finalReadPreference == ReadPreference.PRIMARY_PREFERRED) { - // Check if there is a primary available and return that if possible - connection = this.checkoutWriter(); - // If no connection available checkout a secondary - if(connection == null || connection instanceof Error) { - // If we have tags, look for servers matching the specific tag - if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - return new Error("No replica set members available for query"); - } - } else { - connection = _roundRobin(this, tags); - } - } - } else if(finalReadPreference == ReadPreference.SECONDARY_PREFERRED) { - // If we have tags, look for servers matching the specific tag - if(this.strategyInstance != null) { - connection = this.strategyInstance.checkoutConnection(tags); - - // No candidate servers that match the tags, error - if(connection == null || connection instanceof Error) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } - } - } else if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } - } - } - } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance != null) { - connection = this.strategyInstance.checkoutConnection(tags); - } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance == null) { - return new Error("A strategy for calculating nearness must be enabled such as ping or statistical"); - } else if(finalReadPreference == ReadPreference.SECONDARY && Object.keys(this._state.secondaries).length == 0) { - if(tags != null && typeof tags == 'object') { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } else { - return new Error("No replica set secondary available for query with ReadPreference SECONDARY"); - } - } else { - connection = this.checkoutWriter(); - } - - // Return the connection - return connection; -} - -/** - * @ignore - */ -var _pickFromTags = function(self, tags) { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Match all the servers that match the provdided tags - var keys = Object.keys(self._state.secondaries); - var candidateServers = []; - - for(var i = 0; i < keys.length; i++) { - var server = self._state.secondaries[keys[i]]; - // If we have tags match - if(server.tags != null) { - var matching = true; - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - candidateServers.push(server); - } - } - } - - // If we have a candidate server return - if(candidateServers.length > 0) { - if(self.strategyInstance) return self.strategyInstance.checkoutConnection(tags, candidateServers); - // Set instance to return - return candidateServers[Math.floor(Math.random() * candidateServers.length)].checkoutReader(); - } - } - - // No connection found - return null; -} - -/** - * Pick a secondary using round robin - * - * @ignore - */ -function _roundRobin (replset, tags) { - var keys = Object.keys(replset._state.secondaries); - // Update index - replset._currentServerChoice = replset._currentServerChoice + 1; - // Pick a server - var key = keys[replset._currentServerChoice % keys.length]; - - var conn = null != replset._state.secondaries[key] - ? replset._state.secondaries[key].checkoutReader() - : null; - - // If connection is null fallback to first available secondary - if(null == conn) { - conn = pickFirstConnectedSecondary(replset, tags); - } - - return conn; -} - -/** - * @ignore - */ -var pickFirstConnectedSecondary = function pickFirstConnectedSecondary(self, tags) { - var keys = Object.keys(self._state.secondaries); - var connection; - - // Find first available reader if any - for(var i = 0; i < keys.length; i++) { - connection = self._state.secondaries[keys[i]].checkoutReader(); - if(connection) return connection; - } - - // If we still have a null, read from primary if it's not secondary only - if(self._readPreference == ReadPreference.SECONDARY_PREFERRED) { - connection = self._state.master.checkoutReader(); - if(connection) return connection; - } - - var preferenceName = self._readPreference == ReadPreference.SECONDARY_PREFERRED - ? 'secondary' - : self._readPreference; - - return new Error("No replica set member available for query with ReadPreference " - + preferenceName + " and tags " + JSON.stringify(tags)); -} - -/** - * Get list of secondaries - * @ignore - */ -Object.defineProperty(ReplSet.prototype, "secondaries", {enumerable: true - , get: function() { - return utils.objectToArray(this._state.secondaries); - } -}); - -/** - * Get list of secondaries - * @ignore - */ -Object.defineProperty(ReplSet.prototype, "arbiters", {enumerable: true - , get: function() { - return utils.objectToArray(this._state.arbiters); - } -}); - diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js deleted file mode 100644 index 1fbd9c0c9..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Interval state object constructor - * - * @ignore - */ -var ReplSetState = function ReplSetState (replset) { - this.errorMessages = []; - this.secondaries = {}; - this.addresses = {}; - this.arbiters = {}; - this.passives = {}; - this.members = []; - this.errors = {}; - this.setName = null; - this.master = null; - this.replset = replset; -} - -ReplSetState.prototype.hasValidServers = function() { - var validServers = []; - if(this.master && this.master.isConnected()) return true; - - if(this.secondaries) { - var keys = Object.keys(this.secondaries) - for(var i = 0; i < keys.length; i++) { - if(this.secondaries[keys[i]].isConnected()) - return true; - } - } - - return false; -} - -ReplSetState.prototype.getAllReadServers = function() { - var candidate_servers = []; - for(var name in this.addresses) { - candidate_servers.push(this.addresses[name]); - } - - // Return all possible read candidates - return candidate_servers; -} - -ReplSetState.prototype.addServer = function(server, master) { - server.name = master.me; - - if(master.ismaster) { - this.master = server; - this.addresses[server.name] = server; - this.replset.emit('joined', "primary", master, server); - } else if(master.secondary) { - this.secondaries[server.name] = server; - this.addresses[server.name] = server; - this.replset.emit('joined', "secondary", master, server); - } else if(master.arbiters) { - this.arbiters[server.name] = server; - this.addresses[server.name] = server; - this.replset.emit('joined', "arbiter", master, server); - } -} - -ReplSetState.prototype.contains = function(host) { - return this.addresses[host] != null; -} - -ReplSetState.prototype.isPrimary = function(server) { - return this.master && this.master.name == server.name; -} - -ReplSetState.prototype.isSecondary = function(server) { - return this.secondaries[server.name] != null; -} - -exports.ReplSetState = ReplSetState; diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js deleted file mode 100644 index 15a3a885a..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js +++ /dev/null @@ -1,333 +0,0 @@ -var Server = require("../../server").Server - , format = require('util').format; - -// The ping strategy uses pings each server and records the -// elapsed time for the server so it can pick a server based on lowest -// return time for the db command {ping:true} -var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) { - this.replicaset = replicaset; - this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS; - this.state = 'disconnected'; - this.pingInterval = 5000; - // Class instance - this.Db = require("../../../db").Db; - // Active db connections - this.dbs = {}; - // Current server index - this.index = 0; - // Logger api - this.Logger = null; -} - -// Starts any needed code -PingStrategy.prototype.start = function(callback) { - // already running? - if ('connected' == this.state) return; - - this.state = 'connected'; - - // Start ping server - this._pingServer(callback); -} - -// Stops and kills any processes running -PingStrategy.prototype.stop = function(callback) { - // Stop the ping process - this.state = 'disconnected'; - - // Stop all the server instances - for(var key in this.dbs) { - this.dbs[key].close(); - } - - // optional callback - callback && callback(null, null); -} - -PingStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) { - // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS - // Create a list of candidat servers, containing the primary if available - var candidateServers = []; - var self = this; - - // If we have not provided a list of candidate servers use the default setup - if(!Array.isArray(secondaryCandidates)) { - candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : []; - // Add all the secondaries - var keys = Object.keys(this.replicaset._state.secondaries); - for(var i = 0; i < keys.length; i++) { - candidateServers.push(this.replicaset._state.secondaries[keys[i]]) - } - } else { - candidateServers = secondaryCandidates; - } - - // Final list of eligable server - var finalCandidates = []; - - // If we have tags filter by tags - if(tags != null && typeof tags == 'object') { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Remove any that are not tagged correctly - for(var i = 0; i < candidateServers.length; i++) { - var server = candidateServers[i]; - // If we have tags match - if(server.tags != null) { - var matching = true; - - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - finalCandidates.push(server); - } - } - } - } - } else { - // Final array candidates - var finalCandidates = candidateServers; - } - - // Sort by ping time - finalCandidates.sort(function(a, b) { - return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs']; - }); - - if(0 === finalCandidates.length) - return new Error("No replica set members available for query"); - - // find lowest server with a ping time - var lowest = finalCandidates.filter(function (server) { - return undefined != server.runtimeStats.pingMs; - })[0]; - - if(!lowest) { - lowest = finalCandidates[0]; - } - - // convert to integer - var lowestPing = lowest.runtimeStats.pingMs | 0; - - // determine acceptable latency - var acceptable = lowestPing + this.secondaryAcceptableLatencyMS; - - // remove any server responding slower than acceptable - var len = finalCandidates.length; - while(len--) { - if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) { - finalCandidates.splice(len, 1); - } - } - - if(self.logger && self.logger.debug) { - self.logger.debug("Ping strategy selection order for tags", tags); - finalCandidates.forEach(function(c) { - self.logger.debug(format("%s:%s = %s ms", c.host, c.port, c.runtimeStats['pingMs']), null); - }) - } - - // If no candidates available return an error - if(finalCandidates.length == 0) - return new Error("No replica set members available for query"); - - // Ensure no we don't overflow - this.index = this.index % finalCandidates.length - // Pick a random acceptable server - var connection = finalCandidates[this.index].checkoutReader(); - // Point to next candidate (round robin style) - this.index = this.index + 1; - - if(self.logger && self.logger.debug) { - if(connection) - self.logger.debug("picked server %s:%s", connection.socketOptions.host, connection.socketOptions.port); - } - - return connection; -} - -PingStrategy.prototype._pingServer = function(callback) { - var self = this; - - // Ping server function - var pingFunction = function() { - // Our state changed to disconnected or destroyed return - if(self.state == 'disconnected' || self.state == 'destroyed') return; - // If the replicaset is destroyed return - if(self.replicaset.isDestroyed() || self.replicaset._serverState == 'disconnected') return - - // Create a list of all servers we can send the ismaster command to - var allServers = self.replicaset._state.master != null ? [self.replicaset._state.master] : []; - - // Secondary keys - var keys = Object.keys(self.replicaset._state.secondaries); - // Add all secondaries - for(var i = 0; i < keys.length; i++) { - allServers.push(self.replicaset._state.secondaries[keys[i]]); - } - - // Number of server entries - var numberOfEntries = allServers.length; - - // We got keys - for(var i = 0; i < allServers.length; i++) { - - // We got a server instance - var server = allServers[i]; - - // Create a new server object, avoid using internal connections as they might - // be in an illegal state - new function(serverInstance) { - var _db = self.dbs[serverInstance.host + ":" + serverInstance.port]; - // If we have a db - if(_db != null) { - // Startup time of the command - var startTime = Date.now(); - - // Execute ping command in own scope - var _ping = function(__db, __serverInstance) { - // Execute ping on this connection - __db.executeDbCommand({ping:1}, {failFast:true}, function(err) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime; - } - - __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Process the ismaster for the server - if(result && result.documents && self.replicaset.processIsMaster) { - self.replicaset.processIsMaster(__serverInstance, result.documents[0]); - } - - // Done with the pinging - done(); - }); - }); - }; - // Ping - _ping(_db, serverInstance); - } else { - var connectTimeoutMS = self.replicaset.options.socketOptions - ? self.replicaset.options.socketOptions.connectTimeoutMS : 0 - - // Create a new master connection - var _server = new Server(serverInstance.host, serverInstance.port, { - auto_reconnect: false, - returnIsMasterResults: true, - slaveOk: true, - poolSize: 1, - socketOptions: { connectTimeoutMS: connectTimeoutMS }, - ssl: self.replicaset.options.ssl, - sslValidate: self.replicaset.options.sslValidate, - sslCA: self.replicaset.options.sslCA, - sslCert: self.replicaset.options.sslCert, - sslKey: self.replicaset.options.sslKey, - sslPass: self.replicaset.options.sslPass - }); - - // Create Db instance - var _db = new self.Db('local', _server, { safe: true }); - _db.on("close", function() { - delete self.dbs[this.serverConfig.host + ":" + this.serverConfig.port]; - }) - - var _ping = function(__db, __serverInstance) { - if(self.state == 'disconnected') { - self.stop(); - return; - } - - __db.open(function(err, db) { - if(self.state == 'disconnected' && __db != null) { - return __db.close(); - } - - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Save instance - self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port] = __db; - - // Startup time of the command - var startTime = Date.now(); - - // Execute ping on this connection - __db.executeDbCommand({ping:1}, {failFast:true}, function(err) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime; - } - - __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Process the ismaster for the server - if(result && result.documents && self.replicaset.processIsMaster) { - self.replicaset.processIsMaster(__serverInstance, result.documents[0]); - } - - // Done with the pinging - done(); - }); - }); - }); - }; - - // Ping the server - _ping(_db, serverInstance); - } - - function done() { - // Adjust the number of checks - numberOfEntries--; - - // If we are done with all results coming back trigger ping again - if(0 === numberOfEntries && 'connected' == self.state) { - setTimeout(pingFunction, self.pingInterval); - } - } - }(server); - } - } - - // Start pingFunction - pingFunction(); - - callback && callback(null); -} diff --git a/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js b/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js deleted file mode 100644 index f9b8c4643..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js +++ /dev/null @@ -1,80 +0,0 @@ -// The Statistics strategy uses the measure of each end-start time for each -// query executed against the db to calculate the mean, variance and standard deviation -// and pick the server which the lowest mean and deviation -var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) { - this.replicaset = replicaset; - // Logger api - this.Logger = null; -} - -// Starts any needed code -StatisticsStrategy.prototype.start = function(callback) { - callback && callback(null, null); -} - -StatisticsStrategy.prototype.stop = function(callback) { - callback && callback(null, null); -} - -StatisticsStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) { - // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS - // Create a list of candidat servers, containing the primary if available - var candidateServers = []; - - // If we have not provided a list of candidate servers use the default setup - if(!Array.isArray(secondaryCandidates)) { - candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : []; - // Add all the secondaries - var keys = Object.keys(this.replicaset._state.secondaries); - for(var i = 0; i < keys.length; i++) { - candidateServers.push(this.replicaset._state.secondaries[keys[i]]) - } - } else { - candidateServers = secondaryCandidates; - } - - // Final list of eligable server - var finalCandidates = []; - - // If we have tags filter by tags - if(tags != null && typeof tags == 'object') { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Remove any that are not tagged correctly - for(var i = 0; i < candidateServers.length; i++) { - var server = candidateServers[i]; - // If we have tags match - if(server.tags != null) { - var matching = true; - - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - finalCandidates.push(server); - } - } - } - } - } else { - // Final array candidates - var finalCandidates = candidateServers; - } - - // If no candidates available return an error - if(finalCandidates.length == 0) return new Error("No replica set members available for query"); - // Pick a random server - return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader(); -} diff --git a/node_modules/mongodb/lib/mongodb/connection/server.js b/node_modules/mongodb/lib/mongodb/connection/server.js deleted file mode 100644 index 36a3bc07b..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/server.js +++ /dev/null @@ -1,940 +0,0 @@ -var Connection = require('./connection').Connection, - ReadPreference = require('./read_preference').ReadPreference, - DbCommand = require('../commands/db_command').DbCommand, - MongoReply = require('../responses/mongo_reply').MongoReply, - ConnectionPool = require('./connection_pool').ConnectionPool, - EventEmitter = require('events').EventEmitter, - ServerCapabilities = require('./server_capabilities').ServerCapabilities, - Base = require('./base').Base, - format = require('util').format, - utils = require('../utils'), - timers = require('timers'), - inherits = require('util').inherits; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * Class representing a single MongoDB Server connection - * - * Options - * - **readPreference** {String, default:null}, set's the read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support) - * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * - **poolSize** {Number, default:5}, number of connections in the connection pool, set to 5 as default for legacy reasons. - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **auto_reconnect** {Boolean, default:false}, reconnect on error. - * - **disableDriverBSONSizeCheck** {Boolean, default:false}, force the server to error if the BSON message is to big - * - * @class Represents a Server connection. - * @param {String} host the server host - * @param {Number} port the server port - * @param {Object} [options] optional options for insert command - */ -function Server(host, port, options) { - // Set up Server instance - if(!(this instanceof Server)) return new Server(host, port, options); - - // Set up event emitter - Base.call(this); - - // Ensure correct values - if(port != null && typeof port == 'object') { - options = port; - port = Connection.DEFAULT_PORT; - } - - var self = this; - this.host = host; - this.port = port; - this.options = options == null ? {} : options; - this.internalConnection; - this.internalMaster = false; - this.connected = false; - this.poolSize = this.options.poolSize == null ? 5 : this.options.poolSize; - this.disableDriverBSONSizeCheck = this.options.disableDriverBSONSizeCheck != null ? this.options.disableDriverBSONSizeCheck : false; - this._used = false; - this.replicasetInstance = null; - - // Emit open setup - this.emitOpen = this.options.emitOpen || true; - // Set ssl as connection method - this.ssl = this.options.ssl == null ? false : this.options.ssl; - // Set ssl validation - this.sslValidate = this.options.sslValidate == null ? false : this.options.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.sslCA = Array.isArray(this.options.sslCA) ? this.options.sslCA : null; - // Certificate to present to the server - this.sslCert = this.options.sslCert; - // Certificate private key if in separate file - this.sslKey = this.options.sslKey; - // Password to unlock private key - this.sslPass = this.options.sslPass; - // Server capabilities - this.serverCapabilities = null; - // Set server name - this.name = format("%s:%s", host, port); - - // Ensure we are not trying to validate with no list of certificates - if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) { - throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate"); - } - - // Get the readPreference - var readPreference = this.options['readPreference']; - // If readPreference is an object get the mode string - var validateReadPreference = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference; - // Read preference setting - if(validateReadPreference != null) { - if(validateReadPreference != ReadPreference.PRIMARY && validateReadPreference != ReadPreference.SECONDARY && validateReadPreference != ReadPreference.NEAREST - && validateReadPreference != ReadPreference.SECONDARY_PREFERRED && validateReadPreference != ReadPreference.PRIMARY_PREFERRED) { - throw new Error("Illegal readPreference mode specified, " + validateReadPreference); - } - - // Set read Preference - this._readPreference = readPreference; - } else { - this._readPreference = null; - } - - // Contains the isMaster information returned from the server - this.isMasterDoc; - - // Set default connection pool options - this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {}; - if(this.disableDriverBSONSizeCheck) this.socketOptions.disableDriverBSONSizeCheck = this.disableDriverBSONSizeCheck; - - // Set ssl up if it's defined - if(this.ssl) { - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = this.sslCert; - // Set certificate to present - this.socketOptions.sslKey = this.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = this.sslPass; - } - - // Set up logger if any set - this.logger = this.options.logger != null - && (typeof this.options.logger.debug == 'function') - && (typeof this.options.logger.error == 'function') - && (typeof this.options.logger.log == 'function') - ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]}; - // Internal state of server connection - this._serverState = 'disconnected'; - // Contains state information about server connection - this._state = {'runtimeStats': {'queryStats':new RunningStats()}}; - // Do we record server stats or not - this.recordQueryStats = false; - - // Allow setting the socketTimeoutMS on all connections - // to work around issues such as secondaries blocking due to compaction - utils.setSocketTimeoutProperty(this, this.socketOptions); -}; - -/** - * @ignore - */ -inherits(Server, Base); - -// -// Deprecated, USE ReadPreferences class -// -Server.READ_PRIMARY = ReadPreference.PRIMARY; -Server.READ_SECONDARY = ReadPreference.SECONDARY_PREFERRED; -Server.READ_SECONDARY_ONLY = ReadPreference.SECONDARY; - -/** - * Always ourselves - * @ignore - */ -Server.prototype.setReadPreference = function(readPreference) { - this._readPreference = readPreference; -} - -/** - * @ignore - */ -Server.prototype.isMongos = function() { - return this.isMasterDoc != null && this.isMasterDoc['msg'] == "isdbgrid" ? true : false; -} - -/** - * @ignore - */ -Server.prototype._isUsed = function() { - return this._used; -} - -/** - * @ignore - */ -Server.prototype.close = function(callback) { - // Set server status as disconnected - this._serverState = 'destroyed'; - // Remove all local listeners - this.removeAllListeners(); - - if(this.connectionPool != null) { - // Remove all the listeners on the pool so it does not fire messages all over the place - this.connectionPool.removeAllEventListeners(); - // Close the connection if it's open - this.connectionPool.stop(true); - } - - // Emit close event - if(this.db && !this.isSetMember()) { - var self = this; - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }) - - // Flush out any remaining call handlers - self._flushAllCallHandlers(utils.toError("Connection Closed By Application")); - } - - // Peform callback if present - if(typeof callback === 'function') callback(null); -}; - -Server.prototype.isDestroyed = function() { - return this._serverState == 'destroyed'; -} - -/** - * @ignore - */ -Server.prototype.isConnected = function() { - return this.connectionPool != null && this.connectionPool.isConnected(); -} - -/** - * @ignore - */ -Server.prototype.canWrite = Server.prototype.isConnected; -Server.prototype.canRead = Server.prototype.isConnected; - -Server.prototype.isAutoReconnect = function() { - if(this.isSetMember()) return false; - return this.options.auto_reconnect != null ? this.options.auto_reconnect : true; -} - -/** - * @ignore - */ -Server.prototype.allServerInstances = function() { - return [this]; -} - -/** - * @ignore - */ -Server.prototype.isSetMember = function() { - return this.replicasetInstance != null || this.mongosInstance != null; -} - -/** - * Assigns a replica set to this `server`. - * - * @param {ReplSet} replset - * @ignore - */ -Server.prototype.assignReplicaSet = function (replset) { - this.replicasetInstance = replset; - this.inheritReplSetOptionsFrom(replset); - this.enableRecordQueryStats(replset.recordQueryStats); -} - -/** - * Takes needed options from `replset` and overwrites - * our own options. - * - * @param {ReplSet} replset - * @ignore - */ -Server.prototype.inheritReplSetOptionsFrom = function (replset) { - this.socketOptions = {}; - this.socketOptions.connectTimeoutMS = replset.options.socketOptions.connectTimeoutMS || 30000; - - if(replset.options.ssl) { - // Set ssl on - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = replset.options.sslValidate == null ? false : replset.options.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(replset.options.sslCA) ? replset.options.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = replset.options.sslCert; - // Set certificate to present - this.socketOptions.sslKey = replset.options.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = replset.options.sslPass; - } - - // If a socket option object exists clone it - if(utils.isObject(replset.options.socketOptions)) { - var keys = Object.keys(replset.options.socketOptions); - for(var i = 0; i < keys.length; i++) - this.socketOptions[keys[i]] = replset.options.socketOptions[keys[i]]; - } -} - -/** - * Opens this server connection. - * - * @ignore - */ -Server.prototype.connect = function(dbInstance, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - // Save the options - this.options = options; - - // Currently needed to work around problems with multiple connections in a pool with ssl - // TODO fix if possible - if(this.ssl == true) { - // Set up socket options for ssl - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = this.sslCert; - // Set certificate to present - this.socketOptions.sslKey = this.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = this.sslPass; - } - - // Let's connect - var server = this; - // Let's us override the main receiver of events - var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this; - // Save reference to dbInstance - this.db = dbInstance; // `db` property matches ReplSet and Mongos - this.dbInstances = [dbInstance]; - - // Force connection pool if there is one - if(server.connectionPool) server.connectionPool.stop(); - // Set server state to connecting - this._serverState = 'connecting'; - - if(server.connectionPool != null) { - // Remove all the listeners on the pool so it does not fire messages all over the place - this.connectionPool.removeAllEventListeners(); - // Close the connection if it's open - this.connectionPool.stop(true); - } - - this.connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions); - var connectionPool = this.connectionPool; - // If ssl is not enabled don't wait between the pool connections - if(this.ssl == null || !this.ssl) connectionPool._timeToWait = null; - // Set logger on pool - connectionPool.logger = this.logger; - connectionPool.bson = dbInstance.bson; - - // Set basic parameters passed in - var returnIsMasterResults = options.returnIsMasterResults == null ? false : options.returnIsMasterResults; - - // Create a default connect handler, overriden when using replicasets - var connectCallback = function(_server) { - return function(err, reply) { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - - // Assign the server - _server = _server != null ? _server : server; - - // If something close down the connection and removed the callback before - // proxy killed connection etc, ignore the erorr as close event was isssued - if(err != null && internalCallback == null) return; - // Internal callback - if(err != null) return internalCallback(err, null, _server); - _server.master = reply.documents[0].ismaster == 1 ? true : false; - _server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize); - _server.connectionPool.setMaxMessageSizeBytes(reply.documents[0].maxMessageSizeBytes); - // Set server state to connEcted - _server._serverState = 'connected'; - // Set server as connected - _server.connected = true; - // Save document returned so we can query it - _server.isMasterDoc = reply.documents[0]; - - if(self.emitOpen) { - _server._emitAcrossAllDbInstances(_server, eventReceiver, "open", null, returnIsMasterResults ? reply : null, null); - self.emitOpen = false; - } else { - _server._emitAcrossAllDbInstances(_server, eventReceiver, "reconnect", null, returnIsMasterResults ? reply : null, null); - } - - // Set server capabilities - server.serverCapabilities = new ServerCapabilities(_server.isMasterDoc); - - // If we have it set to returnIsMasterResults - if(returnIsMasterResults) { - internalCallback(null, reply, _server); - } else { - internalCallback(null, dbInstance, _server); - } - } - }; - - // Let's us override the main connect callback - var connectHandler = options.connectHandler == null ? connectCallback(server) : options.connectHandler; - - // Set up on connect method - connectionPool.on("poolReady", function() { - // Create db command and Add the callback to the list of callbacks by the request id (mapping outgoing messages to correct callbacks) - var db_command = DbCommand.NcreateIsMasterCommand(dbInstance, dbInstance.databaseName); - // Check out a reader from the pool - var connection = connectionPool.checkoutConnection(); - // Register handler for messages - server._registerHandler(db_command, false, connection, connectHandler); - // Write the command out - connection.write(db_command); - }) - - // Set up item connection - connectionPool.on("message", function(message) { - // Attempt to parse the message - try { - // Create a new mongo reply - var mongoReply = new MongoReply() - // Parse the header - mongoReply.parseHeader(message, connectionPool.bson) - - // If message size is not the same as the buffer size - // something went terribly wrong somewhere - if(mongoReply.messageLength != message.length) { - // Emit the error - if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", new Error("bson length is different from message length"), server); - // Remove all listeners - server.removeAllListeners(); - } else { - var startDate = new Date().getTime(); - - // Callback instance - var callbackInfo = server._findHandler(mongoReply.responseTo.toString()); - - // The command executed another request, log the handler again under that request id - if(mongoReply.requestId > 0 && mongoReply.cursorId.toString() != "0" - && callbackInfo && callbackInfo.info && callbackInfo.info.exhaust) { - server._reRegisterHandler(mongoReply.requestId, callbackInfo); - } - // Parse the body - mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) { - if(err != null) { - // If pool connection is already closed - if(server._serverState === 'disconnected') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // Remove all listeners and close the connection pool - server.removeAllListeners(); - connectionPool.stop(true); - - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(err, null, server); - } else if(server.isSetMember()) { - if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", utils.toError(err), server); - } else { - if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", utils.toError(err), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(err); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true); - } - // Short cut - return; - } - - // Let's record the stats info if it's enabled - if(server.recordQueryStats == true && server._state['runtimeStats'] != null - && server._state.runtimeStats['queryStats'] instanceof RunningStats) { - // Add data point to the running statistics object - server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start); - } - - // Dispatch the call - server._callHandler(mongoReply.responseTo, mongoReply, null); - - // If we have an error about the server not being master or primary - if((mongoReply.responseFlag & (1 << 1)) != 0 - && mongoReply.documents[0].code - && mongoReply.documents[0].code == 13436) { - server.close(); - } - }); - } - } catch (err) { - // Throw error in next tick - processor(function() { - throw err; - }) - } - }); - - // Handle timeout - connectionPool.on("timeout", function(err) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(err, null, server); - } else if(server.isSetMember()) { - if(server.listeners("timeout") && server.listeners("timeout").length > 0) server.emit("timeout", err, server); - } else { - if(eventReceiver.listeners("timeout") && eventReceiver.listeners("timeout").length > 0) eventReceiver.emit("timeout", err, server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(err); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "timeout", err, server, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - // Handle errors - connectionPool.on("error", function(message, connection, error_options) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - - // Set server state to disconnected - server._serverState = 'disconnected'; - // Error message - var error_message = new Error(message && message.err ? message.err : message); - // Error message coming from ssl - if(error_options && error_options.ssl) error_message.ssl = true; - - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(error_message, null, server); - } else if(server.isSetMember()) { - if(server.listeners("error") && server.listeners("error").length > 0) server.emit("error", error_message, server); - } else { - if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", error_message, server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(error_message); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "error", error_message, server, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - // Handle close events - connectionPool.on("close", function() { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback == 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(new Error("connection closed"), null, server); - } else if(server.isSetMember()) { - if(server.listeners("close") && server.listeners("close").length > 0) server.emit("close", new Error("connection closed"), server); - } else { - if(eventReceiver.listeners("close") && eventReceiver.listeners("close").length > 0) eventReceiver.emit("close", new Error("connection closed"), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(new Error("connection closed")); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "close", server, null, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - /** - * @ignore - */ - var __attemptReconnect = function(server) { - return function() { - // Attempt reconnect - server.connect(server.db, server.options, function(err, result) { - server._reconnect_retries = server._reconnect_retries - 1; - - if(err) { - // Retry - if(server._reconnect_retries == 0 || server._serverState == 'destroyed') { - server._serverState = 'connected'; - server._reconnectInProgreess = false - // Fire all callback errors - return server.__executeAllCallbacksWithError(new Error("failed to reconnect to server")); - } else { - return setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - } else { - // Set as authenticating (isConnected will be false) - server._serverState = 'authenticating'; - // Apply any auths, we don't try to catch any errors here - // as there are nowhere to simply propagate them to - self._apply_auths(server.db, function(err, result) { - server._serverState = 'connected'; - server._reconnectInProgreess = false; - server._commandsStore.execute_queries(); - server._commandsStore.execute_writes(); - }); - } - }); - } - } - - // If we have a parser error we are in an unknown state, close everything and emit - // error - connectionPool.on("parseError", function(err) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(utils.toError(err), null, server); - } else if(server.isSetMember()) { - if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", utils.toError(err), server); - } else { - if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", utils.toError(err), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(utils.toError(err)); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true); - } - }); - - // Boot up connection poole, pass in a locator of callbacks - connectionPool.start(); -} - -/** - * @ignore - */ -Server.prototype.allRawConnections = function() { - return this.connectionPool != null ? this.connectionPool.getAllConnections() : []; -} - -/** - * Check if a writer can be provided - * @ignore - */ -var canCheckoutWriter = function(self, read) { - // We cannot write to an arbiter or secondary server - if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) { - return new Error("Cannot write to an arbiter"); - } if(self.isMasterDoc && self.isMasterDoc['secondary'] == true) { - return new Error("Cannot write to a secondary"); - } else if(read == true && self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) { - return new Error("Cannot read from primary when secondary only specified"); - } else if(!self.isMasterDoc) { - return new Error("Cannot determine state of server"); - } - - // Return no error - return null; -} - -/** - * @ignore - */ -Server.prototype.checkoutWriter = function(read) { - if(read == true) return this.connectionPool.checkoutConnection(); - // Check if are allowed to do a checkout (if we try to use an arbiter f.ex) - var result = canCheckoutWriter(this, read); - // If the result is null check out a writer - if(result == null && this.connectionPool != null) { - var connection = this.connectionPool.checkoutConnection(); - // Add server capabilities to the connection - if(connection) - connection.serverCapabilities = this.serverCapabilities; - return connection; - } else if(result == null) { - return null; - } else { - return result; - } -} - -/** - * Check if a reader can be provided - * @ignore - */ -var canCheckoutReader = function(self) { - // We cannot write to an arbiter or secondary server - if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) { - return new Error("Cannot write to an arbiter"); - } else if(self._readPreference != null) { - // If the read preference is Primary and the instance is not a master return an error - if((self._readPreference == ReadPreference.PRIMARY) && self.isMasterDoc && self.isMasterDoc['ismaster'] != true) { - return new Error("Read preference is Server.PRIMARY and server is not master"); - } else if(self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) { - return new Error("Cannot read from primary when secondary only specified"); - } - } else if(!self.isMasterDoc) { - return new Error("Cannot determine state of server"); - } - - // Return no error - return null; -} - -/** - * @ignore - */ -Server.prototype.checkoutReader = function(read) { - // Check if are allowed to do a checkout (if we try to use an arbiter f.ex) - var result = canCheckoutReader(this); - // If the result is null check out a writer - if(result == null && this.connectionPool != null) { - var connection = this.connectionPool.checkoutConnection(); - // Add server capabilities to the connection - if(connection) - connection.serverCapabilities = this.serverCapabilities; - return connection; - } else if(result == null) { - return null; - } else { - return result; - } -} - -/** - * @ignore - */ -Server.prototype.enableRecordQueryStats = function(enable) { - this.recordQueryStats = enable; -} - -/** - * Internal statistics object used for calculating average and standard devitation on - * running queries - * @ignore - */ -var RunningStats = function() { - var self = this; - this.m_n = 0; - this.m_oldM = 0.0; - this.m_oldS = 0.0; - this.m_newM = 0.0; - this.m_newS = 0.0; - - // Define getters - Object.defineProperty(this, "numDataValues", { enumerable: true - , get: function () { return this.m_n; } - }); - - Object.defineProperty(this, "mean", { enumerable: true - , get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; } - }); - - Object.defineProperty(this, "variance", { enumerable: true - , get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); } - }); - - Object.defineProperty(this, "standardDeviation", { enumerable: true - , get: function () { return Math.sqrt(this.variance); } - }); - - Object.defineProperty(this, "sScore", { enumerable: true - , get: function () { - var bottom = this.mean + this.standardDeviation; - if(bottom == 0) return 0; - return ((2 * this.mean * this.standardDeviation)/(bottom)); - } - }); -} - -/** - * @ignore - */ -RunningStats.prototype.push = function(x) { - // Update the number of samples - this.m_n = this.m_n + 1; - // See Knuth TAOCP vol 2, 3rd edition, page 232 - if(this.m_n == 1) { - this.m_oldM = this.m_newM = x; - this.m_oldS = 0.0; - } else { - this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n; - this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM); - - // set up for next iteration - this.m_oldM = this.m_newM; - this.m_oldS = this.m_newS; - } -} - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "autoReconnect", { enumerable: true - , get: function () { - return this.options['auto_reconnect'] == null ? false : this.options['auto_reconnect']; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "connection", { enumerable: true - , get: function () { - return this.internalConnection; - } - , set: function(connection) { - this.internalConnection = connection; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "master", { enumerable: true - , get: function () { - return this.internalMaster; - } - , set: function(value) { - this.internalMaster = value; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "primary", { enumerable: true - , get: function () { - return this; - } -}); - -/** - * Getter for query Stats - * @ignore - */ -Object.defineProperty(Server.prototype, "queryStats", { enumerable: true - , get: function () { - return this._state.runtimeStats.queryStats; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "runtimeStats", { enumerable: true - , get: function () { - return this._state.runtimeStats; - } -}); - -/** - * Get Read Preference method - * @ignore - */ -Object.defineProperty(Server.prototype, "readPreference", { enumerable: true - , get: function () { - if(this._readPreference == null && this.readSecondary) { - return Server.READ_SECONDARY; - } else if(this._readPreference == null && !this.readSecondary) { - return Server.READ_PRIMARY; - } else { - return this._readPreference; - } - } -}); - -/** - * @ignore - */ -exports.Server = Server; diff --git a/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js b/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js deleted file mode 100644 index 88bdf9f4a..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/server_capabilities.js +++ /dev/null @@ -1,48 +0,0 @@ -var ServerCapabilities = function(isMasterResult) { - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var maxNumberOfDocsInBatch = 1000; - - if(isMasterResult.minWireVersion >= 0) { - textSearch = true; - } - - if(isMasterResult.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if(isMasterResult.maxWireVersion >= 2) { - writeCommands = true; - } - - // If no min or max wire version set to 0 - if(isMasterResult.minWireVersion == null) { - isMasterResult.minWireVersion = 0; - } - - if(isMasterResult.maxWireVersion == null) { - isMasterResult.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, "hasAggregationCursor", aggregationCursor); - setup_get_property(this, "hasWriteCommands", writeCommands); - setup_get_property(this, "hasTextSearch", textSearch); - setup_get_property(this, "hasAuthCommands", authCommands); - setup_get_property(this, "minWireVersion", isMasterResult.minWireVersion); - setup_get_property(this, "maxWireVersion", isMasterResult.maxWireVersion); - setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); -} - -var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true - , get: function () { return value; } - }); -} - -exports.ServerCapabilities = ServerCapabilities; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/connection/url_parser.js b/node_modules/mongodb/lib/mongodb/connection/url_parser.js deleted file mode 100644 index 1d32b6a7b..000000000 --- a/node_modules/mongodb/lib/mongodb/connection/url_parser.js +++ /dev/null @@ -1,254 +0,0 @@ -var fs = require('fs'), - ReadPreference = require('./read_preference').ReadPreference; - -exports.parse = function(url, options) { - // Ensure we have a default options object if none set - options = options || {}; - // Variables - var connection_part = ''; - var auth_part = ''; - var query_string_part = ''; - var dbName = 'admin'; - - // Must start with mongodb - if(url.indexOf("mongodb://") != 0) - throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); - // If we have a ? mark cut the query elements off - if(url.indexOf("?") != -1) { - query_string_part = url.substr(url.indexOf("?") + 1); - connection_part = url.substring("mongodb://".length, url.indexOf("?")) - } else { - connection_part = url.substring("mongodb://".length); - } - - // Check if we have auth params - if(connection_part.indexOf("@") != -1) { - auth_part = connection_part.split("@")[0]; - connection_part = connection_part.split("@")[1]; - } - - // Check if the connection string has a db - if(connection_part.indexOf(".sock") != -1) { - if(connection_part.indexOf(".sock/") != -1) { - dbName = connection_part.split(".sock/")[1]; - connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); - } - } else if(connection_part.indexOf("/") != -1) { - dbName = connection_part.split("/")[1]; - connection_part = connection_part.split("/")[0]; - } - - // Result object - var object = {}; - - // Pick apart the authentication part of the string - var authPart = auth_part || ''; - var auth = authPart.split(':', 2); - if(options['uri_decode_auth']){ - auth[0] = decodeURIComponent(auth[0]); - if(auth[1]){ - auth[1] = decodeURIComponent(auth[1]); - } - } - - // Add auth to final object if we have 2 elements - if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; - - // Variables used for temporary storage - var hostPart; - var urlOptions; - var servers; - var serverOptions = {socketOptions: {}}; - var dbOptions = {read_preference_tags: []}; - var replSetServersOptions = {socketOptions: {}}; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = {}; - - // Let's check if we are using a domain socket - if(url.match(/\.sock/)) { - // Split out the socket part - var domainSocket = url.substring( - url.indexOf("mongodb://") + "mongodb://".length - , url.lastIndexOf(".sock") + ".sock".length); - // Clean out any auth stuff if any - if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; - servers = [{domain_socket: domainSocket}]; - } else { - // Split up the db - hostPart = connection_part; - // Parse all server results - servers = hostPart.split(',').map(function(h) { - var hostPort = h.split(':', 2); - var _host = hostPort[0] || 'localhost'; - var _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; - - // Return the mapped object - return {host: _host, port: _port}; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if(!opt) return; - var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; - // Options implementations - switch(name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = (value == 'true'); - dbOptions.slaveOk = (value == 'true'); - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = (value == 'true'); - break; - case 'minPoolSize': - throw new Error("minPoolSize not supported"); - case 'maxIdleTimeMS': - throw new Error("maxIdleTimeMS not supported"); - case 'waitQueueMultiple': - throw new Error("waitQueueMultiple not supported"); - case 'waitQueueTimeoutMS': - throw new Error("waitQueueTimeoutMS not supported"); - case 'uuidRepresentation': - throw new Error("uuidRepresentation not supported"); - case 'ssl': - if(value == 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - break; - } - serverOptions.ssl = (value == 'true'); - replSetServersOptions.ssl = (value == 'true'); - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = (value == 'true'); - break; - case 'fsync': - dbOptions.fsync = (value == 'true'); - break; - case 'journal': - dbOptions.journal = (value == 'true'); - break; - case 'safe': - dbOptions.safe = (value == 'true'); - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = (value == 'true'); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if(value == 'GSSAPI') { - // If no password provided decode only the principal - if(object.auth == null) { - var urlDecodeAuthPart = decodeURIComponent(authPart); - if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); - object.auth = {user: urlDecodeAuthPart, password: null}; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if(value == 'MONGODB-X509') { - object.auth = {user: decodeURIComponent(authPart)}; - } - - // Only support GSSAPI or MONGODB-CR for now - if(value != 'GSSAPI' - && value != 'MONGODB-X509' - && value != 'MONGODB-CR' - && value != 'PLAIN') - throw new Error("only GSSAPI, PLAIN, MONGODB-X509 or MONGODB-CR is supported by authMechanism"); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'wtimeoutMS': - dbOptions.wtimeoutMS = parseInt(value, 10); - break; - case 'readPreference': - if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); - dbOptions.read_preference = value; - break; - case 'readPreferenceTags': - // Contains the tag object - var tagObject = {}; - if(value == null || value == '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - var tags = value.split(/\,/); - for(var i = 0; i < tags.length; i++) { - var parts = tags[i].trim().split(/\:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - break; - default: - break; - } - }); - - // No tags: should be null (not []) - if(dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if((dbOptions.w == -1 || dbOptions.w == 0) && ( - dbOptions.journal == true - || dbOptions.fsync == true - || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") - - // If no read preference set it to primary - if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; - - // Add servers to result - object.servers = servers; - // Returned parsed object - return object; -} diff --git a/node_modules/mongodb/lib/mongodb/cursor.js b/node_modules/mongodb/lib/mongodb/cursor.js deleted file mode 100644 index d54754e04..000000000 --- a/node_modules/mongodb/lib/mongodb/cursor.js +++ /dev/null @@ -1,1008 +0,0 @@ -var QueryCommand = require('./commands/query_command').QueryCommand, - GetMoreCommand = require('./commands/get_more_command').GetMoreCommand, - KillCursorCommand = require('./commands/kill_cursor_command').KillCursorCommand, - Long = require('bson').Long, - ReadPreference = require('./connection/read_preference').ReadPreference, - CursorStream = require('./cursorstream'), - timers = require('timers'), - utils = require('./utils'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Constructor for a cursor object that handles all the operations on query result - * using find. This cursor object is unidirectional and cannot traverse backwards. Clients should not be creating a cursor directly, - * but use find to acquire a cursor. (INTERNAL TYPE) - * - * Options - * - **skip** {Number} skip number of documents to skip. - * - **limit** {Number}, limit the number of results to return. -1 has a special meaning and is used by Db.eval. A value of 1 will also be treated as if it were -1. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **hint** {Object}, hint force the query to use a specific index. - * - **explain** {Boolean}, explain return the explaination of the query. - * - **snapshot** {Boolean}, snapshot Snapshot mode assures no duplicates are returned. - * - **timeout** {Boolean}, timeout allow the query to timeout. - * - **tailable** {Boolean}, tailable allow the cursor to be tailable. - * - **awaitdata** {Boolean}, awaitdata allow the cursor to wait for data, only applicable for tailable cursor. - * - **oplogReplay** {Boolean}, sets an internal flag, only applicable for tailable cursor. - * - **batchSize** {Number}, batchSize the number of the subset of results to request the database to return for every request. This should initially be greater than 1 otherwise the database will automatically close the cursor. The batch size can be set to 1 with cursorInstance.batchSize after performing the initial query to the database. - * - **raw** {Boolean}, raw return all query documents as raw buffers (default false). - * - **read** {Boolean}, read specify override of read from source (primary/secondary). - * - **returnKey** {Boolean}, returnKey only return the index key. - * - **maxScan** {Number}, maxScan limit the number of items to scan. - * - **min** {Number}, min set index bounds. - * - **max** {Number}, max set index bounds. - * - **maxTimeMS** {Number}, number of miliseconds to wait before aborting the query. - * - **showDiskLoc** {Boolean}, showDiskLoc show disk location of results. - * - **comment** {String}, comment you can put a $comment field on a query to make looking in the profiler logs simpler. - * - **numberOfRetries** {Number}, numberOfRetries if using awaidata specifies the number of times to retry on timeout. - * - **dbName** {String}, dbName override the default dbName. - * - **tailableRetryInterval** {Number}, tailableRetryInterval specify the miliseconds between getMores on tailable cursor. - * - **exhaust** {Boolean}, exhaust have the server send all the documents at once as getMore packets. - * - **partial** {Boolean}, partial have the sharded system return a partial result from mongos. - * - * @class Represents a Cursor. - * @param {Db} db the database object to work with. - * @param {Collection} collection the collection to query. - * @param {Object} selector the query selector. - * @param {Object} fields an object containing what fields to include or exclude from objects returned. - * @param {Object} [options] additional options for the collection. -*/ -function Cursor(db, collection, selector, fields, options) { - this.db = db; - this.collection = collection; - this.selector = selector; - this.fields = fields; - options = !options ? {} : options; - - this.skipValue = options.skip == null ? 0 : options.skip; - this.limitValue = options.limit == null ? 0 : options.limit; - this.sortValue = options.sort; - this.hint = options.hint; - this.explainValue = options.explain; - this.snapshot = options.snapshot; - this.timeout = options.timeout == null ? true : options.timeout; - this.tailable = options.tailable; - this.awaitdata = options.awaitdata; - this.oplogReplay = options.oplogReplay; - this.numberOfRetries = options.numberOfRetries == null ? 5 : options.numberOfRetries; - this.currentNumberOfRetries = this.numberOfRetries; - this.batchSizeValue = options.batchSize == null ? 0 : options.batchSize; - this.raw = options.raw == null ? false : options.raw; - this.read = options.read == null ? ReadPreference.PRIMARY : options.read; - this.returnKey = options.returnKey; - this.maxScan = options.maxScan; - this.min = options.min; - this.max = options.max; - this.showDiskLoc = options.showDiskLoc; - this.comment = options.comment; - this.tailableRetryInterval = options.tailableRetryInterval || 100; - this.exhaust = options.exhaust || false; - this.partial = options.partial || false; - this.slaveOk = options.slaveOk || false; - this.maxTimeMSValue = options.maxTimeMS; - - this.totalNumberOfRecords = 0; - this.items = []; - this.cursorId = Long.fromInt(0); - - // This name - this.dbName = options.dbName; - - // State variables for the cursor - this.state = Cursor.INIT; - // Keep track of the current query run - this.queryRun = false; - this.getMoreTimer = false; - - // If we are using a specific db execute against it - if(this.dbName != null) { - this.collectionName = this.dbName + "." + this.collection.collectionName; - } else { - this.collectionName = (this.db.databaseName ? this.db.databaseName + "." : '') + this.collection.collectionName; - } -}; - -/** - * Resets this cursor to its initial state. All settings like the query string, - * tailable, batchSizeValue, skipValue and limits are preserved. - * - * @return {Cursor} returns itself with rewind applied. - * @api public - */ -Cursor.prototype.rewind = function() { - var self = this; - - if (self.state != Cursor.INIT) { - if (self.state != Cursor.CLOSED) { - self.close(function() {}); - } - - self.numberOfReturned = 0; - self.totalNumberOfRecords = 0; - self.items = []; - self.cursorId = Long.fromInt(0); - self.state = Cursor.INIT; - self.queryRun = false; - } - - return self; -}; - - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * - * @param {Function} callback This will be called after executing this method successfully. The first parameter will contain the Error object if an error occured, or null otherwise. The second parameter will contain an array of BSON deserialized objects as a result of the query. - * @return {null} - * @api public - */ -Cursor.prototype.toArray = function(callback) { - var self = this; - - if(!callback) { - throw new Error('callback is mandatory'); - } - - if(this.tailable) { - callback(new Error("Tailable cursor cannot be converted to array"), null); - } else if(this.state != Cursor.CLOSED) { - // return toArrayExhaust(self, callback); - // If we are using exhaust we can't use the quick fire method - if(self.exhaust) return toArrayExhaust(self, callback); - // Quick fire using trampoline to avoid nextTick - self.nextObject({noReturn: true}, function(err, result) { - if(err) return callback(utils.toError(err), null); - if(self.cursorId.toString() == "0") { - self.state = Cursor.CLOSED; - return callback(null, self.items); - } - - // Let's issue getMores until we have no more records waiting - getAllByGetMore(self, function(err, done) { - self.state = Cursor.CLOSED; - if(err) return callback(utils.toError(err), null); - // Let's release the internal list - var items = self.items; - self.items = null; - // Return all the items - callback(null, items); - }); - }) - - } else { - callback(new Error("Cursor is closed"), null); - } -} - -var toArrayExhaust = function(self, callback) { - var items = []; - - self.each(function(err, item) { - if(err != null) { - return callback(utils.toError(err), null); - } - - if(item != null && Array.isArray(items)) { - items.push(item); - } else { - var resultItems = items; - items = null; - self.items = []; - callback(null, resultItems); - } - }); -} - -var getAllByGetMore = function(self, callback) { - getMore(self, {noReturn: true}, function(err, result) { - if(err) return callback(utils.toError(err)); - if(result == null) return callback(null, null); - if(self.cursorId.toString() == "0") return callback(null, null); - getAllByGetMore(self, callback); - }) -}; - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * - * @param {Function} callback this will be called for while iterating every document of the query result. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the document. - * @return {null} - * @api public - */ -Cursor.prototype.each = function(callback) { - var self = this; - var fn; - - if (!callback) { - throw new Error('callback is mandatory'); - } - - if(this.state != Cursor.CLOSED) { - // If we are using exhaust we can't use the quick fire method - if(self.exhaust) return eachExhaust(self, callback); - // Quick fire using trampoline to avoid nextTick - if(this.items.length > 0) { - // Trampoline all the entries - while(fn = loop(self, callback)) fn(self, callback); - // Call each again - self.each(callback); - } else { - self.nextObject(function(err, item) { - - if(err) { - self.state = Cursor.CLOSED; - return callback(utils.toError(err), item); - } - - if(item == null) return callback(null, null); - callback(null, item); - self.each(callback); - }) - } - } else { - callback(new Error("Cursor is closed"), null); - } -}; - -// Special for exhaust command as we don't initiate the actual result sets -// the server just sends them as they arrive meaning we need to get the IO event -// loop happen so we can receive more data from the socket or we return to early -// after the first fetch and loose all the incoming getMore's automatically issued -// from the server. -var eachExhaust = function(self, callback) { - //FIX: stack overflow (on deep callback) (cred: https://github.com/limp/node-mongodb-native/commit/27da7e4b2af02035847f262b29837a94bbbf6ce2) - processor(function(){ - // Fetch the next object until there is no more objects - self.nextObject(function(err, item) { - if(err != null) return callback(err, null); - if(item != null) { - callback(null, item); - eachExhaust(self, callback); - } else { - // Close the cursor if done - self.state = Cursor.CLOSED; - callback(err, null); - } - }); - }); -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -var loop = function(self, callback) { - // No more items we are done - if(self.items.length == 0) return; - // Get the next document - var doc = self.items.shift(); - // Callback - callback(null, doc); - // Loop - return loop; -} - -/** - * Determines how many result the query for this cursor will return - * - * @param {Boolean} applySkipLimit if set to true will apply the skip and limits set on the cursor. Defaults to false. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the number of results or null if an error occured. - * @return {null} - * @api public - */ -Cursor.prototype.count = function(applySkipLimit, callback) { - if(typeof applySkipLimit == 'function') { - callback = applySkipLimit; - applySkipLimit = false; - } - - var options = {}; - if(applySkipLimit) { - if(typeof this.skipValue == 'number') options.skip = this.skipValue; - if(typeof this.limitValue == 'number') options.limit = this.limitValue; - } - - // If maxTimeMS set - if(typeof this.maxTimeMSValue == 'number') options.maxTimeMS = this.maxTimeMSValue; - - // Call count command - this.collection.count(this.selector, options, callback); -}; - -/** - * Sets the sort parameter of this cursor to the given value. - * - * This method has the following method signatures: - * (keyOrList, callback) - * (keyOrList, direction, callback) - * - * @param {String|Array|Object} keyOrList This can be a string or an array. If passed as a string, the string will be the field to sort. If passed an array, each element will represent a field to be sorted and should be an array that contains the format [string, direction]. - * @param {String|Number} direction this determines how the results are sorted. "asc", "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending order. Note that the strings are case insensitive. - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.sort = function(keyOrList, direction, callback) { - callback = callback || function(){}; - if(typeof direction === "function") { callback = direction; direction = null; } - - if(this.tailable) { - callback(new Error("Tailable cursor doesn't support sorting"), null); - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - callback(new Error("Cursor is closed"), null); - } else { - var order = keyOrList; - - if(direction != null) { - order = [[keyOrList, direction]]; - } - - this.sortValue = order; - callback(null, this); - } - return this; -}; - -/** - * Sets the limit parameter of this cursor to the given value. - * - * @param {Number} limit the new limit. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the limit given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.limit = function(limit, callback) { - if(this.tailable) { - if(callback) { - callback(new Error("Tailable cursor doesn't support limit"), null); - } else { - throw new Error("Tailable cursor doesn't support limit"); - } - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - if(callback) { - callback(new Error("Cursor is closed"), null); - } else { - throw new Error("Cursor is closed"); - } - } else { - if(limit != null && limit.constructor != Number) { - if(callback) { - callback(new Error("limit requires an integer"), null); - } else { - throw new Error("limit requires an integer"); - } - } else { - this.limitValue = limit; - if(callback) return callback(null, this); - } - } - - return this; -}; - -/** - * Specifies a time limit for a query operation. After the specified - * time is exceeded, the operation will be aborted and an error will be - * returned to the client. If maxTimeMS is null, no limit is applied. - * - * @param {Number} maxTimeMS the maxTimeMS for the query. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the limit given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.maxTimeMS = function(maxTimeMS, callback) { - if(typeof maxTimeMS != 'number') { - throw new Error("maxTimeMS must be a number"); - } - - // Save the maxTimeMS option - this.maxTimeMSValue = maxTimeMS; - // Return the cursor for chaining - return this; -}; - -/** - * Sets the read preference for the cursor - * - * @param {String} the read preference for the cursor, one of Server.READ_PRIMARY, Server.READ_SECONDARY, Server.READ_SECONDARY_ONLY - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the read preference given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.setReadPreference = function(readPreference, tags, callback) { - if(typeof tags == 'function') callback = tags; - - var _mode = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference; - - if(this.queryRun == true || this.state == Cursor.CLOSED) { - if(callback == null) throw new Error("Cannot change read preference on executed query or closed cursor"); - callback(new Error("Cannot change read preference on executed query or closed cursor")); - } else if(_mode != null && _mode != 'primary' - && _mode != 'secondaryOnly' && _mode != 'secondary' - && _mode != 'nearest' && _mode != 'primaryPreferred' && _mode != 'secondaryPreferred') { - if(callback == null) throw new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported"); - callback(new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported")); - } else { - this.read = readPreference; - if(callback != null) callback(null, this); - } - - return this; -} - -/** - * Sets the skip parameter of this cursor to the given value. - * - * @param {Number} skip the new skip value. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the skip value given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.skip = function(skip, callback) { - callback = callback || function(){}; - - if(this.tailable) { - callback(new Error("Tailable cursor doesn't support skip"), null); - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - callback(new Error("Cursor is closed"), null); - } else { - if(skip != null && skip.constructor != Number) { - callback(new Error("skip requires an integer"), null); - } else { - this.skipValue = skip; - callback(null, this); - } - } - - return this; -}; - -/** - * Sets the batch size parameter of this cursor to the given value. - * - * @param {Number} batchSize the new batch size. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the batchSize given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.batchSize = function(batchSize, callback) { - if(this.state == Cursor.CLOSED) { - if(callback != null) { - return callback(new Error("Cursor is closed"), null); - } else { - throw new Error("Cursor is closed"); - } - } else if(batchSize != null && batchSize.constructor != Number) { - if(callback != null) { - return callback(new Error("batchSize requires an integer"), null); - } else { - throw new Error("batchSize requires an integer"); - } - } else { - this.batchSizeValue = batchSize; - if(callback != null) return callback(null, this); - } - - return this; -}; - -/** - * The limit used for the getMore command - * - * @return {Number} The number of records to request per batch. - * @ignore - * @api private - */ -var limitRequest = function(self) { - var requestedLimit = self.limitValue; - var absLimitValue = Math.abs(self.limitValue); - var absBatchValue = Math.abs(self.batchSizeValue); - - if(absLimitValue > 0) { - if (absBatchValue > 0) { - requestedLimit = Math.min(absLimitValue, absBatchValue); - } - } else { - requestedLimit = self.batchSizeValue; - } - - return requestedLimit; -}; - - -/** - * Generates a QueryCommand object using the parameters of this cursor. - * - * @return {QueryCommand} The command object - * @ignore - * @api private - */ -var generateQueryCommand = function(self) { - // Unpack the options - var queryOptions = QueryCommand.OPTS_NONE; - if(!self.timeout) { - queryOptions |= QueryCommand.OPTS_NO_CURSOR_TIMEOUT; - } - - if(self.tailable != null) { - queryOptions |= QueryCommand.OPTS_TAILABLE_CURSOR; - self.skipValue = self.limitValue = 0; - - // if awaitdata is set - if(self.awaitdata != null) { - queryOptions |= QueryCommand.OPTS_AWAIT_DATA; - } - - // This sets an internal undocumented flag. Clients should not depend on its - // behavior! - if(self.oplogReplay != null) { - queryOptions |= QueryCommand.OPTS_OPLOG_REPLAY; - } - } - - if(self.exhaust) { - queryOptions |= QueryCommand.OPTS_EXHAUST; - } - - // Unpack the read preference to set slave ok correctly - var read = self.read instanceof ReadPreference ? self.read.mode : self.read; - - // if(self.read == 'secondary') - if(read == ReadPreference.PRIMARY_PREFERRED - || read == ReadPreference.SECONDARY - || read == ReadPreference.SECONDARY_PREFERRED - || read == ReadPreference.NEAREST) { - queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Override slaveOk from the user - if(self.slaveOk) { - queryOptions |= QueryCommand.OPTS_SLAVE; - } - - if(self.partial) { - queryOptions |= QueryCommand.OPTS_PARTIAL; - } - - // limitValue of -1 is a special case used by Db#eval - var numberToReturn = self.limitValue == -1 ? -1 : limitRequest(self); - - // Check if we need a special selector - if(self.sortValue != null || self.explainValue != null || self.hint != null || self.snapshot != null - || self.returnKey != null || self.maxScan != null || self.min != null || self.max != null - || self.showDiskLoc != null || self.comment != null || typeof self.maxTimeMSValue == 'number') { - - // Build special selector - var specialSelector = {'$query':self.selector}; - if(self.sortValue != null) specialSelector['orderby'] = utils.formattedOrderClause(self.sortValue); - if(self.hint != null && self.hint.constructor == Object) specialSelector['$hint'] = self.hint; - if(self.snapshot != null) specialSelector['$snapshot'] = true; - if(self.returnKey != null) specialSelector['$returnKey'] = self.returnKey; - if(self.maxScan != null) specialSelector['$maxScan'] = self.maxScan; - if(self.min != null) specialSelector['$min'] = self.min; - if(self.max != null) specialSelector['$max'] = self.max; - if(self.showDiskLoc != null) specialSelector['$showDiskLoc'] = self.showDiskLoc; - if(self.comment != null) specialSelector['$comment'] = self.comment; - - // If we are querying the $cmd collection we need to add maxTimeMS as a field - // otherwise for a normal query it's a "special selector" $maxTimeMS - if(typeof self.maxTimeMSValue == 'number' - && self.collectionName.indexOf('.$cmd') != -1) { - specialSelector['maxTimeMS'] = self.maxTimeMSValue; - } else if(typeof self.maxTimeMSValue == 'number' - && self.collectionName.indexOf('.$cmd') == -1) { - specialSelector['$maxTimeMS'] = self.maxTimeMSValue; - } - - // If we have explain set only return a single document with automatic cursor close - if(self.explainValue != null) { - numberToReturn = (-1)*Math.abs(numberToReturn); - specialSelector['$explain'] = true; - } - - // Return the query - return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, specialSelector, self.fields); - } else { - return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, self.selector, self.fields); - } -}; - -/** - * @return {Object} Returns an object containing the sort value of this cursor with - * the proper formatting that can be used internally in this cursor. - * @ignore - * @api private - */ -Cursor.prototype.formattedOrderClause = function() { - return utils.formattedOrderClause(this.sortValue); -}; - -/** - * Converts the value of the sort direction into its equivalent numerical value. - * - * @param sortDirection {String|number} Range of acceptable values: - * 'ascending', 'descending', 'asc', 'desc', 1, -1 - * - * @return {number} The equivalent numerical value - * @throws Error if the given sortDirection is invalid - * @ignore - * @api private - */ -Cursor.prototype.formatSortValue = function(sortDirection) { - return utils.formatSortValue(sortDirection); -}; - -/** - * Gets the next document from the cursor. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results. - * @api public - */ -Cursor.prototype.nextObject = function(options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - if(self.state == Cursor.INIT) { - var cmd; - try { - cmd = generateQueryCommand(self); - } catch (err) { - return callback(err, null); - } - - // No need to check the keys - var queryOptions = {exhaust: self.exhaust - , raw:self.raw - , read:self.read - , connection:self.connection - , checkKeys: false}; - - // Execute command - var commandHandler = function(err, result) { - // If on reconnect, the command got given a different connection, switch - // the whole cursor to it. - self.connection = queryOptions.connection; - self.state = Cursor.OPEN; - if(err != null && result == null) return callback(utils.toError(err), null); - - if(err == null && (result == null || result.documents == null || !Array.isArray(result.documents))) { - return self.close(function() {callback(new Error("command failed to return results"), null);}); - } - - if(err == null && result && result.documents[0] && result.documents[0]['$err']) { - return self.close(function() {callback(utils.toError(result.documents[0]['$err']), null);}); - } - - if(err == null && result && result.documents[0] && result.documents[0]['errmsg']) { - return self.close(function() {callback(utils.toError(result.documents[0]), null);}); - } - - self.queryRun = true; - self.state = Cursor.OPEN; // Adjust the state of the cursor - self.cursorId = result.cursorId; - self.totalNumberOfRecords = result.numberReturned; - - // Add the new documents to the list of items, using forloop to avoid - // new array allocations and copying - for(var i = 0; i < result.documents.length; i++) { - self.items.push(result.documents[i]); - } - - // If we have noReturn set just return (not modifying the internal item list) - // used for toArray - if(options.noReturn) { - return callback(null, true); - } - - // Ignore callbacks until the cursor is dead for exhausted - if(self.exhaust && result.cursorId.toString() == "0") { - self.nextObject(callback); - } else if(self.exhaust == false || self.exhaust == null) { - self.nextObject(callback); - } - }; - - // If we have no connection set on this cursor check one out - if(self.connection == null) { - try { - self.connection = self.db.serverConfig.checkoutReader(this.read); - // Add to the query options - queryOptions.connection = self.connection; - } catch(err) { - return callback(utils.toError(err), null); - } - } - - // Execute the command - self.db._executeQueryCommand(cmd, queryOptions, commandHandler); - // Set the command handler to null - commandHandler = null; - } else if(self.items.length) { - callback(null, self.items.shift()); - } else if(self.cursorId.greaterThan(Long.fromInt(0))) { - getMore(self, callback); - } else { - // Force cursor to stay open - return self.close(function() {callback(null, null);}); - } -} - -/** - * Gets more results from the database if any. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results. - * @ignore - * @api private - */ -var getMore = function(self, options, callback) { - var limit = 0; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - if(self.state == Cursor.GET_MORE) return callback(null, null); - - // Set get more in progress - self.state = Cursor.GET_MORE; - - // Set options - if (!self.tailable && self.limitValue > 0) { - limit = self.limitValue - self.totalNumberOfRecords; - if (limit < 1) { - self.close(function() {callback(null, null);}); - return; - } - } - - try { - var getMoreCommand = new GetMoreCommand( - self.db - , self.collectionName - , limitRequest(self) - , self.cursorId - ); - - // Set up options - var command_options = {read: self.read, raw: self.raw, connection:self.connection }; - - // Execute the command - self.db._executeQueryCommand(getMoreCommand, command_options, function(err, result) { - var cbValue; - - // Get more done - self.state = Cursor.OPEN; - - if(err != null) { - self.state = Cursor.CLOSED; - return callback(utils.toError(err), null); - } - - // Ensure we get a valid result - if(!result || !result.documents) { - self.state = Cursor.CLOSED; - return callback(utils.toError("command failed to return results"), null) - } - - // If the QueryFailure flag is set - if((result.responseFlag & (1 << 1)) != 0) { - self.state = Cursor.CLOSED; - return callback(utils.toError("QueryFailure flag set on getmore command"), null); - } - - try { - var isDead = 1 === result.responseFlag && result.cursorId.isZero(); - - self.cursorId = result.cursorId; - self.totalNumberOfRecords += result.numberReturned; - - // Determine if there's more documents to fetch - if(result.numberReturned > 0) { - if (self.limitValue > 0) { - var excessResult = self.totalNumberOfRecords - self.limitValue; - - if (excessResult > 0) { - result.documents.splice(-1 * excessResult, excessResult); - } - } - - // Reset the tries for awaitdata if we are using it - self.currentNumberOfRetries = self.numberOfRetries; - // Get the documents - for(var i = 0; i < result.documents.length; i++) { - self.items.push(result.documents[i]); - } - - // Don's shift a document out as we need it for toArray - if(options.noReturn) { - cbValue = true; - } else { - cbValue = self.items.shift(); - } - } else if(self.tailable && !isDead && self.awaitdata) { - // Excute the tailable cursor once more, will timeout after ~4 sec if awaitdata used - self.currentNumberOfRetries = self.currentNumberOfRetries - 1; - if(self.currentNumberOfRetries == 0) { - self.close(function() { - callback(new Error("tailable cursor timed out"), null); - }); - } else { - getMore(self, callback); - } - } else if(self.tailable && !isDead) { - self.getMoreTimer = setTimeout(function() { getMore(self, callback); }, self.tailableRetryInterval); - } else { - self.close(function() {callback(null, null); }); - } - - result = null; - } catch(err) { - callback(utils.toError(err), null); - } - if (cbValue != null) callback(null, cbValue); - }); - - getMoreCommand = null; - } catch(err) { - // Get more done - self.state = Cursor.OPEN; - - var handleClose = function() { - callback(utils.toError(err), null); - }; - - self.close(handleClose); - handleClose = null; - } -} - -/** - * Gets a detailed information about how the query is performed on this cursor and how - * long it took the database to process it. - * - * @param {Function} callback this will be called after executing this method. The first parameter will always be null while the second parameter will be an object containing the details. - * @api public - */ -Cursor.prototype.explain = function(callback) { - var limit = (-1)*Math.abs(this.limitValue); - - // Create a new cursor and fetch the plan - var cursor = new Cursor(this.db, this.collection, this.selector, this.fields, { - skip: this.skipValue - , limit:limit - , sort: this.sortValue - , hint: this.hint - , explain: true - , snapshot: this.snapshot - , timeout: this.timeout - , tailable: this.tailable - , batchSize: this.batchSizeValue - , slaveOk: this.slaveOk - , raw: this.raw - , read: this.read - , returnKey: this.returnKey - , maxScan: this.maxScan - , min: this.min - , max: this.max - , showDiskLoc: this.showDiskLoc - , comment: this.comment - , awaitdata: this.awaitdata - , oplogReplay: this.oplogReplay - , numberOfRetries: this.numberOfRetries - , dbName: this.dbName - }); - - // Fetch the explaination document - cursor.nextObject(function(err, item) { - if(err != null) return callback(utils.toError(err), null); - // close the cursor - cursor.close(function(err, result) { - if(err != null) return callback(utils.toError(err), null); - callback(null, item); - }); - }); -}; - -/** - * Returns a Node ReadStream interface for this cursor. - * - * Options - * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting. - * - * @return {CursorStream} returns a stream object. - * @api public - */ -Cursor.prototype.stream = function stream(options) { - return new CursorStream(this, options); -} - -/** - * Close the cursor. - * - * @param {Function} callback this will be called after executing this method. The first parameter will always contain null while the second parameter will contain a reference to this cursor. - * @return {null} - * @api public - */ -Cursor.prototype.close = function(callback) { - var self = this - this.getMoreTimer && clearTimeout(this.getMoreTimer); - // Close the cursor if not needed - if(this.cursorId instanceof Long && this.cursorId.greaterThan(Long.fromInt(0))) { - try { - var command = new KillCursorCommand(this.db, [this.cursorId]); - // Added an empty callback to ensure we don't throw any null exceptions - this.db._executeQueryCommand(command, {read:self.read, raw:self.raw, connection:self.connection}); - } catch(err) {} - } - - // Null out the connection - self.connection = null; - // Reset cursor id - this.cursorId = Long.fromInt(0); - // Set to closed status - this.state = Cursor.CLOSED; - - if(callback) { - callback(null, self); - self.items = []; - } - - return this; -}; - -/** - * Check if the cursor is closed or open. - * - * @return {Boolean} returns the state of the cursor. - * @api public - */ -Cursor.prototype.isClosed = function() { - return this.state == Cursor.CLOSED ? true : false; -}; - -/** - * Init state - * - * @classconstant INIT - **/ -Cursor.INIT = 0; - -/** - * Cursor open - * - * @classconstant OPEN - **/ -Cursor.OPEN = 1; - -/** - * Cursor closed - * - * @classconstant CLOSED - **/ -Cursor.CLOSED = 2; - -/** - * Cursor performing a get more - * - * @classconstant OPEN - **/ -Cursor.GET_MORE = 3; - -/** - * @ignore - * @api private - */ -exports.Cursor = Cursor; diff --git a/node_modules/mongodb/lib/mongodb/cursorstream.js b/node_modules/mongodb/lib/mongodb/cursorstream.js deleted file mode 100644 index 90b425b96..000000000 --- a/node_modules/mongodb/lib/mongodb/cursorstream.js +++ /dev/null @@ -1,164 +0,0 @@ -var timers = require('timers'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Module dependecies. - */ -var Stream = require('stream').Stream; - -/** - * CursorStream - * - * Returns a stream interface for the **cursor**. - * - * Options - * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting. - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - **close** {function() {}} the end event triggers when there is no more documents available. - * - * @class Represents a CursorStream. - * @param {Cursor} cursor a cursor object that the stream wraps. - * @return {Stream} - */ -function CursorStream(cursor, options) { - if(!(this instanceof CursorStream)) return new CursorStream(cursor); - options = options ? options : {}; - - Stream.call(this); - - this.readable = true; - this.paused = false; - this._cursor = cursor; - this._destroyed = null; - this.options = options; - - // give time to hook up events - var self = this; - process.nextTick(function() { - self._init(); - }); -} - -/** - * Inherit from Stream - * @ignore - * @api private - */ -CursorStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - */ -CursorStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - */ -CursorStream.prototype.paused; - -/** - * Initialize the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._init = function () { - if (this._destroyed) return; - this._next(); -} - -/** - * Pull the next document from the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._next = function () { - if(this.paused || this._destroyed) return; - - var self = this; - // Get the next object - processor(function() { - if(self.paused || self._destroyed) return; - - self._cursor.nextObject(function (err, doc) { - self._onNextObject(err, doc); - }); - }); -} - -/** - * Handle each document as its returned from the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._onNextObject = function (err, doc) { - if(err) return this.destroy(err); - - // when doc is null we hit the end of the cursor - if(!doc && (this._cursor.state == 1 || this._cursor.state == 2)) { - this.emit('end') - return this.destroy(); - } else if(doc) { - var data = typeof this.options.transform == 'function' ? this.options.transform(doc) : doc; - this.emit('data', data); - this._next(); - } -} - -/** - * Pauses the stream. - * - * @api public - */ -CursorStream.prototype.pause = function () { - this.paused = true; -} - -/** - * Resumes the stream. - * - * @api public - */ -CursorStream.prototype.resume = function () { - var self = this; - - // Don't do anything if we are not paused - if(!this.paused) return; - if(!this._cursor.state == 3) return; - - process.nextTick(function() { - self.paused = false; - // Only trigger more fetching if the cursor is open - self._next(); - }) -} - -/** - * Destroys the stream, closing the underlying - * cursor. No more events will be emitted. - * - * @api public - */ -CursorStream.prototype.destroy = function (err) { - if (this._destroyed) return; - this._destroyed = true; - this.readable = false; - - this._cursor.close(); - - if(err) { - this.emit('error', err); - } - - this.emit('close'); -} - -// TODO - maybe implement the raw option to pass binary? -//CursorStream.prototype.setEncoding = function () { -//} - -module.exports = exports = CursorStream; diff --git a/node_modules/mongodb/lib/mongodb/db.js b/node_modules/mongodb/lib/mongodb/db.js deleted file mode 100644 index ebf7a037c..000000000 --- a/node_modules/mongodb/lib/mongodb/db.js +++ /dev/null @@ -1,2086 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var QueryCommand = require('./commands/query_command').QueryCommand - , DbCommand = require('./commands/db_command').DbCommand - , MongoReply = require('./responses/mongo_reply').MongoReply - , Admin = require('./admin').Admin - , Collection = require('./collection').Collection - , Server = require('./connection/server').Server - , ReplSet = require('./connection/repl_set/repl_set').ReplSet - , ReadPreference = require('./connection/read_preference').ReadPreference - , Mongos = require('./connection/mongos').Mongos - , Cursor = require('./cursor').Cursor - , EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , crypto = require('crypto') - , timers = require('timers') - , utils = require('./utils') - - // Authentication methods - , mongodb_cr_authenticate = require('./auth/mongodb_cr.js').authenticate - , mongodb_gssapi_authenticate = require('./auth/mongodb_gssapi.js').authenticate - , mongodb_sspi_authenticate = require('./auth/mongodb_sspi.js').authenticate - , mongodb_plain_authenticate = require('./auth/mongodb_plain.js').authenticate - , mongodb_x509_authenticate = require('./auth/mongodb_x509.js').authenticate; - -var hasKerberos = false; -// Check if we have a the kerberos library -try { - require('kerberos'); - hasKerberos = true; -} catch(err) {} - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Create a new Db instance. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **native_parser** {Boolean, default:false}, use c++ bson parser. - * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **serializeFunctions** {Boolean, default:false}, serialize functions. - * - **raw** {Boolean, default:false}, perform operations using raw bson buffers. - * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution. - * - **retryMiliSeconds** {Number, default:5000}, number of milliseconds between retries. - * - **numberOfRetries** {Number, default:5}, number of retries off connection. - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **slaveOk** {Number, default:null}, force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server). - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - **bufferMaxEntries** {Boolean, default: -1}, sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @class Represents a Db - * @param {String} databaseName name of the database. - * @param {Object} serverConfig server config object. - * @param {Object} [options] additional options for the collection. - */ -function Db(databaseName, serverConfig, options) { - if(!(this instanceof Db)) return new Db(databaseName, serverConfig, options); - EventEmitter.call(this); - var self = this; - this.databaseName = databaseName; - this.serverConfig = serverConfig; - this.options = options == null ? {} : options; - // State to check against if the user force closed db - this._applicationClosed = false; - // Fetch the override flag if any - var overrideUsedFlag = this.options['override_used_flag'] == null ? false : this.options['override_used_flag']; - - // Verify that nobody is using this config - if(!overrideUsedFlag && this.serverConfig != null && typeof this.serverConfig == 'object' && this.serverConfig._isUsed && this.serverConfig._isUsed()) { - throw new Error('A Server or ReplSet instance cannot be shared across multiple Db instances'); - } else if(!overrideUsedFlag && typeof this.serverConfig == 'object'){ - // Set being used - this.serverConfig._used = true; - } - - // Allow slaveOk override - this.slaveOk = this.options['slave_ok'] == null ? false : this.options['slave_ok']; - this.slaveOk = this.options['slaveOk'] == null ? this.slaveOk : this.options['slaveOk']; - - // Number of operations to buffer before failure - this.bufferMaxEntries = typeof this.options['bufferMaxEntries'] == 'number' ? this.options['bufferMaxEntries'] : -1; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Contains all the connections for the db - try { - this.native_parser = this.options.native_parser; - // The bson lib - var bsonLib = this.bsonLib = this.options.native_parser ? require('bson').BSONNative : require('bson').BSONPure; - // Fetch the serializer object - var BSON = bsonLib.BSON; - - // Create a new instance - this.bson = new BSON([bsonLib.Long, bsonLib.ObjectID, bsonLib.Binary, bsonLib.Code, bsonLib.DBRef, bsonLib.Symbol, bsonLib.Double, bsonLib.Timestamp, bsonLib.MaxKey, bsonLib.MinKey]); - this.bson.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs; - - // Backward compatibility to access types - this.bson_deserializer = bsonLib; - this.bson_serializer = bsonLib; - - // Add any overrides to the serializer and deserializer - this.bson_deserializer.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs; - } catch (err) { - // If we tried to instantiate the native driver - var msg = 'Native bson parser not compiled, please compile ' - + 'or avoid using native_parser=true'; - throw Error(msg); - } - - // Internal state of the server - this._state = 'disconnected'; - - this.pkFactory = this.options.pk == null ? bsonLib.ObjectID : this.options.pk; - this.forceServerObjectId = this.options.forceServerObjectId != null ? this.options.forceServerObjectId : false; - - // Added safe - this.safe = this.options.safe == null ? false : this.options.safe; - - // If we have not specified a "safe mode" we just print a warning to the console - if(this.options.safe == null && this.options.w == null && this.options.journal == null && this.options.fsync == null) { - console.log("========================================================================================"); - console.log("= Please ensure that you set the default write concern for the database by setting ="); - console.log("= one of the options ="); - console.log("= ="); - console.log("= w: (value of > -1 or the string 'majority'), where < 1 means ="); - console.log("= no write acknowledgement ="); - console.log("= journal: true/false, wait for flush to journal before acknowledgement ="); - console.log("= fsync: true/false, wait for flush to file system before acknowledgement ="); - console.log("= ="); - console.log("= For backward compatibility safe is still supported and ="); - console.log("= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] ="); - console.log("= the default value is false which means the driver receives does not ="); - console.log("= return the information of the success/error of the insert/update/remove ="); - console.log("= ="); - console.log("= ex: new Db(new Server('localhost', 27017), {safe:false}) ="); - console.log("= ="); - console.log("= http://www.mongodb.org/display/DOCS/getLastError+Command ="); - console.log("= ="); - console.log("= The default of no acknowledgement will change in the very near future ="); - console.log("= ="); - console.log("= This message will disappear when the default safe is set on the driver Db ="); - console.log("========================================================================================"); - } - - // Internal states variables - this.notReplied ={}; - this.isInitializing = true; - this.openCalled = false; - - // Command queue, keeps a list of incoming commands that need to be executed once the connection is up - this.commands = []; - - // Set up logger - this.logger = this.options.logger != null - && (typeof this.options.logger.debug == 'function') - && (typeof this.options.logger.error == 'function') - && (typeof this.options.logger.log == 'function') - ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Associate the logger with the server config - this.serverConfig.logger = this.logger; - if(this.serverConfig.strategyInstance) this.serverConfig.strategyInstance.logger = this.logger; - this.tag = new Date().getTime(); - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[]}; - - // Controls serialization options - this.serializeFunctions = this.options.serializeFunctions != null ? this.options.serializeFunctions : false; - - // Raw mode - this.raw = this.options.raw != null ? this.options.raw : false; - - // Record query stats - this.recordQueryStats = this.options.recordQueryStats != null ? this.options.recordQueryStats : false; - - // If we have server stats let's make sure the driver objects have it enabled - if(this.recordQueryStats == true) { - this.serverConfig.enableRecordQueryStats(true); - } - - // Retry information - this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 1000; - this.numberOfRetries = this.options.numberOfRetries != null ? this.options.numberOfRetries : 60; - - // Set default read preference if any - this.readPreference = this.options.readPreference; - - // Set read preference on serverConfig if none is set - // but the db one was - if(this.serverConfig.options.readPreference == null - && this.readPreference != null) { - this.serverConfig.setReadPreference(this.readPreference); - } - - // Ensure we keep a reference to this db - this.serverConfig._dbStore.add(this); -}; - -/** - * @ignore - */ -function validateDatabaseName(databaseName) { - if(typeof databaseName !== 'string') throw new Error("database name must be a string"); - if(databaseName.length === 0) throw new Error("database name cannot be the empty string"); - if(databaseName == '$external') return; - - var invalidChars = [" ", ".", "$", "/", "\\"]; - for(var i = 0; i < invalidChars.length; i++) { - if(databaseName.indexOf(invalidChars[i]) != -1) throw new Error("database names cannot contain the character '" + invalidChars[i] + "'"); - } -} - -/** - * @ignore - */ -inherits(Db, EventEmitter); - -/** - * Initialize the database connection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the index information or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.open = function(callback) { - var self = this; - - // Check that the user has not called this twice - if(this.openCalled) { - // Close db - this.close(); - // Throw error - throw new Error("db object already connecting, open cannot be called multiple times"); - } - - // If we have a specified read preference - if(this.readPreference != null) this.serverConfig.setReadPreference(this.readPreference); - - // Set that db has been opened - this.openCalled = true; - - // Set the status of the server - self._state = 'connecting'; - - // Set up connections - if(self.serverConfig instanceof Server || self.serverConfig instanceof ReplSet || self.serverConfig instanceof Mongos) { - // Ensure we have the original options passed in for the server config - var connect_options = {}; - for(var name in self.serverConfig.options) { - connect_options[name] = self.serverConfig.options[name] - } - connect_options.firstCall = true; - - // Attempt to connect - self.serverConfig.connect(self, connect_options, function(err, result) { - if(err != null) { - // Close db to reset connection - return self.close(function () { - // Return error from connection - return callback(err, null); - }); - } - // Set the status of the server - self._state = 'connected'; - // If we have queued up commands execute a command to trigger replays - if(self.commands.length > 0) _execute_queued_command(self); - // Callback - process.nextTick(function() { - try { - callback(null, self); - } catch(err) { - self.close(); - throw err; - } - }); - }); - } else { - try { - callback(Error("Server parameter must be of type Server, ReplSet or Mongos"), null); - } catch(err) { - self.close(); - throw err; - } - } -}; - -/** - * Create a new Db instance sharing the current socket connections. - * - * @param {String} dbName the name of the database we want to use. - * @return {Db} a db instance using the new database. - * @api public - */ -Db.prototype.db = function(dbName) { - // Copy the options and add out internal override of the not shared flag - var options = {}; - for(var key in this.options) { - options[key] = this.options[key]; - } - - // Add override flag - options['override_used_flag'] = true; - // Check if the db already exists and reuse if it's the case - var db = this.serverConfig._dbStore.fetch(dbName); - - // Create a new instance - if(!db) { - db = new Db(dbName, this.serverConfig, options); - } - - // Return the db object - return db; -}; - -/** - * Close the current db connection, including all the child db instances. Emits close event if no callback is provided. - * - * @param {Boolean} [forceClose] connection can never be reused. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.close = function(forceClose, callback) { - var self = this; - // Ensure we force close all connections - this._applicationClosed = false; - - if(typeof forceClose == 'function') { - callback = forceClose; - } else if(typeof forceClose == 'boolean') { - this._applicationClosed = forceClose; - } - - this.serverConfig.close(function(err, result) { - // You can reuse the db as everything is shut down - self.openCalled = false; - // If we have a callback call it - if(callback) callback(err, result); - }); -}; - -/** - * Access the Admin database - * - * @param {Function} [callback] returns the results. - * @return {Admin} the admin db object. - * @api public - */ -Db.prototype.admin = function(callback) { - if(callback == null) return new Admin(this); - callback(null, new Admin(this)); -}; - -/** - * Returns a cursor to all the collection information. - * - * @param {String} [collectionName] the collection name we wish to retrieve the information from. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the options or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.collectionsInfo = function(collectionName, callback) { - if(callback == null && typeof collectionName == 'function') { callback = collectionName; collectionName = null; } - // Create selector - var selector = {}; - // If we are limiting the access to a specific collection name - if(collectionName != null) selector.name = this.databaseName + "." + collectionName; - - // Return Cursor - // callback for backward compatibility - if(callback) { - callback(null, new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector)); - } else { - return new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector); - } -}; - -/** - * Get the list of all collection names for the specified db - * - * Options - * - **namesOnly** {String, default:false}, Return only the full collection namespace. - * - * @param {String} [collectionName] the collection name we wish to filter by. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection names or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.collectionNames = function(collectionName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - collectionName = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Ensure no breaking behavior - if(collectionName != null && typeof collectionName == 'object') { - options = collectionName; - collectionName = null; - } - - // Let's make our own callback to reuse the existing collections info method - self.collectionsInfo(collectionName, function(err, cursor) { - if(err != null) return callback(err, null); - - cursor.toArray(function(err, documents) { - if(err != null) return callback(err, null); - - // List of result documents that have been filtered - var filtered_documents = documents.filter(function(document) { - return !(document.name.indexOf(self.databaseName) == -1 || document.name.indexOf('$') != -1); - }); - - // If we are returning only the names - if(options.namesOnly) { - filtered_documents = filtered_documents.map(function(document) { return document.name }); - } - - // Return filtered items - callback(null, filtered_documents); - }); - }); -}; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can - * can use it without a callback in the following way. var collection = db.collection('mycollection'); - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strict**, (Boolean, default:false) returns an error if the collection does not exist - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName the collection name we wish to access. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collection or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.collection = function(collectionName, options, callback) { - var self = this; - if(typeof options === "function") { callback = options; options = {}; } - // Execute safe - - if(options && (options.strict)) { - self.collectionNames(collectionName, function(err, collections) { - if(err != null) return callback(err, null); - - if(collections.length == 0) { - return callback(new Error("Collection " + collectionName + " does not exist. Currently in safe mode."), null); - } else { - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - return callback(err, null); - } - return callback(null, collection); - } - }); - } else { - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - if(callback == null) { - throw err; - } else { - return callback(err, null); - } - } - - // If we have no callback return collection object - return callback == null ? collection : callback(null, collection); - } -}; - -/** - * Fetch all collections for the current db. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the collections or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.collections = function(callback) { - var self = this; - // Let's get the collection names - self.collectionNames(function(err, documents) { - if(err != null) return callback(err, null); - var collections = []; - documents.forEach(function(document) { - collections.push(new Collection(self, document.name.replace(self.databaseName + ".", ''), self.pkFactory)); - }); - // Return the collection objects - callback(null, collections); - }); -}; - -/** - * Evaluate javascript on the server - * - * Options - * - **nolock** {Boolean, default:false}, Tell MongoDB not to block on the evaulation of the javascript. - * - * @param {Code} code javascript to execute on server. - * @param {Object|Array} [parameters] the parameters for the call. - * @param {Object} [options] the options - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from eval or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.eval = function(code, parameters, options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - var finalCode = code; - var finalParameters = []; - // If not a code object translate to one - if(!(finalCode instanceof this.bsonLib.Code)) { - finalCode = new this.bsonLib.Code(finalCode); - } - - // Ensure the parameters are correct - if(parameters != null && parameters.constructor != Array && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if(parameters != null && parameters.constructor == Array && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - var selector = {'$eval':finalCode, 'args':finalParameters}; - // Check if the nolock parameter is passed in - if(options['nolock']) { - selector['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = ReadPreference.PRIMARY; - - // Execute the eval - this.collection(DbCommand.SYSTEM_COMMAND_COLLECTION).findOne(selector, options, function(err, result) { - if(err) return callback(err); - - if(result && result.ok == 1) { - callback(null, result.retval); - } else if(result) { - callback(new Error("eval failed: " + result.errmsg), null); return; - } else { - callback(err, result); - } - }); -}; - -/** - * Dereference a dbref, against a db - * - * @param {DBRef} dbRef db reference object we wish to resolve. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dereference or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.dereference = function(dbRef, callback) { - var db = this; - // If we have a db reference then let's get the db first - if(dbRef.db != null) db = this.db(dbRef.db); - // Fetch the collection and find the reference - var collection = db.collection(dbRef.namespace); - collection.findOne({'_id':dbRef.oid}, function(err, result) { - callback(err, result); - }); -}; - -/** - * Logout user from server, fire off on all connections and remove all auth info - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from logout or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.logout = function(options, callback) { - var self = this; - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Number of connections we need to logout from - var numberOfConnections = this.serverConfig.allRawConnections().length; - - // Let's generate the logout command object - var logoutCommand = DbCommand.logoutCommand(self, {logout:1}, options); - self._executeQueryCommand(logoutCommand, {onAll:true}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - // Remove the db from auths - self.serverConfig.auth.remove(self.databaseName); - - // Handle error result - utils.handleSingleCommandResultReturn(true, false, internalCallback)(err, result); - } - }); -}; - -/** - * Authenticate a user against the server. - * authMechanism - * Options - * - **authMechanism** {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR - * - * @param {String} username username. - * @param {String} password password. - * @param {Object} [options] the options - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from authentication or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.authenticate = function(username, password, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Set default mechanism - if(!options.authMechanism) { - options.authMechanism = 'MONGODB-CR'; - } else if(options.authMechanism != 'GSSAPI' - && options.authMechanism != 'MONGODB-CR' - && options.authMechanism != 'MONGODB-X509' - && options.authMechanism != 'PLAIN') { - return callback(new Error("only GSSAPI, PLAIN, MONGODB-X509 or MONGODB-CR is supported by authMechanism")); - } - - // the default db to authenticate against is 'this' - // if authententicate is called from a retry context, it may be another one, like admin - var authdb = options.authdb ? options.authdb : self.databaseName; - authdb = options.authSource ? options.authSource : authdb; - - // Callback - var _callback = function(err, result) { - if(self.listeners("authenticated").length > 9) { - self.emit("authenticated", err, result); - } - - // Return to caller - callback(err, result); - } - - // If classic auth delegate to auth command - if(options.authMechanism == 'MONGODB-CR') { - mongodb_cr_authenticate(self, username, password, authdb, options, _callback); - } else if(options.authMechanism == 'PLAIN') { - mongodb_plain_authenticate(self, username, password, options, _callback); - } else if(options.authMechanism == 'MONGODB-X509') { - mongodb_x509_authenticate(self, username, password, options, _callback); - } else if(options.authMechanism == 'GSSAPI') { - // - // Kerberos library is not installed, throw and error - if(hasKerberos == false) { - console.log("========================================================================================"); - console.log("= Please make sure that you install the Kerberos library to use GSSAPI ="); - console.log("= ="); - console.log("= npm install -g kerberos ="); - console.log("= ="); - console.log("= The Kerberos package is not installed by default for simplicities sake ="); - console.log("= and needs to be global install ="); - console.log("========================================================================================"); - throw new Error("Kerberos library not installed"); - } - - if(process.platform == 'win32') { - mongodb_sspi_authenticate(self, username, password, authdb, options, _callback); - } else { - // We have the kerberos library, execute auth process - mongodb_gssapi_authenticate(self, username, password, authdb, options, _callback); - } - } -}; - -/** - * Add a user to the database. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **customData**, (Object, default:{}) custom data associated with the user (only Mongodb 2.6 or higher) - * - **roles**, (Array, default:[]) roles associated with the created user (only Mongodb 2.6 or higher) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username username. - * @param {String} password password. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from addUser or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.addUser = function(username, password, options, callback) { - // Checkout a write connection to get the server capabilities - var connection = this.serverConfig.checkoutWriter(); - if(connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasAuthCommands) { - return _executeAuthCreateUserCommand(this, username, password, options, callback); - } - - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Get the error options - var errorOptions = _getWriteConcern(this, options); - errorOptions.w = errorOptions.w == null ? 1 : errorOptions.w; - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - // Fetch a user collection - var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION); - // Check if we are inserting the first user - collection.count({}, function(err, count) { - // We got an error (f.ex not authorized) - if(err != null) return callback(err, null); - // Check if the user exists and update i - collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { - // We got an error (f.ex not authorized) - if(err != null) return callback(err, null); - // Add command keys - var commandOptions = errorOptions; - commandOptions.dbName = options['dbName']; - commandOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - collection.update({user: username},{$set: {user: username, pwd: userPassword}}, commandOptions, function(err, results, full) { - if(count == 0 && err) { - callback(null, [{user:username, pwd:userPassword}]); - } else if(err) { - callback(err, null) - } else { - callback(null, [{user:username, pwd:userPassword}]); - } - }); - }); - }); -}; - -/** - * @ignore - */ -var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { - // Special case where there is no password ($external users) - if(typeof username == 'string' - && password != null && typeof password == 'object') { - callback = options; - options = password; - password = null; - } - - // Unpack all options - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Error out if we digestPassword set - if(options.digestPassword != null) { - throw utils.toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); - } - - // Get additional values - var customData = options.customData != null ? options.customData : {}; - var roles = Array.isArray(options.roles) ? options.roles : []; - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // If not roles defined print deprecated message - if(roles.length == 0) { - console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); - } - - // Get the error options - var writeConcern = _getWriteConcern(self, options); - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Check the db name and add roles if needed - if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { - roles = ['root'] - } else if(!Array.isArray(options.roles)) { - roles = ['dbOwner'] - } - - // Build the command to execute - var command = { - createUser: username - , customData: customData - , roles: roles - , digestPassword:false - , writeConcern: writeConcern - } - - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - - // No password - if(typeof password == 'string') { - command.pwd = userPassword; - } - - // console.log("================================== add user") - // console.dir(command) - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err) return callback(err, null); - callback(!result.ok ? utils.toError("Failed to add user " + username) : null - , result.ok ? [{user: username, pwd: ''}] : null); - }) -} - -/** - * Remove a user from a database - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username username. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.removeUser = function(username, options, callback) { - // Checkout a write connection to get the server capabilities - var connection = this.serverConfig.checkoutWriter(); - if(connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasAuthCommands) { - return _executeAuthRemoveUserCommand(this, username, options, callback); - } - - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Figure out the safe mode settings - var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe; - // Override with options passed in if applicable - safe = options != null && options['safe'] != null ? options['safe'] : safe; - // Ensure it's at least set to safe - safe = safe == null ? {w: 1} : safe; - - // Fetch a user collection - var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION); - collection.findOne({user: username}, {dbName: options['dbName']}, function(err, user) { - if(user != null) { - // Add command keys - var commandOptions = safe; - commandOptions.dbName = options['dbName']; - - collection.remove({user: username}, commandOptions, function(err, result) { - callback(err, true); - }); - } else { - callback(err, false); - } - }); -}; - -var _executeAuthRemoveUserCommand = function(self, username, options, callback) { - // Unpack all options - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Get the error options - var writeConcern = _getWriteConcern(self, options); - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Get additional values - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Build the command to execute - var command = { - dropUser: username - , writeConcern: writeConcern - } - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err) return callback(err, null); - callback(null, result.ok ? true : false); - }) -} - -/** - * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **capped** {Boolean, default:false}, create a capped collection. - * - **size** {Number}, the size of the capped collection in bytes. - * - **max** {Number}, the maximum number of documents in the capped collection. - * - **autoIndexId** {Boolean, default:true}, create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strict**, (Boolean, default:false) throws an error if collection already exists - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName the collection name we wish to access. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from createCollection or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.createCollection = function(collectionName, options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Figure out the safe mode settings - var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe; - // Override with options passed in if applicable - safe = options != null && options['safe'] != null ? options['safe'] : safe; - // Ensure it's at least set to safe - safe = safe == null ? {w: 1} : safe; - - // Check if we have the name - this.collectionNames(collectionName, function(err, collections) { - if(err != null) return callback(err, null); - - var found = false; - collections.forEach(function(collection) { - if(collection.name == self.databaseName + "." + collectionName) found = true; - }); - - // If the collection exists either throw an exception (if db in safe mode) or return the existing collection - if(found && options && options.strict) { - return callback(new Error("Collection " + collectionName + " already exists. Currently in safe mode."), null); - } else if(found){ - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - return callback(err, null); - } - return callback(null, collection); - } - - // Create a new collection and return it - self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options) - , {read:false, safe:safe} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - // Create collection and return - try { - return callback(null, new Collection(self, collectionName, self.pkFactory, options)); - } catch(err) { - return callback(err, null); - } - })); - }); -}; - -var _getReadConcern = function(self, options) { - if(options.readPreference) return options.readPreference; - if(self.readPreference) return self.readPreference; - return 'primary'; -} - -/** - * Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server. - * - * Options - * - **maxTimeMS** {Number}, number of miliseconds to wait before aborting the query. - * - **ignoreCommandFilter** {Boolean}, overrides the default redirection of certain commands to primary. - * - **writeCommand** {Boolean, default: false}, signals this is a write command and to ignore read preferences - * - **checkKeys** {Boolean, default: false}, overrides the default not to check the key names for the command - * - * @param {Object} selector the command hash to send to the server, ex: {ping:1}. - * @param {Object} [options] additional options for the command. - * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter. - * @return {null} - * @api public - */ -Db.prototype.command = function(selector, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Ignore command preference (I know what I'm doing) - var ignoreCommandFilter = options.ignoreCommandFilter ? options.ignoreCommandFilter : false; - // Set read preference if we set one - var readPreference = _getReadConcern(this, options); - - // Ensure only commands who support read Prefrences are exeuted otherwise override and use Primary - if(readPreference != false && ignoreCommandFilter == false) { - if(selector['group'] || selector['aggregate'] || selector['collStats'] || selector['dbStats'] - || selector['count'] || selector['distinct'] || selector['geoNear'] || selector['geoSearch'] - || selector['geoWalk'] || selector['text'] - || (selector['mapreduce'] && (selector.out == 'inline' || selector.out.inline))) { - // Set the read preference - options.readPreference = readPreference; - } else { - options.readPreference = ReadPreference.PRIMARY; - } - } else if(readPreference != false) { - options.readPreference = readPreference; - } - - // Add the maxTimeMS option to the command if specified - if(typeof options.maxTimeMS == 'number') { - selector.maxTimeMS = options.maxTimeMS - } - - // Command options - var command_options = {}; - - // Do we have an override for checkKeys - if(typeof options['checkKeys'] == 'boolean') command_options['checkKeys'] = options['checkKeys']; - command_options['checkKeys'] = typeof options['checkKeys'] == 'boolean' ? options['checkKeys'] : false; - if(typeof options['serializeFunctions'] == 'boolean') command_options['serializeFunctions'] = options['serializeFunctions']; - if(options['dbName']) command_options['dbName'] = options['dbName']; - - // If we have a write command, remove readPreference as an option - if((options.writeCommand - || selector['findAndModify'] - || selector['insert'] || selector['update'] || selector['delete'] - || selector['createUser'] || selector['updateUser'] || selector['removeUser']) - && options.readPreference) { - delete options['readPreference']; - } - - // Execute a query command - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, selector, command_options), options, function(err, results) { - if(err) return callback(err, null); - if(results.documents[0].errmsg) - return callback(utils.toError(results.documents[0]), null); - callback(null, results.documents[0]); - }); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @param {String} collectionName the name of the collection we wish to drop. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropCollection or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.dropCollection = function(collectionName, callback) { - var self = this; - callback || (callback = function(){}); - - // Drop the collection - this._executeQueryCommand(DbCommand.createDropCollectionCommand(this, collectionName) - , utils.handleSingleCommandResultReturn(true, false, callback) - ); -}; - -/** - * Rename a collection. - * - * Options - * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists. - * - * @param {String} fromCollection the name of the current collection we wish to rename. - * @param {String} toCollection the new name of the collection. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from renameCollection or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {} - } - - // Add return new collection - options.new_collection = true; - - // Execute using the collection method - this.collection(fromCollection).rename(toCollection, options, callback); -}; - -/** - * Return last error message for the given connection, note options can be combined. - * - * Options - * - **fsync** {Boolean, default:false}, option forces the database to fsync all files before returning. - * - **j** {Boolean, default:false}, awaits the journal commit before returning, > MongoDB 2.0. - * - **w** {Number}, until a write operation has been replicated to N servers. - * - **wtimeout** {Number}, number of miliseconds to wait before timing out. - * - * Connection Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Object} [connectionOptions] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from lastError or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.lastError = function(options, connectionOptions, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - connectionOptions = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createGetLastErrorCommand(options, this), connectionOptions, function(err, error) { - callback(err, error && error.documents); - }); -}; - -/** - * Legacy method calls. - * - * @ignore - * @api private - */ -Db.prototype.error = Db.prototype.lastError; -Db.prototype.lastStatus = Db.prototype.lastError; - -/** - * Return all errors up to the last time db reset_error_history was called. - * - * Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from previousErrors or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.previousErrors = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createGetPreviousErrorsCommand(this), options, function(err, error) { - callback(err, error.documents); - }); -}; - -/** - * Runs a command on the database. - * @ignore - * @api private - */ -Db.prototype.executeDbCommand = function(command_hash, options, callback) { - if(callback == null) { callback = options; options = {}; } - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, command_hash, options), options, function(err, result) { - if(callback) callback(err, result); - }); -}; - -/** - * Runs a command on the database as admin. - * @ignore - * @api private - */ -Db.prototype.executeDbAdminCommand = function(command_hash, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {} - } - - if(options.readPreference) { - options.read = options.readPreference; - } - - this._executeQueryCommand(DbCommand.createAdminDbCommand(this, command_hash), options, function(err, result) { - if(callback) callback(err, result); - }); -}; - -/** - * Resets the error history of the mongo instance. - * - * Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from resetErrorHistory or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.resetErrorHistory = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createResetErrorHistoryCommand(this), options, function(err, error) { - if(callback) callback(err, error && error.documents); - }); -}; - -/** - * Creates an index on the collection. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * - * @param {String} collectionName name of the collection to create the index on. - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from createIndex or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Get the error options - var errorOptions = _getWriteConcern(this, options); - // Create command - var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); - // Default command options - var commandOptions = {}; - - // If we have error conditions set handle them - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute insert command - this._executeInsertCommand(command, commandOptions, function(err, result) { - if(err != null) return callback(err, null); - - result = result && result.documents; - if (result[0].err) { - callback(utils.toError(result[0])); - } else { - callback(null, command.documents[0].name); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute insert command - var result = this._executeInsertCommand(command, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(null, null); - } -}; - -/** - * Ensures that an index exists, if it does not it creates it - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowledgement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName name of the collection to create the index on. - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from ensureIndex or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callback) { - var self = this; - - if (typeof callback === 'undefined' && typeof options === 'function') { - callback = options; - options = {}; - } - - if (options == null) { - options = {}; - } - - // Get the error options - var errorOptions = _getWriteConcern(this, options); - // Make sure we don't try to do a write concern without a callback - if(_hasWriteConcern(errorOptions) && callback == null) - throw new Error("Cannot use a writeConcern without a provided callback"); - // Create command - var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); - var index_name = command.documents[0].name; - - // Default command options - var commandOptions = {}; - // Check if the index allready exists - this.indexInformation(collectionName, function(err, collectionInfo) { - if(err != null) return callback(err, null); - - if(!collectionInfo[index_name]) { - // If we have error conditions set handle them - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - if(typeof callback === 'function' - && commandOptions.w < 1 && !commandOptions.fsync && !commandOptions.journal) { - commandOptions.w = 1; - } - - self._executeInsertCommand(command, commandOptions, function(err, result) { - // Only callback if we have one specified - if(typeof callback === 'function') { - if(err != null) return callback(err, null); - - result = result && result.documents; - if (result[0].err) { - callback(utils.toError(result[0])); - } else { - callback(null, command.documents[0].name); - } - } - }); - } else { - // Execute insert command - var result = self._executeInsertCommand(command, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(null, index_name); - } - } else { - if(typeof callback === 'function') return callback(null, index_name); - } - }); -}; - -/** - * Returns the information available on allocated cursors. - * - * Options - * - **readPreference** {String}, the preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from cursorInfo or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.cursorInfo = function(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, {'cursorInfo':1}) - , options - , utils.handleSingleCommandResultReturn(null, null, callback)); -}; - -/** - * Drop an index on a collection. - * - * @param {String} collectionName the name of the collection where the command will drop an index. - * @param {String} indexName name of the index to drop. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropIndex or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.dropIndex = function(collectionName, indexName, callback) { - this._executeQueryCommand(DbCommand.createDropIndexCommand(this, collectionName, indexName) - , utils.handleSingleCommandResultReturn(null, null, callback)); -}; - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * - * @param {String} collectionName the name of the collection. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from reIndex or null if an error occurred. - * @api public -**/ -Db.prototype.reIndex = function(collectionName, callback) { - this._executeQueryCommand(DbCommand.createReIndexCommand(this, collectionName) - , utils.handleSingleCommandResultReturn(true, false, callback)); -}; - -/** - * Retrieves this collections index info. - * - * Options - * - **full** {Boolean, default:false}, returns the full raw index information. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {String} collectionName the name of the collection. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from indexInformation or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.indexInformation = function(collectionName, options, callback) { - if(typeof callback === 'undefined') { - if(typeof options === 'undefined') { - callback = collectionName; - collectionName = null; - } else { - callback = options; - } - options = {}; - } - - // If we specified full information - var full = options['full'] == null ? false : options['full']; - // Build selector for the indexes - var selector = collectionName != null ? {ns: (this.databaseName + "." + collectionName)} : {}; - - // Set read preference if we set one - var readPreference = options['readPreference'] ? options['readPreference'] : ReadPreference.PRIMARY; - - // Iterate through all the fields of the index - this.collection(DbCommand.SYSTEM_INDEX_COLLECTION, function(err, collection) { - // Perform the find for the collection - collection.find(selector).setReadPreference(readPreference).toArray(function(err, indexes) { - if(err != null) return callback(err, null); - // Contains all the information - var info = {}; - - // if full defined just return all the indexes directly - if(full) return callback(null, indexes); - - // Process all the indexes - for(var i = 0; i < indexes.length; i++) { - var index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for(var name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - // Return all the indexes - callback(null, info); - }); - }); -}; - -/** - * Drop a database. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from dropDatabase or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.dropDatabase = function(callback) { - this._executeQueryCommand(DbCommand.createDropDatabaseCommand(this) - , utils.handleSingleCommandResultReturn(true, false, callback)); -} - -/** - * Get all the db statistics. - * - * Options - * - **scale** {Number}, divide the returned sizes by scale value. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Objects} [options] options for the stats command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the results from stats or null if an error occurred. - * @return {null} - * @api public - */ -Db.prototype.stats = function stats(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - dbStats:this.collectionName - }; - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Execute the command - this.command(commandObject, options, callback); -} - -/** - * @ignore - */ -var __executeQueryCommand = function(self, db_command, options, callback) { - // Options unpacking - var read = options['read'] != null ? options['read'] : false; - read = options['readPreference'] != null && options['read'] == null ? options['readPreference'] : read; - var raw = options['raw'] != null ? options['raw'] : self.raw; - var onAll = options['onAll'] != null ? options['onAll'] : false; - var specifiedConnection = options['connection'] != null ? options['connection'] : null; - - // Correct read preference to default primary if set to false, null or primary - if(!(typeof read == 'object') && read._type == 'ReadPreference') { - read = (read == null || read == 'primary' || read == false) ? ReadPreference.PRIMARY : read; - if(!ReadPreference.isValid(read)) return callback(new Error("Illegal readPreference mode specified, " + read)); - } else if(typeof read == 'object' && read._type == 'ReadPreference') { - if(!read.isValid()) return callback(new Error("Illegal readPreference mode specified, " + read.mode)); - } - - // If we have a read preference set and we are a mongos pass the read preference on to the mongos instance, - if(self.serverConfig.isMongos() && read != null && read != false) { - db_command.setMongosReadPreference(read); - } - - // If we got a callback object - if(typeof callback === 'function' && !onAll) { - // Override connection if we passed in a specific connection - var connection = specifiedConnection != null ? specifiedConnection : null; - - if(connection instanceof Error) return callback(connection, null); - - // Fetch either a reader or writer dependent on the specified read option if no connection - // was passed in - if(connection == null) { - connection = self.serverConfig.checkoutReader(read); - } - - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error || connection['message'] != null) { - return callback(connection); - } - - // Exhaust Option - var exhaust = options.exhaust || false; - - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command, raw, connection, exhaust, callback); - - // Write the message out and handle any errors if there are any - connection.write(db_command, function(err) { - if(err != null) { - // Call the handler with an error - if(Array.isArray(db_command)) - self.serverConfig._callHandler(db_command[0].getRequestId(), null, err); - else - self.serverConfig._callHandler(db_command.getRequestId(), null, err); - } - }); - } else if(typeof callback === 'function' && onAll) { - var connections = self.serverConfig.allRawConnections(); - var numberOfEntries = connections.length; - // Go through all the connections - for(var i = 0; i < connections.length; i++) { - // Fetch a connection - var connection = connections[i]; - - // Ensure we have a valid connection - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error) { - return callback(connection); - } - - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command, raw, connection, callback); - - // Write the message out - connection.write(db_command, function(err) { - // Adjust the number of entries we need to process - numberOfEntries = numberOfEntries - 1; - // Remove listener - if(err != null) { - // Clean up listener and return error - self.serverConfig._removeHandler(db_command.getRequestId()); - } - - // No more entries to process callback with the error - if(numberOfEntries <= 0) { - callback(err); - } - }); - - // Update the db_command request id - db_command.updateRequestId(); - } - } else { - // Fetch either a reader or writer dependent on the specified read option - // var connection = read == null || read == 'primary' || read == false ? self.serverConfig.checkoutWriter(true) : self.serverConfig.checkoutReader(read); - var connection = self.serverConfig.checkoutReader(read); - // Override connection if needed - connection = specifiedConnection != null ? specifiedConnection : connection; - // Ensure we have a valid connection - if(connection == null || connection instanceof Error || connection['message'] != null) return null; - // Write the message out - connection.write(db_command, function(err) { - if(err != null) { - // Emit the error - self.emit("error", err); - } - }); - } -}; - -/** - * Execute db query command (not safe) - * @ignore - * @api private - */ -Db.prototype._executeQueryCommand = function(db_command, options, callback) { - var self = this; - - // Unpack the parameters - if (typeof callback === 'undefined') { - callback = options; - options = {}; - } - - // fast fail option used for HA, no retry - var failFast = options['failFast'] != null - ? options['failFast'] - : false; - - // Check if the user force closed the command - if(this._applicationClosed) { - var err = new Error("db closed by application"); - if('function' == typeof callback) { - return callback(err, null); - } else { - throw err; - } - } - - if(this.serverConfig.isDestroyed()) - return callback(new Error("Connection was destroyed by application")); - - // Specific connection - var connection = options.connection; - // Check if the connection is actually live - if(connection - && (!connection.isConnected || !connection.isConnected())) connection = null; - - // Get the configuration - var config = this.serverConfig; - var read = options.read; - // Allow for the usage of the readPreference model - if(read == null) { - read = options.readPreference; - } - - if(!connection && !config.canRead(read) && !config.canWrite() && config.isAutoReconnect()) { - if(read == ReadPreference.PRIMARY - || read == ReadPreference.PRIMARY_PREFERRED - || (read != null && typeof read == 'object' && read.mode) - || read == null) { - - // Save the command - self.serverConfig._commandsStore.read_from_writer( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } else { - self.serverConfig._commandsStore.read( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } - - // If we have blown through the number of items let's - if(!self.serverConfig._commandsStore.validateBufferLimit(self.bufferMaxEntries)) { - self.close(); - } - } else if(!connection && !config.canRead(read) && !config.canWrite() && !config.isAutoReconnect()) { - return callback(new Error("no open connections"), null); - } else { - if(typeof callback == 'function') { - __executeQueryCommand(self, db_command, options, function (err, result, conn) { - callback(err, result, conn); - }); - } else { - __executeQueryCommand(self, db_command, options); - } - } -}; - -/** - * @ignore - */ -var __executeInsertCommand = function(self, db_command, options, callback) { - // Always checkout a writer for this kind of operations - var connection = self.serverConfig.checkoutWriter(); - // Get safe mode - var safe = options['safe'] != null ? options['safe'] : false; - var raw = options['raw'] != null ? options['raw'] : self.raw; - var specifiedConnection = options['connection'] != null ? options['connection'] : null; - // Override connection if needed - connection = specifiedConnection != null ? specifiedConnection : connection; - - // Validate if we can use this server 2.6 wire protocol - if(!connection.isCompatible()) { - return callback(utils.toError("driver is incompatible with this server version"), null); - } - - // Ensure we have a valid connection - if(typeof callback === 'function') { - // Ensure we have a valid connection - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error) { - return callback(connection); - } - - var errorOptions = _getWriteConcern(self, options); - if(errorOptions.w > 0 || errorOptions.w == 'majority' || errorOptions.j || errorOptions.journal || errorOptions.fsync) { - // db command is now an array of commands (original command + lastError) - db_command = [db_command, DbCommand.createGetLastErrorCommand(safe, self)]; - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command[1], raw, connection, callback); - } - } - - // If we have no callback and there is no connection - if(connection == null) return null; - if(connection instanceof Error && typeof callback == 'function') return callback(connection, null); - if(connection instanceof Error) return null; - if(connection == null && typeof callback == 'function') return callback(new Error("no primary server found"), null); - - // Write the message out - connection.write(db_command, function(err) { - // Return the callback if it's not a safe operation and the callback is defined - if(typeof callback === 'function' && (safe == null || safe == false)) { - // Perform the callback - callback(err, null); - } else if(typeof callback === 'function') { - // Call the handler with an error - self.serverConfig._callHandler(db_command[1].getRequestId(), null, err); - } else if(typeof callback == 'function' && safe && safe.w == -1) { - // Call the handler with no error - self.serverConfig._callHandler(db_command[1].getRequestId(), null, null); - } else if(!safe || safe.w == -1) { - self.emit("error", err); - } - }); -}; - -/** - * Execute an insert Command - * @ignore - * @api private - */ -Db.prototype._executeInsertCommand = function(db_command, options, callback) { - var self = this; - - // Unpack the parameters - if(callback == null && typeof options === 'function') { - callback = options; - options = {}; - } - - // Ensure options are not null - options = options == null ? {} : options; - - // Check if the user force closed the command - if(this._applicationClosed) { - if(typeof callback == 'function') { - return callback(new Error("db closed by application"), null); - } else { - throw new Error("db closed by application"); - } - } - - if(this.serverConfig.isDestroyed()) return callback(new Error("Connection was destroyed by application")); - - // Specific connection - var connection = options.connection; - // Check if the connection is actually live - if(connection - && (!connection.isConnected || !connection.isConnected())) connection = null; - - // Get config - var config = self.serverConfig; - // Check if we are connected - if(!connection && !config.canWrite() && config.isAutoReconnect()) { - self.serverConfig._commandsStore.write( - { type:'insert' - , 'db_command':db_command - , 'options':options - , 'callback':callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - - // If we have blown through the number of items let's - if(!self.serverConfig._commandsStore.validateBufferLimit(self.bufferMaxEntries)) { - self.close(); - } - } else if(!connection && !config.canWrite() && !config.isAutoReconnect()) { - return callback(new Error("no open connections"), null); - } else { - __executeInsertCommand(self, db_command, options, callback); - } -}; - -/** - * Update command is the same - * @ignore - * @api private - */ -Db.prototype._executeUpdateCommand = Db.prototype._executeInsertCommand; -/** - * Remove command is the same - * @ignore - * @api private - */ -Db.prototype._executeRemoveCommand = Db.prototype._executeInsertCommand; - -/** - * Wrap a Mongo error document into an Error instance. - * Deprecated. Use utils.toError instead. - * - * @ignore - * @api private - * @deprecated - */ -Db.prototype.wrap = utils.toError; - -/** - * Default URL - * - * @classconstant DEFAULT_URL - **/ -Db.DEFAULT_URL = 'mongodb://localhost:27017/default'; - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occurred, or null otherwise. While the second parameter will contain the db instance or null if an error occurred. - * @return {null} - * @api public - */ -Db.connect = function(url, options, callback) { - // Ensure correct mapping of the callback - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Ensure same behavior as previous version w:0 - if(url.indexOf("safe") == -1 - && url.indexOf("w") == -1 - && url.indexOf("journal") == -1 && url.indexOf("j") == -1 - && url.indexOf("fsync") == -1) options.w = 0; - - // Avoid circular require problem - var MongoClient = require('./mongo_client.js').MongoClient; - // Attempt to connect - MongoClient.connect.call(MongoClient, url, options, callback); -}; - -/** - * State of the db connection - * @ignore - */ -Object.defineProperty(Db.prototype, "state", { enumerable: true - , get: function () { - return this.serverConfig._serverState; - } -}); - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -}; - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -}; - -/** - * @ignore - */ -var _getWriteConcern = function(self, options, callback) { - // Final options - var finalOptions = {w:1}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.options); - } else if(self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.safe); - } else if(typeof self.safe == "boolean") { - finalOptions = {w: (self.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -}; - -/** - * Legacy support - * - * @ignore - * @api private - */ -exports.connect = Db.connect; -exports.Db = Db; - -/** - * Remove all listeners to the db instance. - * @ignore - * @api private - */ -Db.prototype.removeAllEventListeners = function() { - this.removeAllListeners("close"); - this.removeAllListeners("error"); - this.removeAllListeners("timeout"); - this.removeAllListeners("parseError"); - this.removeAllListeners("poolReady"); - this.removeAllListeners("message"); -}; diff --git a/node_modules/mongodb/lib/mongodb/gridfs/chunk.js b/node_modules/mongodb/lib/mongodb/gridfs/chunk.js deleted file mode 100644 index 59c6a267a..000000000 --- a/node_modules/mongodb/lib/mongodb/gridfs/chunk.js +++ /dev/null @@ -1,221 +0,0 @@ -var Binary = require('bson').Binary, - ObjectID = require('bson').ObjectID; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = exports.Chunk = function(file, mongoObject, writeConcern) { - if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var self = this; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || {w:1}; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if(mongoObjectFinal.data == null) { - } else if(typeof mongoObjectFinal.data == "string") { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 'binary', 0); - this.data = new Binary(buffer); - } else if(Array.isArray(mongoObjectFinal.data)) { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data.join(''), 'binary', 0); - this.data = new Binary(buffer); - } else if(mongoObjectFinal.data instanceof Binary || Object.prototype.toString.call(mongoObjectFinal.data) == "[object Binary]") { - this.data = mongoObjectFinal.data; - } else if(Buffer.isBuffer(mongoObjectFinal.data)) { - } else { - throw Error("Illegal chunk format"); - } - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition); - this.internalPosition = this.data.length(); - if(callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length == 0 ? this.length() : length; - - if(this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if ((this.length() - this.internalPosition) >= length) { - var data = null; - if (this.data.buffer != null) { //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { //Native BSON - data = new Buffer(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition == this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(callback) { - var self = this; - - self.file.chunkCollection(function(err, collection) { - if(err) return callback(err); - - collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { - if(err) return callback(err); - - if(self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = {forceServerObjectId:true}; - for(var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.insert(mongoObject, options, function(err, collection) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *
    
    - *        {
    - *          '_id' : , // {number} id for this chunk
    - *          'files_id' : , // {number} foreign key to the file collection
    - *          'n' : , // {number} chunk number
    - *          'data' : , // {bson#Binary} the chunk data itself
    - *        }
    - *        
    - * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - 'files_id': this.file.fileId, - 'n': this.chunkNumber, - 'data': this.data}; - // If we are saving using a specific ObjectId - if(this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, "position", { enumerable: true - , get: function () { - return this.internalPosition; - } - , set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 256; diff --git a/node_modules/mongodb/lib/mongodb/gridfs/grid.js b/node_modules/mongodb/lib/mongodb/gridfs/grid.js deleted file mode 100644 index aa695b723..000000000 --- a/node_modules/mongodb/lib/mongodb/gridfs/grid.js +++ /dev/null @@ -1,103 +0,0 @@ -var GridStore = require('./gridstore').GridStore, - ObjectID = require('bson').ObjectID; - -/** - * A class representation of a simple Grid interface. - * - * @class Represents the Grid. - * @param {Db} db A database instance to interact with. - * @param {String} [fsName] optional different root collection for GridFS. - * @return {Grid} - */ -function Grid(db, fsName) { - - if(!(this instanceof Grid)) return new Grid(db, fsName); - - this.db = db; - this.fsName = fsName == null ? GridStore.DEFAULT_ROOT_COLLECTION : fsName; -} - -/** - * Puts binary data to the grid - * - * Options - * - **_id** {Any}, unique id for this file - * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * - **metadata** {Object}, arbitrary data the user wants to store. - * - * @param {Buffer} data buffer with Binary Data. - * @param {Object} [options] the options for the files. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.put = function(data, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - // If root is not defined add our default one - options['root'] = options['root'] == null ? this.fsName : options['root']; - - // Return if we don't have a buffer object as data - if(!(Buffer.isBuffer(data))) return callback(new Error("Data object must be a buffer object"), null); - // Get filename if we are using it - var filename = options['filename'] || null; - // Get id if we are using it - var id = options['_id'] || null; - // Create gridstore - var gridStore = new GridStore(this.db, id, filename, "w", options); - gridStore.open(function(err, gridStore) { - if(err) return callback(err, null); - - gridStore.write(data, function(err, result) { - if(err) return callback(err, null); - - gridStore.close(function(err, result) { - if(err) return callback(err, null); - callback(null, result); - }) - }) - }) -} - -/** - * Get binary data to the grid - * - * @param {Any} id for file. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.get = function(id, callback) { - // Create gridstore - var gridStore = new GridStore(this.db, id, null, "r", {root:this.fsName}); - gridStore.open(function(err, gridStore) { - if(err) return callback(err, null); - - // Return the data - gridStore.read(function(err, data) { - return callback(err, data) - }); - }) -} - -/** - * Delete file from grid - * - * @param {Any} id for file. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.delete = function(id, callback) { - // Create gridstore - GridStore.unlink(this.db, id, {root:this.fsName}, function(err, result) { - if(err) return callback(err, false); - return callback(null, true); - }); -} - -exports.Grid = Grid; diff --git a/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js b/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js deleted file mode 100644 index 57767ae35..000000000 --- a/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js +++ /dev/null @@ -1,1546 +0,0 @@ -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - */ -var Chunk = require('./chunk').Chunk, - DbCommand = require('../commands/db_command').DbCommand, - ObjectID = require('bson').ObjectID, - Buffer = require('buffer').Buffer, - fs = require('fs'), - timers = require('timers'), - util = require('util'), - inherits = util.inherits, - ReadStream = require('./readstream').ReadStream, - Stream = require('stream'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -/** - * A class representation of a file stored in GridFS. - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwriten. - * - **w+"** - write in edit mode. - * - * Options - * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * - **metadata** {Object}, arbitrary data the user wants to store. - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * @class Represents the GridStore. - * @param {Db} db A database instance to interact with. - * @param {Any} [id] optional unique id for this file - * @param {String} [filename] optional filename for this file, no unique constrain on the field - * @param {String} mode set the mode for this file. - * @param {Object} options optional properties to specify. - * @return {GridStore} - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - - var self = this; - this.db = db; - - // Call stream constructor - if(typeof Stream == 'function') { - Stream.call(this); - } else { - // 0.4.X backward compatibility fix - Stream.Stream.call(this); - } - - // Handle options - if(typeof options === 'undefined') options = {}; - // Handle mode - if(typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if(typeof mode == 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if(id instanceof ObjectID) { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if(typeof filename == 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? "r" : mode; - this.options = options == null ? {w:1} : options; - - // If we have no write concerns set w:1 as default - if(this.options.w == null - && this.options.j == null - && this.options.fsync == null) this.options.w = 1; - - // Set the root if overridden - this.root = this.options['root'] == null ? exports.GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = this.options.readPreference || 'primary'; - this.writeConcern = _getWriteConcern(this, this.options); - // Set default chunk size - this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; -} - -/** - * Code for the streaming capabilities of the gridstore object - * Most code from Aaron heckmanns project https://github.com/aheckmann/gridfs-stream - * Modified to work on the gridstore object itself - * @ignore - */ -if(typeof Stream == 'function') { - GridStore.prototype = { __proto__: Stream.prototype } -} else { - // Node 0.4.X compatibility code - GridStore.prototype = { __proto__: Stream.Stream.prototype } -} - -// Move pipe to _pipe -GridStore.prototype._pipe = GridStore.prototype.pipe; - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an **{Error}** object and the second parameter will be null if an error occured. Otherwise, the first parameter will be null and the second will contain the reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.open = function(callback) { - if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ - callback(new Error("Illegal mode " + this.mode), null); - return; - } - - var self = this; - // If we are writing we need to ensure we have the right indexes for md5's - if((self.mode == "w" || self.mode == "w+")) { - // Get files collection - self.collection(function(err, collection) { - if(err) return callback(err); - - // Put index on filename - collection.ensureIndex([['filename', 1]], function(err, index) { - if(err) return callback(err); - - // Get chunk collection - self.chunkCollection(function(err, chunkCollection) { - if(err) return callback(err); - - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], function(err, index) { - if(err) return callback(err); - _open(self, callback); - }); - }); - }); - }); - } else { - // Open the gridstore - _open(self, callback); - } -}; - -/** - * Hidding the _open function - * @ignore - * @api private - */ -var _open = function(self, callback) { - self.collection(function(err, collection) { - if(err!==null) { - callback(new Error("at collection: "+err), null); - return; - } - - // Create the query - var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; - query = null == self.fileId && this.filename == null ? null : query; - - // Fetch the chunks - if(query != null) { - collection.find(query, {readPreference:self.readPreference}, function(err, cursor) { - if(err) return error(err); - - // Fetch the file - cursor.nextObject(function(err, doc) { - if(err) return error(err); - - // Check if the collection for the files exists otherwise prepare the new one - if(doc != null) { - self.fileId = doc._id; - self.filename = doc.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode != 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; - return error(new Error((self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename) + " does not exist", self)); - } - - // Process the mode of the object - if(self.mode == "r") { - nthChunk(self, 0, function(err, chunk) { - if(err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = self.length; - callback(null, self); - }); - } - }); - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - self.chunkCollection(function(err, collection2) { - if(err) return error(err); - - // No file exists set up write mode - if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = self.length; - callback(null, self); - }); - } - }); - } - }); - - // only pass error to callback once - function error (err) { - if(error.err) return; - callback(error.err = err); - } -}; - -/** - * Stores a file from the file system to the GridFS database. - * - * @param {String|Buffer|FileHandle} file the file to store. - * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the the second will contain the reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.writeFile = function (file, callback) { - var self = this; - if (typeof file === 'string') { - fs.open(file, 'r', function (err, fd) { - if(err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function (err, self) { - if(err) return callback(err, self); - - fs.fstat(file, function (err, stats) { - if(err) return callback(err, self); - - var offset = 0; - var index = 0; - var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); - - // Write a chunk - var writeChunk = function() { - fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { - if(err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, {n:index++}, self.writeConcern); - chunk.write(data, function(err, chunk) { - if(err) return callback(err, self); - - chunk.save(function(err, result) { - if(err) return callback(err, self); - - self.position = self.position + data.length; - - // Point to current chunk - self.currentChunk = chunk; - - if(offset >= stats.size) { - fs.close(file); - self.close(function(err, result) { - if(err) return callback(err, self); - return callback(null, self); - }); - } else { - return processor(writeChunk); - } - }); - }); - }); - } - - // Process the first write - processor(writeChunk); - }); - }); -}; - -/** - * Writes some data. This method will work properly only if initialized with mode - * "w" or "w+". - * - * @param string {string} The data to write. - * @param close {boolean=false} opt_argument Closes this file after writing if - * true. - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - * - * @ignore - * @api private - */ -var writeBuffer = function(self, buffer, close, callback) { - if(typeof close === "function") { callback = close; close = null; } - var finalClose = (close == null) ? false : close; - - if(self.mode[0] != "w") { - callback(new Error((self.referenceBy == REFERENCE_BY_ID ? self.toHexString() : self.filename) + " not opened for writing"), null); - } else { - if(self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while(leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - var firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - // If we have left over data write it - if(leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - // Write out all the chunks and then return - for(var i = 0; i < chunksToWrite.length; i++) { - var chunk = chunksToWrite[i]; - chunk.save(function(err, result) { - if(err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if(numberOfChunksToWrite <= 0) { - return callback(null, self); - } - }) - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - * @param callback {function(object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *
    
    - *        {
    - *          '_id' : , // {number} id for this file
    - *          'filename' : , // {string} name for this file
    - *          'contentType' : , // {string} mime type for this file
    - *          'length' : , // {number} size of this file?
    - *          'chunksize' : , // {number} chunk size used by this file
    - *          'uploadDate' : , // {Date}
    - *          'aliases' : , // {array of string}
    - *          'metadata' : , // {string}
    - *        }
    - *        
    - * - * @ignore - * @api private - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - '_id': self.fileId, - 'filename': self.filename, - 'contentType': self.contentType, - 'length': self.position ? self.position : 0, - 'chunkSize': self.chunkSize, - 'uploadDate': self.uploadDate, - 'aliases': self.aliases, - 'metadata': self.metadata - }; - - var md5Command = {filemd5:self.fileId, root:self.root}; - self.db.command(md5Command, function(err, results) { - mongoObject.md5 = results.md5; - callback(mongoObject); - }); -}; - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @param {Function} callback this will be called after executing this method. Passes an **{Error}** object to the first parameter and null to the second if an error occured. Otherwise, passes null to the first and a reference to this object to the second. - * @return {null} - * @api public - */ -GridStore.prototype.close = function(callback) { - var self = this; - - if(self.mode[0] == "w") { - if(self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save(function(err, chunk) { - if(err && typeof callback == 'function') return callback(err); - - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - // Build the mongo object - if(self.uploadDate != null) { - files.remove({'_id':self.fileId}, {safe:true}, function(err, collection) { - if(err && typeof callback == 'function') return callback(err); - - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } - } else if(self.mode[0] == "r") { - if(typeof callback == 'function') - callback(null, null); - } else { - if(typeof callback == 'function') - callback(new Error("Illegal mode " + self.mode), null); - } -}; - -/** - * Gets the nth chunk of this file. - * - * @param chunkNumber {number} The nth chunk to retrieve. - * @param callback {function(*, Chunk|object)} This will be called after - * executing this method. null will be passed to the first parameter while - * a new {@link Chunk} instance will be passed to the second parameter if - * the chunk was found or an empty object {} if not. - * - * @ignore - * @api private - */ -var nthChunk = function(self, chunkNumber, callback) { - self.chunkCollection(function(err, collection) { - if(err) return callback(err); - - collection.find({'files_id':self.fileId, 'n':chunkNumber}, {readPreference: self.readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.nextObject(function(err, chunk) { - if(err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); - }); - }); -}; - -/** - * - * @ignore - * @api private - */ -GridStore.prototype._nthChunk = function(chunkNumber, callback) { - nthChunk(this, chunkNumber, callback); -} - -/** - * @return {Number} The last chunk number of this file. - * - * @ignore - * @api private - */ -var lastChunkNumber = function(self) { - return Math.floor(self.length/self.chunkSize); -}; - -/** - * Retrieve this file's chunks collection. - * - * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured. - * @return {null} - * @api public - */ -GridStore.prototype.chunkCollection = function(callback) { - this.db.collection((this.root + ".chunks"), callback); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @param callback {function(*, boolean)} This will be called after this method - * executes. Passes null to the first and true to the second argument. - * - * @ignore - * @api private - */ -var deleteChunks = function(self, callback) { - if(self.fileId != null) { - self.chunkCollection(function(err, collection) { - if(err) return callback(err, false); - collection.remove({'files_id':self.fileId}, {safe:true}, function(err, result) { - if(err) return callback(err, false); - callback(null, true); - }); - }); - } else { - callback(null, true); - } -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @param {Function} callback this will be called after this method executes. Passes null to the first and true to the second argument. - * @return {null} - * @api public - */ -GridStore.prototype.unlink = function(callback) { - var self = this; - deleteChunks(this, function(err) { - if(err!==null) { - err.message = "at deleteChunks: " + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if(err!==null) { - err.message = "at collection: " + err.message; - return callback(err); - } - - collection.remove({'_id':self.fileId}, {safe:true}, function(err) { - callback(err, self); - }); - }); - }); -}; - -/** - * Retrieves the file collection associated with this object. - * - * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured. - * @return {null} - * @api public - */ -GridStore.prototype.collection = function(callback) { - this.db.collection(this.root + ".files", callback); -}; - -/** - * Reads the data of this file. - * - * @param {String} [separator] the character to be recognized as the newline separator. - * @param {Function} callback This will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character. - * @return {null} - * @api public - */ -GridStore.prototype.readlines = function(separator, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - separator = args.length ? args.shift() : "\n"; - - this.read(function(err, data) { - if(err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for(var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -}; - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.rewind = function(callback) { - var self = this; - - if(this.currentChunk.chunkNumber != 0) { - if(this.mode[0] == "w") { - deleteChunks(self, function(err, gridStore) { - if(err) return callback(err); - self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if(err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -}; - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @param {Number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {String|Buffer} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {Function} callback this will be called after this method is executed. null will be passed to the first parameter and a string containing the contents of the buffer concatenated with the contents read from this file will be passed to the second. - * @return {null} - * @api public - */ -GridStore.prototype.read = function(length, buffer, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if(finalLength == 0 && finalBuffer.length == 0) return callback(new Error("File does not exist"), null); - // Else return data - callback(null, finalBuffer); - } else { - var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) return callback(err); - - if(chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if (finalBuffer._index > 0) { - callback(null, finalBuffer) - } else { - callback(new Error("no chunks found for file, possibly corrupt"), null); - } - } - }); - } -} - -/** - * Retrieves the position of the read/write head of this file. - * - * @param {Function} callback This gets called after this method terminates. null is passed to the first parameter and the position is passed to the second. - * @return {null} - * @api public - */ -GridStore.prototype.tell = function(callback) { - callback(null, this.position); -}; - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @param {Number} [position] the position to seek to - * @param {Number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.seek = function(position, seekLocation, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - seekLocation = args.length ? args.shift() : null; - - var seekLocationFinal = seekLocation == null ? exports.GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if(seekLocationFinal == exports.GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if(seekLocationFinal == exports.GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition/self.chunkSize); - if(newChunkNumber != self.currentChunk.chunkNumber) { - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(err, self); - }); - }; - - if(self.mode[0] == 'w') { - self.currentChunk.save(function(err) { - if(err) return callback(err); - seekChunk(); - }); - } else { - seekChunk(); - } - } else { - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(null, self); - } -}; - -/** - * Verify if the file is at EOF. - * - * @return {Boolean} true if the read/write head is at the end of this file. - * @api public - */ -GridStore.prototype.eof = function() { - return this.position == this.length ? true : false; -}; - -/** - * Retrieves a single character from this file. - * - * @param {Function} callback this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {null} - * @api public - */ -GridStore.prototype.getc = function(callback) { - var self = this; - - if(self.eof()) { - callback(null, null); - } else if(self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -}; - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @param {String} string the string to write. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.puts = function(string, callback) { - var finalString = string.match(/\n$/) == null ? string + "\n" : string; - this.write(finalString, callback); -}; - -/** - * Returns read stream based on this GridStore file - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **end** {function() {}} the end event triggers when there is no more documents available. - * - **close** {function() {}} the close event triggers when the stream is closed. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - * @param {Boolean} autoclose if true current GridStore will be closed when EOF and 'close' event will be fired - * @return {null} - * @api public - */ -GridStore.prototype.stream = function(autoclose) { - return new ReadStream(autoclose, this); -}; - -/** -* The collection to be used for holding the files and chunks collection. -* -* @classconstant DEFAULT_ROOT_COLLECTION -**/ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** -* Default file mime type -* -* @classconstant DEFAULT_CONTENT_TYPE -**/ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** -* Seek mode where the given length is absolute. -* -* @classconstant IO_SEEK_SET -**/ -GridStore.IO_SEEK_SET = 0; - -/** -* Seek mode where the given length is an offset to the current read/write head. -* -* @classconstant IO_SEEK_CUR -**/ -GridStore.IO_SEEK_CUR = 1; - -/** -* Seek mode where the given length is an offset to the end of the file. -* -* @classconstant IO_SEEK_END -**/ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Db} db the database to query. - * @param {String} name the name of the file to look for. - * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {Function} callback this will be called after this method executes. Passes null to the first and passes true to the second if the file exists and false otherwise. - * @return {null} - * @api public - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - // Establish read preference - var readPreference = options.readPreference || 'primary'; - // Fetch collection - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + ".files", function(err, collection) { - if(err) return callback(err); - - // Build query - var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) - ? {'filename':fileIdObject} - : {'_id':fileIdObject}; // Attempt to locate file - - collection.find(query, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.nextObject(function(err, item) { - if(err) return callback(err); - callback(null, item == null ? false : true); - }); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @param {Db} db the database to query. - * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {Function} callback this will be called after this method executes. Passes null to the first and passes an array of strings containing the names of the files. - * @return {null} - * @api public - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - // Ensure we have correct values - if(rootCollection != null && typeof rootCollection == 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || 'primary'; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection((rootCollectionFinal + ".files"), function(err, collection) { - if(err) return callback(err); - - collection.find({}, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.each(function(err, item) { - if(item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @param {Db} db the database to query. - * @param {String} name the name of the file. - * @param {Number} [length] the size of data to read. - * @param {Number} [offset] the offset from the head of the file of which to start reading from. - * @param {Object} [options] the options for the file. - * @param {Function} callback this will be called after this method executes. A string with an error message will be passed to the first parameter when the length and offset combination exceeds the length of the file while an Error object will be passed if other forms of error occured, otherwise, a string is passed. The second parameter will contain the data read if successful or null if an error occured. - * @return {null} - * @api public - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - // Make sure we are not reading out of bounds - if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); - if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); - if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); - - if(offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if(err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Reads the data of this file. - * - * @param {Db} db the database to query. - * @param {String} name the name of the file. - * @param {String} [separator] the character to be recognized as the newline separator. - * @param {Object} [options] file options. - * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character. - * @return {null} - * @api public - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - - var finalSeperator = separator == null ? "\n" : separator; - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @param {Db} db the database to interact with. - * @param {String|Array} names the name/names of the files to delete. - * @param {Object} [options] the options for the files. - * @callback {Function} this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.unlink = function(db, names, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() : null; - - if(names.constructor == Array) { - var tc = 0; - for(var i = 0; i < names.length; i++) { - ++tc; - self.unlink(db, names[i], options, function(result) { - if(--tc == 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, "w", options).open(function(err, gridStore) { - if(err) return callback(err); - deleteChunks(gridStore, function(err, result) { - if(err) return callback(err); - gridStore.collection(function(err, collection) { - if(err) return callback(err); - collection.remove({'_id':gridStore.fileId}, {safe:true}, function(err, collection) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * Returns the current chunksize of the file. - * - * @field chunkSize - * @type {Number} - * @getter - * @setter - * @property return number of bytes in the current chunkSize. - */ -Object.defineProperty(GridStore.prototype, "chunkSize", { enumerable: true - , get: function () { - return this.internalChunkSize; - } - , set: function(value) { - if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } -}); - -/** - * The md5 checksum for this file. - * - * @field md5 - * @type {Number} - * @getter - * @setter - * @property return this files md5 checksum. - */ -Object.defineProperty(GridStore.prototype, "md5", { enumerable: true - , get: function () { - return this.internalMd5; - } -}); - -/** - * GridStore Streaming methods - * Handles the correct return of the writeable stream status - * @ignore - */ -Object.defineProperty(GridStore.prototype, "writable", { enumerable: true - , get: function () { - if(this._writeable == null) { - this._writeable = this.mode != null && this.mode.indexOf("w") != -1; - } - // Return the _writeable - return this._writeable; - } - , set: function(value) { - this._writeable = value; - } -}); - -/** - * Handles the correct return of the readable stream status - * @ignore - */ -Object.defineProperty(GridStore.prototype, "readable", { enumerable: true - , get: function () { - if(this._readable == null) { - this._readable = this.mode != null && this.mode.indexOf("r") != -1; - } - return this._readable; - } - , set: function(value) { - this._readable = value; - } -}); - -GridStore.prototype.paused; - -/** - * Handles the correct setting of encoding for the stream - * @ignore - */ -GridStore.prototype.setEncoding = fs.ReadStream.prototype.setEncoding; - -/** - * Handles the end events - * @ignore - */ -GridStore.prototype.end = function end(data) { - var self = this; - // allow queued data to write before closing - if(!this.writable) return; - this.writable = false; - - if(data) { - this._q.push(data); - } - - this.on('drain', function () { - self.close(function (err) { - if (err) return _error(self, err); - self.emit('close'); - }); - }); - - _flush(self); -} - -/** - * Handles the normal writes to gridstore - * @ignore - */ -var _writeNormal = function(self, data, close, callback) { - // If we have a buffer write it using the writeBuffer method - if(Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - // Wrap the string in a buffer and write - return writeBuffer(self, new Buffer(data, 'binary'), close, callback); - } -} - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @param {String|Buffer} data the data to write. - * @param {Boolean} [close] closes this file after writing if set to true. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.write = function write(data, close, callback) { - // If it's a normal write delegate the call - if(typeof close == 'function' || typeof callback == 'function') { - return _writeNormal(this, data, close, callback); - } - - // Otherwise it's a stream write - var self = this; - if (!this.writable) { - throw new Error('GridWriteStream is not writable'); - } - - // queue data until we open. - if (!this._opened) { - // Set up a queue to save data until gridstore object is ready - this._q = []; - _openStream(self); - this._q.push(data); - return false; - } - - // Push data to queue - this._q.push(data); - _flush(this); - // Return write successful - return true; -} - -/** - * Handles the destroy part of a stream - * @ignore - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if(!this.writable) return; - this.readable = false; - if(this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -} - -/** - * Handles the destroySoon part of a stream - * @ignore - */ -GridStore.prototype.destroySoon = function destroySoon() { - // as soon as write queue is drained, destroy. - // may call destroy immediately if no data is queued. - if(!this._q.length) { - return this.destroy(); - } - this._destroying = true; -} - -/** - * Handles the pipe part of the stream - * @ignore - */ -GridStore.prototype.pipe = function(destination, options) { - var self = this; - // Open the gridstore - this.open(function(err, result) { - if(err) _errorRead(self, err); - if(!self.readable) return; - // Set up the pipe - self._pipe(destination, options); - // Emit the stream is open - self.emit('open'); - // Read from the stream - _read(self); - }) -} - -/** - * Internal module methods - * @ignore - */ -var _read = function _read(self) { - if (!self.readable || self.paused || self.reading) { - return; - } - - self.reading = true; - var stream = self._stream = self.stream(); - stream.paused = self.paused; - - stream.on('data', function (data) { - if (self._decoder) { - var str = self._decoder.write(data); - if (str.length) self.emit('data', str); - } else { - self.emit('data', data); - } - }); - - stream.on('end', function (data) { - self.emit('end', data); - }); - - stream.on('error', function (data) { - _errorRead(self, data); - }); - - stream.on('close', function (data) { - self.emit('close', data); - }); - - self.pause = function () { - // native doesn't always pause. - // bypass its pause() method to hack it - self.paused = stream.paused = true; - } - - self.resume = function () { - if(!self.paused) return; - - self.paused = false; - stream.resume(); - self.readable = stream.readable; - } - - self.destroy = function () { - self.readable = false; - stream.destroy(); - } -} - -/** - * pause - * @ignore - */ -GridStore.prototype.pause = function pause () { - // Overridden when the GridStore opens. - this.paused = true; -} - -/** - * resume - * @ignore - */ -GridStore.prototype.resume = function resume () { - // Overridden when the GridStore opens. - this.paused = false; -} - -/** - * Internal module methods - * @ignore - */ -var _flush = function _flush(self, _force) { - if (!self._opened) return; - if (!_force && self._flushing) return; - self._flushing = true; - - // write the entire q to gridfs - if (!self._q.length) { - self._flushing = false; - self.emit('drain'); - - if(self._destroying) { - self.destroy(); - } - return; - } - - self.write(self._q.shift(), function (err, store) { - if (err) return _error(self, err); - self.emit('progress', store.position); - _flush(self, true); - }); -} - -var _openStream = function _openStream (self) { - if(self._opening == true) return; - self._opening = true; - - // Open the store - self.open(function (err, gridstore) { - if (err) return _error(self, err); - self._opened = true; - self.emit('open'); - _flush(self); - }); -} - -var _error = function _error(self, err) { - self.destroy(); - self.emit('error', err); -} - -var _errorRead = function _errorRead (self, err) { - self.readable = false; - self.emit('error', err); -} - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options, callback) { - // Final options - var finalOptions = {w:1}; - options = options || {}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(self.db.safe.w != null || typeof self.db.safe.j == 'boolean' || typeof self.db.safe.journal == 'boolean' || typeof self.db.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.safe); - } else if(self.db.options.w != null || typeof self.db.options.j == 'boolean' || typeof self.db.options.journal == 'boolean' || typeof self.db.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.options); - } else if(typeof self.db.safe == "boolean") { - finalOptions = {w: (self.db.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * @ignore - * @api private - */ -exports.GridStore = GridStore; diff --git a/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/node_modules/mongodb/lib/mongodb/gridfs/readstream.js deleted file mode 100644 index 83ed96cb3..000000000 --- a/node_modules/mongodb/lib/mongodb/gridfs/readstream.js +++ /dev/null @@ -1,199 +0,0 @@ -var Stream = require('stream').Stream, - timers = require('timers'), - util = require('util'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * ReadStream - * - * Returns a stream interface for the **file**. - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **end** {function() {}} the end event triggers when there is no more documents available. - * - **close** {function() {}} the close event triggers when the stream is closed. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - * @class Represents a GridFS File Stream. - * @param {Boolean} autoclose automatically close file when the stream reaches the end. - * @param {GridStore} cursor a cursor object that the stream wraps. - * @return {ReadStream} - */ -function ReadStream(autoclose, gstore) { - if (!(this instanceof ReadStream)) return new ReadStream(autoclose, gstore); - Stream.call(this); - - this.autoclose = !!autoclose; - this.gstore = gstore; - - this.finalLength = gstore.length - gstore.position; - this.completedLength = 0; - this.currentChunkNumber = gstore.currentChunk.chunkNumber; - - this.paused = false; - this.readable = true; - this.pendingChunk = null; - this.executing = false; - this.destroyed = false; - - // Calculate the number of chunks - this.numberOfChunks = Math.ceil(gstore.length/gstore.chunkSize); - - // This seek start position inside the current chunk - this.seekStartPosition = gstore.position - (this.currentChunkNumber * gstore.chunkSize); - - var self = this; - processor(function() { - self._execute(); - }); -}; - -/** - * Inherit from Stream - * @ignore - * @api private - */ -ReadStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - */ -ReadStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - */ -ReadStream.prototype.paused; - -/** - * @ignore - * @api private - */ -ReadStream.prototype._execute = function() { - if(this.paused === true || this.readable === false) { - return; - } - - var gstore = this.gstore; - var self = this; - // Set that we are executing - this.executing = true; - - var last = false; - var toRead = 0; - - if(gstore.currentChunk.chunkNumber >= (this.numberOfChunks - 1)) { - self.executing = false; - last = true; - } - - // Data setup - var data = null; - - // Read a slice (with seek set if none) - if(this.seekStartPosition > 0 && (gstore.currentChunk.length() - this.seekStartPosition) > 0) { - data = gstore.currentChunk.readSlice(gstore.currentChunk.length() - this.seekStartPosition); - this.seekStartPosition = 0; - } else { - data = gstore.currentChunk.readSlice(gstore.currentChunk.length()); - } - - // Return the data - if(data != null && gstore.currentChunk.chunkNumber == self.currentChunkNumber) { - self.currentChunkNumber = self.currentChunkNumber + 1; - self.completedLength += data.length; - self.pendingChunk = null; - self.emit("data", data); - } - - if(last === true) { - self.readable = false; - self.emit("end"); - - if(self.autoclose === true) { - if(gstore.mode[0] == "w") { - gstore.close(function(err, doc) { - if (err) { - console.log("############################## 0") - self.emit("error", err); - return; - } - self.readable = false; - self.destroyed = true; - self.emit("close", doc); - }); - } else { - self.readable = false; - self.destroyed = true; - self.emit("close"); - } - } - } else { - gstore._nthChunk(gstore.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) { - self.readable = false; - if(self.listeners("error").length > 0) - self.emit("error", err); - self.executing = false; - return; - } - - self.pendingChunk = chunk; - if(self.paused === true) { - self.executing = false; - return; - } - - gstore.currentChunk = self.pendingChunk; - self._execute(); - }); - } -}; - -/** - * Pauses this stream, then no farther events will be fired. - * - * @ignore - * @api public - */ -ReadStream.prototype.pause = function() { - if(!this.executing) { - this.paused = true; - } -}; - -/** - * Destroys the stream, then no farther events will be fired. - * - * @ignore - * @api public - */ -ReadStream.prototype.destroy = function() { - if(this.destroyed) return; - this.destroyed = true; - this.readable = false; - // Emit close event - this.emit("close"); -}; - -/** - * Resumes this stream. - * - * @ignore - * @api public - */ -ReadStream.prototype.resume = function() { - if(this.paused === false || !this.readable) { - return; - } - - this.paused = false; - var self = this; - processor(function() { - self._execute(); - }); -}; - -exports.ReadStream = ReadStream; diff --git a/node_modules/mongodb/lib/mongodb/index.js b/node_modules/mongodb/lib/mongodb/index.js deleted file mode 100644 index 91d28df4f..000000000 --- a/node_modules/mongodb/lib/mongodb/index.js +++ /dev/null @@ -1,69 +0,0 @@ -try { - exports.BSONPure = require('bson').BSONPure; - exports.BSONNative = require('bson').BSONNative; -} catch(err) { - // do nothing -} - -// export the driver version -exports.version = require('../../package').version; - -[ 'commands/base_command' - , 'admin' - , 'collection' - , 'connection/read_preference' - , 'connection/connection' - , 'connection/server' - , 'connection/mongos' - , 'connection/repl_set/repl_set' - , 'mongo_client' - , 'cursor' - , 'db' - , 'mongo_client' - , 'gridfs/grid' - , 'gridfs/chunk' - , 'gridfs/gridstore'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// backwards compat -exports.ReplSetServers = exports.ReplSet; -// Add BSON Classes -exports.Binary = require('bson').Binary; -exports.Code = require('bson').Code; -exports.DBRef = require('bson').DBRef; -exports.Double = require('bson').Double; -exports.Long = require('bson').Long; -exports.MinKey = require('bson').MinKey; -exports.MaxKey = require('bson').MaxKey; -exports.ObjectID = require('bson').ObjectID; -exports.Symbol = require('bson').Symbol; -exports.Timestamp = require('bson').Timestamp; -// Add BSON Parser -exports.BSON = require('bson').BSONPure.BSON; - -// Get the Db object -var Db = require('./db').Db; -// Set up the connect function -var connect = Db.connect; -var obj = connect; -// Map all values to the exports value -for(var name in exports) { - obj[name] = exports[name]; -} - -// Add the pure and native backward compatible functions -exports.pure = exports.native = function() { - return obj; -} - -// Map all values to the exports value -for(var name in exports) { - connect[name] = exports[name]; -} - -// Set our exports to be the connect function -module.exports = connect; diff --git a/node_modules/mongodb/lib/mongodb/mongo_client.js b/node_modules/mongodb/lib/mongodb/mongo_client.js deleted file mode 100644 index 0b855b3a0..000000000 --- a/node_modules/mongodb/lib/mongodb/mongo_client.js +++ /dev/null @@ -1,441 +0,0 @@ -var Db = require('./db').Db - , Server = require('./connection/server').Server - , Mongos = require('./connection/mongos').Mongos - , ReplSet = require('./connection/repl_set/repl_set').ReplSet - , ReadPreference = require('./connection/read_preference').ReadPreference - , inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , parse = require('./connection/url_parser').parse; - -/** - * Create a new MongoClient instance. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **native_parser** {Boolean, default:false}, use c++ bson parser. - * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **serializeFunctions** {Boolean, default:false}, serialize functions. - * - **raw** {Boolean, default:false}, peform operations using raw bson buffers. - * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution. - * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries. - * - **numberOfRetries** {Number, default:5}, number of retries off connection. - * - **bufferMaxEntries** {Boolean, default: -1}, sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @class Represents a MongoClient - * @param {Object} serverConfig server config object. - * @param {Object} [options] additional options for the collection. - */ -function MongoClient(serverConfig, options) { - if(serverConfig != null) { - options = options == null ? {} : options; - // If no write concern is set set the default to w:1 - if(options != null && !options.journal && !options.w && !options.fsync) { - options.w = 1; - } - - // The internal db instance we are wrapping - this._db = new Db('test', serverConfig, options); - } -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.connect = function(url, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - MongoClient.connect(url, options, function(err, db) { - if(err) return callback(err, db); - // Store internal db instance reference - self._db = db; - // Emit open and perform callback - self.emit("open", err, db); - callback(err, db); - }); -} - -/** - * Initialize the database connection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the connected mongoclient or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.open = function(callback) { - // Self reference - var self = this; - // Open the db - this._db.open(function(err, db) { - if(err) return callback(err, null); - // Emit open event - self.emit("open", err, db); - // Callback - callback(null, self); - }) -} - -/** - * Close the current db connection, including all the child db instances. Emits close event if no callback is provided. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the close method or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.close = function(callback) { - this._db.close(callback); -} - -/** - * Create a new Db instance sharing the current socket connections. - * - * @param {String} dbName the name of the database we want to use. - * @return {Db} a db instance using the new database. - * @api public - */ -MongoClient.prototype.db = function(dbName) { - return this._db.db(dbName); -} - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.connect = function(url, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Set default empty server options - var serverOptions = options.server || {}; - var mongosOptions = options.mongos || {}; - var replSetServersOptions = options.replSet || options.replSetServers || {}; - var dbOptions = options.db || {}; - - // If callback is null throw an exception - if(callback == null) - throw new Error("no callback function provided"); - - // Parse the string - var object = parse(url, options); - // Merge in any options for db in options object - if(dbOptions) { - for(var name in dbOptions) object.db_options[name] = dbOptions[name]; - } - - // Added the url to the options - object.db_options.url = url; - - // Merge in any options for server in options object - if(serverOptions) { - for(var name in serverOptions) object.server_options[name] = serverOptions[name]; - } - - // Merge in any replicaset server options - if(replSetServersOptions) { - for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; - } - - // Merge in any replicaset server options - if(mongosOptions) { - for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; - } - - // We need to ensure that the list of servers are only either direct members or mongos - // they cannot be a mix of monogs and mongod's - var totalNumberOfServers = object.servers.length; - var totalNumberOfMongosServers = 0; - var totalNumberOfMongodServers = 0; - var serverConfig = null; - var errorServers = {}; - - // Failure modes - if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); - - // If we have no db setting for the native parser try to set the c++ one first - object.db_options.native_parser = _setNativeParser(object.db_options); - // If no auto_reconnect is set, set it to true as default for single servers - if(typeof object.server_options.auto_reconnect != 'boolean') { - object.server_options.auto_reconnect = true; - } - - // If we have more than a server, it could be replicaset or mongos list - // need to verify that it's one or the other and fail if it's a mix - // Connect to all servers and run ismaster - for(var i = 0; i < object.servers.length; i++) { - // Set up socket options - var _server_options = { - poolSize:1 - , socketOptions: { - connectTimeoutMS:30000 - , socketTimeoutMS: 30000 - } - , auto_reconnect:false}; - - // Ensure we have ssl setup for the servers - if(object.rs_options.ssl) { - _server_options.ssl = object.rs_options.ssl; - _server_options.sslValidate = object.rs_options.sslValidate; - _server_options.sslCA = object.rs_options.sslCA; - _server_options.sslCert = object.rs_options.sslCert; - _server_options.sslKey = object.rs_options.sslKey; - _server_options.sslPass = object.rs_options.sslPass; - } else if(object.server_options.ssl) { - _server_options.ssl = object.server_options.ssl; - _server_options.sslValidate = object.server_options.sslValidate; - _server_options.sslCA = object.server_options.sslCA; - _server_options.sslCert = object.server_options.sslCert; - _server_options.sslKey = object.server_options.sslKey; - _server_options.sslPass = object.server_options.sslPass; - } - - // Set up the Server object - var _server = object.servers[i].domain_socket - ? new Server(object.servers[i].domain_socket, _server_options) - : new Server(object.servers[i].host, object.servers[i].port, _server_options); - - var connectFunction = function(__server) { - // Attempt connect - new Db(object.dbName, __server, {safe:false, native_parser:false}).open(function(err, db) { - // Update number of servers - totalNumberOfServers = totalNumberOfServers - 1; - // If no error do the correct checks - if(!err) { - // Close the connection - db.close(true); - var isMasterDoc = db.serverConfig.isMasterDoc; - // Check what type of server we have - if(isMasterDoc.setName) totalNumberOfMongodServers++; - if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; - } else { - errorServers[__server.host + ":" + __server.port] = __server; - } - - if(totalNumberOfServers == 0) { - // If we have a mix of mongod and mongos, throw an error - if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { - return process.nextTick(function() { - try { - callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - - if(totalNumberOfMongodServers == 0 && object.servers.length == 1) { - var obj = object.servers[0]; - serverConfig = obj.domain_socket ? - new Server(obj.domain_socket, object.server_options) - : new Server(obj.host, obj.port, object.server_options); - } else if(totalNumberOfMongodServers > 0 || totalNumberOfMongosServers > 0) { - var finalServers = object.servers - .filter(function(serverObj) { - return errorServers[serverObj.host + ":" + serverObj.port] == null; - }) - .map(function(serverObj) { - return new Server(serverObj.host, serverObj.port, object.server_options); - }); - // Clean out any error servers - errorServers = {}; - // Set up the final configuration - if(totalNumberOfMongodServers > 0) { - serverConfig = new ReplSet(finalServers, object.rs_options); - } else { - serverConfig = new Mongos(finalServers, object.mongos_options); - } - } - - if(serverConfig == null) { - return process.nextTick(function() { - try { - callback(new Error("Could not locate any valid servers in initial seed list")); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - // Ensure no firing off open event before we are ready - serverConfig.emitOpen = false; - // Set up all options etc and connect to the database - _finishConnecting(serverConfig, object, options, callback) - } - }); - } - - // Wrap the context of the call - connectFunction(_server); - } -} - -var _setNativeParser = function(db_options) { - if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; - - try { - require('bson').BSONNative.BSON; - return true; - } catch(err) { - return false; - } -} - -var _finishConnecting = function(serverConfig, object, options, callback) { - // Safe settings - var safe = {}; - // Build the safe parameter if needed - if(object.db_options.journal) safe.j = object.db_options.journal; - if(object.db_options.w) safe.w = object.db_options.w; - if(object.db_options.fsync) safe.fsync = object.db_options.fsync; - if(object.db_options.wtimeoutMS) safe.wtimeout = object.db_options.wtimeoutMS; - - // If we have a read Preference set - if(object.db_options.read_preference) { - var readPreference = new ReadPreference(object.db_options.read_preference); - // If we have the tags set up - if(object.db_options.read_preference_tags) - readPreference = new ReadPreference(object.db_options.read_preference, object.db_options.read_preference_tags); - // Add the read preference - object.db_options.readPreference = readPreference; - } - - // No safe mode if no keys - if(Object.keys(safe).length == 0) safe = false; - - // Add the safe object - object.db_options.safe = safe; - - // Get the socketTimeoutMS - var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; - - // If we have a replset, override with replicaset socket timeout option if available - if(serverConfig instanceof ReplSet) { - socketTimeoutMS = object.rs_options.socketOptions.socketTimeoutMS || socketTimeoutMS; - } - - // Set socketTimeout to the same as the connectTimeoutMS or 30 sec - serverConfig.connectTimeoutMS = serverConfig.connectTimeoutMS || 30000; - serverConfig.socketTimeoutMS = serverConfig.connectTimeoutMS; - - // Set up the db options - var db = new Db(object.dbName, serverConfig, object.db_options); - // Open the db - db.open(function(err, db){ - if(err) { - return process.nextTick(function() { - try { - callback(err, null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - - // Reset the socket timeout - serverConfig.socketTimeoutMS = socketTimeoutMS || 0; - - // Set the provided write concern or fall back to w:1 as default - if(db.options !== null && !db.options.safe && !db.options.journal - && !db.options.w && !db.options.fsync && typeof db.options.w != 'number' - && (db.options.safe == false && object.db_options.url.indexOf("safe=") == -1)) { - db.options.w = 1; - } - - if(err == null && object.auth){ - // What db to authenticate against - var authentication_db = db; - if(object.db_options && object.db_options.authSource) { - authentication_db = db.db(object.db_options.authSource); - } - - // Build options object - var options = {}; - if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; - if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; - - // Authenticate - authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ - if(success){ - process.nextTick(function() { - try { - callback(null, db); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } else { - if(db) db.close(); - process.nextTick(function() { - try { - callback(err ? err : new Error('Could not authenticate user ' + auth[0]), null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - }); - } else { - process.nextTick(function() { - try { - callback(err, db); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - }); -} - -exports.MongoClient = MongoClient; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js b/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js deleted file mode 100644 index 21e8cec39..000000000 --- a/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js +++ /dev/null @@ -1,83 +0,0 @@ -var Long = require('bson').Long - , timers = require('timers'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - Reply message from mongo db -**/ -var MongoReply = exports.MongoReply = function() { - this.documents = []; - this.index = 0; -}; - -MongoReply.prototype.parseHeader = function(binary_reply, bson) { - // Unpack the standard header first - this.messageLength = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Fetch the request id for this reply - this.requestId = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Fetch the id of the request that triggered the response - this.responseTo = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - // Skip op-code field - this.index = this.index + 4 + 4; - // Unpack the reply message - this.responseFlag = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Unpack the cursor id (a 64 bit long integer) - var low_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - var high_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - this.cursorId = new Long(low_bits, high_bits); - // Unpack the starting from - this.startingFrom = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Unpack the number of objects returned - this.numberReturned = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; -} - -MongoReply.prototype.parseBody = function(binary_reply, bson, raw, callback) { - raw = raw == null ? false : raw; - - try { - // Let's unpack all the bson documents, deserialize them and store them - for(var object_index = 0; object_index < this.numberReturned; object_index++) { - var _options = {promoteLongs: bson.promoteLongs}; - - // Read the size of the bson object - var bsonObjectSize = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - - // If we are storing the raw responses to pipe straight through - if(raw) { - // Deserialize the object and add to the documents array - this.documents.push(binary_reply.slice(this.index, this.index + bsonObjectSize)); - } else { - // Deserialize the object and add to the documents array - this.documents.push(bson.deserialize(binary_reply.slice(this.index, this.index + bsonObjectSize), _options)); - } - - // Adjust binary index to point to next block of binary bson data - this.index = this.index + bsonObjectSize; - } - - // No error return - callback(null); - } catch(err) { - return callback(err); - } -} - -MongoReply.prototype.is_error = function(){ - if(this.documents.length == 1) { - return this.documents[0].ok == 1 ? false : true; - } - return false; -}; - -MongoReply.prototype.error_message = function() { - return this.documents.length == 1 && this.documents[0].ok == 1 ? '' : this.documents[0].errmsg; -}; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/scope.js b/node_modules/mongodb/lib/mongodb/scope.js deleted file mode 100644 index aaf32210b..000000000 --- a/node_modules/mongodb/lib/mongodb/scope.js +++ /dev/null @@ -1,199 +0,0 @@ -var Cursor2 = require('./cursor').Cursor - , Readable = require('stream').Readable - , utils = require('./utils') - , inherits = require('util').inherits; - -var Cursor = function Cursor(_scope_options, _cursor) { - // - // Backward compatible methods - this.toArray = function(callback) { - return _cursor.toArray(callback); - } - - this.each = function(callback) { - return _cursor.each(callback); - } - - this.next = function(callback) { - this.nextObject(callback); - } - - this.nextObject = function(callback) { - return _cursor.nextObject(callback); - } - - this.setReadPreference = function(readPreference, callback) { - _scope_options.readPreference = {readPreference: readPreference}; - _cursor.setReadPreference(readPreference, callback); - return this; - } - - this.batchSize = function(batchSize, callback) { - _scope_options.batchSize = batchSize; - _cursor.batchSize(_scope_options.batchSize, callback); - return this; - } - - this.count = function(applySkipLimit, callback) { - return _cursor.count(applySkipLimit, callback); - } - - this.stream = function(options) { - return _cursor.stream(options); - } - - this.close = function(callback) { - return _cursor.close(callback); - } - - this.explain = function(callback) { - return _cursor.explain(callback); - } - - this.isClosed = function(callback) { - return _cursor.isClosed(); - } - - this.rewind = function() { - return _cursor.rewind(); - } - - // Internal methods - this.limit = function(limit, callback) { - _cursor.limit(limit, callback); - _scope_options.limit = limit; - return this; - } - - this.skip = function(skip, callback) { - _cursor.skip(skip, callback); - _scope_options.skip = skip; - return this; - } - - this.hint = function(hint) { - _scope_options.hint = hint; - _cursor.hint = _scope_options.hint; - return this; - } - - this.maxTimeMS = function(maxTimeMS) { - _cursor.maxTimeMS(maxTimeMS) - _scope_options.maxTimeMS = maxTimeMS; - return this; - }, - - this.sort = function(keyOrList, direction, callback) { - _cursor.sort(keyOrList, direction, callback); - _scope_options.sort = keyOrList; - return this; - }, - - this.fields = function(fields) { - _fields = fields; - _cursor.fields = _fields; - return this; - } - - // - // Backward compatible settings - Object.defineProperty(this, "timeout", { - get: function() { - return _cursor.timeout; - } - }); - - Object.defineProperty(this, "read", { - get: function() { - return _cursor.read; - } - }); - - Object.defineProperty(this, "items", { - get: function() { - return _cursor.items; - } - }); -} - -var Scope = function(collection, _selector, _fields, _scope_options) { - var self = this; - - // Ensure we have at least an empty cursor options object - _scope_options = _scope_options || {}; - var _write_concern = _scope_options.write_concern || null; - - // Ensure default read preference - if(!_scope_options.readPreference) _scope_options.readPreference = {readPreference: 'primary'}; - - // Set up the cursor - var _cursor = new Cursor2( - collection.db, collection, _selector - , _fields, _scope_options - ); - - // Write branch options - var writeOptions = { - insert: function(documents, callback) { - // Merge together options - var options = _write_concern || {}; - // Execute insert - collection.insert(documents, options, callback); - }, - - save: function(document, callback) { - // Merge together options - var save_options = _write_concern || {}; - // Execute save - collection.save(document, save_options, function(err, result) { - if(typeof result == 'number' && result == 1) { - return callback(null, document); - } - - return callback(null, document); - }); - }, - - find: function(selector) { - _selector = selector; - return writeOptions; - }, - - // - // Update is implicit multiple document update - update: function(operations, callback) { - // Merge together options - var update_options = _write_concern || {}; - - // Set up options, multi is default operation - update_options.multi = _scope_options.multi ? _scope_options.multi : true; - if(_scope_options.upsert) update_options.upsert = _scope_options.upsert; - - // Execute options - collection.update(_selector, operations, update_options, function(err, result, obj) { - callback(err, obj); - }); - }, - } - - // Set write concern - this.withWriteConcern = function(write_concern) { - // Save the current write concern to the Scope - _scope_options.write_concern = write_concern; - _write_concern = write_concern; - // Only allow legal options - return writeOptions; - } - - // Start find - this.find = function(selector, options) { - // Save the current selector - _selector = selector; - // Set the cursor - _cursor.selector = selector; - // Return only legal read options - return new Cursor(_scope_options, _cursor); - } -} - -exports.Scope = Scope; \ No newline at end of file diff --git a/node_modules/mongodb/lib/mongodb/utils.js b/node_modules/mongodb/lib/mongodb/utils.js deleted file mode 100644 index 4eca8c00d..000000000 --- a/node_modules/mongodb/lib/mongodb/utils.js +++ /dev/null @@ -1,202 +0,0 @@ -var timers = require('timers'); - -/** - * Sort functions, Normalize and prepare sort parameters - */ -var formatSortValue = exports.formatSortValue = function(sortDirection) { - var value = ("" + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error("Illegal sort clause, must be of the form " - + "[['field1', '(ascending|descending)'], " - + "['field2', '(ascending|descending)']]"); - } -}; - -var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - - if (Array.isArray(sortValue)) { - for(var i = 0; i < sortValue.length; i++) { - if(sortValue[i].constructor == String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if(Object.prototype.toString.call(sortValue) === '[object Object]') { - orderBy = sortValue; - } else if (sortValue.constructor == String) { - orderBy[sortValue] = 1; - } else { - throw new Error("Illegal sort clause, must be of the form " + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); - } - - return orderBy; -}; - -exports.encodeInt = function(value) { - var buffer = new Buffer(4); - buffer[3] = (value >> 24) & 0xff; - buffer[2] = (value >> 16) & 0xff; - buffer[1] = (value >> 8) & 0xff; - buffer[0] = value & 0xff; - return buffer; -} - -exports.encodeIntInPlace = function(value, buffer, index) { - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; -} - -exports.encodeCString = function(string) { - var buf = new Buffer(string, 'utf8'); - return [buf, new Buffer([0])]; -} - -exports.decodeUInt32 = function(array, index) { - return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24; -} - -// Decode the int -exports.decodeUInt8 = function(array, index) { - return array[index]; -} - -/** - * Context insensitive type checks - */ - -var toString = Object.prototype.toString; - -exports.isObject = function (arg) { - return '[object Object]' == toString.call(arg) -} - -exports.isArray = function (arg) { - return Array.isArray(arg) || - 'object' == typeof arg && '[object Array]' == toString.call(arg) -} - -exports.isDate = function (arg) { - return 'object' == typeof arg && '[object Date]' == toString.call(arg) -} - -exports.isRegExp = function (arg) { - return 'object' == typeof arg && '[object RegExp]' == toString.call(arg) -} - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = new Error(msg); - e.name = 'MongoError'; - - // Get all object keys - var keys = typeof error == 'object' - ? Object.keys(error) - : []; - - for(var i = 0; i < keys.length; i++) { - e[keys[i]] = error[keys[i]]; - } - - return e; -} -exports.toError = toError; - -/** - * Convert a single level object to an array - * @ignore - * @api private - */ -exports.objectToArray = function(object) { - var list = []; - - for(var name in object) { - list.push(object[name]) - } - - return list; -} - -/** - * Handle single command document return - * @ignore - * @api private - */ -exports.handleSingleCommandResultReturn = function(override_value_true, override_value_false, callback) { - return function(err, result, connection) { - if(err && typeof callback == 'function') return callback(err, null); - if(!result || !result.documents || result.documents.length == 0) - if(typeof callback == 'function') return callback(toError("command failed to return results"), null) - if(result && result.documents[0].ok == 1) { - if(override_value_true) return callback(null, override_value_true) - if(typeof callback == 'function') return callback(null, result.documents[0]); - } - - // Return the error from the document - if(typeof callback == 'function') return callback(toError(result.documents[0]), override_value_false); - } -} - -/** - * Return correct processor - * @ignore - * @api private - */ -exports.processor = function() { - // Set processor, setImmediate if 0.10 otherwise nextTick - process.maxTickDepth = Infinity; - // Only use nextTick - return process.nextTick; -} - -/** - * Allow setting the socketTimeoutMS on all connections - * to work around issues such as secondaries blocking due to compaction - * - * @ignore - * @api private - */ -exports.setSocketTimeoutProperty = function(self, options) { - Object.defineProperty(self, "socketTimeoutMS", { - enumerable: true - , get: function () { return options.socketTimeoutMS; } - , set: function (value) { - // Set the socket timeoutMS value - options.socketTimeoutMS = value; - - // Get all the connections - var connections = self.allRawConnections(); - for(var i = 0; i < connections.length; i++) { - connections[i].socketTimeoutMS = value; - } - } - }); -} - -exports.hasWriteCommands = function(connection) { - return connection != null && connection.serverCapabilities != null && connection.serverCapabilities.hasWriteCommands; -} - - - diff --git a/node_modules/mongodb/node_modules/bson/.travis.yml b/node_modules/mongodb/node_modules/bson/.travis.yml deleted file mode 100644 index 54459614e..000000000 --- a/node_modules/mongodb/node_modules/bson/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.8 - - 0.10 # development version of 0.8, may be unstable - - 0.11 \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/Makefile b/node_modules/mongodb/node_modules/bson/Makefile deleted file mode 100644 index 77ce4e040..000000000 --- a/node_modules/mongodb/node_modules/bson/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -NODE = node -NPM = npm -NODEUNIT = node_modules/nodeunit/bin/nodeunit - -all: clean node_gyp - -test: clean node_gyp - npm test - -node_gyp: clean - node-gyp configure build - -clean: - node-gyp clean - -browserify: - node_modules/.bin/onejs build browser_build/package.json browser_build/bson.js - -.PHONY: all diff --git a/node_modules/mongodb/node_modules/bson/README.md b/node_modules/mongodb/node_modules/bson/README.md deleted file mode 100644 index 1a6fc2baf..000000000 --- a/node_modules/mongodb/node_modules/bson/README.md +++ /dev/null @@ -1,45 +0,0 @@ -Javascript + C++ BSON parser -============================ - -This BSON parser is primarily meant for usage with the `mongodb` node.js driver. However thanks to such wonderful tools at `onejs` we are able to package up a BSON parser that will work in the browser aswell. The current build is located in the `browser_build/bson.js` file. - -A simple example on how to use it - - - - - - - - - It's got two simple methods to use in your application. - - * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** - * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports - - * BSON.deserialize(buffer, options, isArray) - * Options - * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * @param {TypedArray/Array} a TypedArray/Array containing the BSON data - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. diff --git a/node_modules/mongodb/node_modules/bson/binding.gyp b/node_modules/mongodb/node_modules/bson/binding.gyp deleted file mode 100644 index f308f3ea1..000000000 --- a/node_modules/mongodb/node_modules/bson/binding.gyp +++ /dev/null @@ -1,17 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'bson', - 'sources': [ 'ext/bson.cc' ], - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'conditions': [ - ['OS=="mac"', { - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' - } - }] - ] - } - ] -} diff --git a/node_modules/mongodb/node_modules/bson/browser_build/bson.js b/node_modules/mongodb/node_modules/bson/browser_build/bson.js deleted file mode 100644 index d86a00d4b..000000000 --- a/node_modules/mongodb/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,4843 +0,0 @@ -var bson = (function(){ - - var pkgmap = {}, - global = {}, - nativeRequire = typeof require != 'undefined' && require, - lib, ties, main, async; - - function exports(){ return main(); }; - - exports.main = exports; - exports.module = module; - exports.packages = pkgmap; - exports.pkg = pkg; - exports.require = function require(uri){ - return pkgmap.main.index.require(uri); - }; - - - ties = {}; - - aliases = {}; - - - return exports; - -function join() { - return normalize(Array.prototype.join.call(arguments, "/")); -}; - -function normalize(path) { - var ret = [], parts = path.split('/'), cur, prev; - - var i = 0, l = parts.length-1; - for (; i <= l; i++) { - cur = parts[i]; - - if (cur === "." && prev !== undefined) continue; - - if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { - ret.pop(); - prev = ret.slice(-1)[0]; - } else { - if (prev === ".") ret.pop(); - ret.push(cur); - prev = cur; - } - } - - return ret.join("/"); -}; - -function dirname(path) { - return path && path.substr(0, path.lastIndexOf("/")) || "."; -}; - -function findModule(workingModule, uri){ - var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), - moduleIndexId = join(moduleId, 'index'), - pkg = workingModule.pkg, - module; - - var i = pkg.modules.length, - id; - - while(i-->0){ - id = pkg.modules[i].id; - - if(id==moduleId || id == moduleIndexId){ - module = pkg.modules[i]; - break; - } - } - - return module; -} - -function newRequire(callingModule){ - function require(uri){ - var module, pkg; - - if(/^\./.test(uri)){ - module = findModule(callingModule, uri); - } else if ( ties && ties.hasOwnProperty( uri ) ) { - return ties[uri]; - } else if ( aliases && aliases.hasOwnProperty( uri ) ) { - return require(aliases[uri]); - } else { - pkg = pkgmap[uri]; - - if(!pkg && nativeRequire){ - try { - pkg = nativeRequire(uri); - } catch (nativeRequireError) {} - - if(pkg) return pkg; - } - - if(!pkg){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module = pkg.index; - } - - if(!module){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module.parent = callingModule; - return module.call(); - }; - - - return require; -} - - -function module(parent, id, wrapper){ - var mod = { pkg: parent, id: id, wrapper: wrapper }, - cached = false; - - mod.exports = {}; - mod.require = newRequire(mod); - - mod.call = function(){ - if(cached) { - return mod.exports; - } - - cached = true; - - global.require = mod.require; - - mod.wrapper(mod, mod.exports, global, global.require); - return mod.exports; - }; - - if(parent.mainModuleId == mod.id){ - parent.index = mod; - parent.parents.length === 0 && ( main = mod.call ); - } - - parent.modules.push(mod); -} - -function pkg(/* [ parentId ...], wrapper */){ - var wrapper = arguments[ arguments.length - 1 ], - parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), - ctx = wrapper(parents); - - - pkgmap[ctx.name] = ctx; - - arguments.length == 1 && ( pkgmap.main = ctx ); - - return function(modules){ - var id; - for(id in modules){ - module(ctx, id, modules[id]); - } - }; -} - - -}(this)); - -bson.pkg(function(parents){ - - return { - 'name' : 'bson', - 'mainModuleId' : 'bson', - 'modules' : [], - 'parents' : parents - }; - -})({ 'binary': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - - -}, - - - -'binary_parser': function(module, exports, global, require, undefined){ - /** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; - -}, - - - -'bson': function(module, exports, global, require, undefined){ - var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] || true; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; - -}, - - - -'code': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; -}, - - - -'db_ref': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; -}, - - - -'double': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; -}, - - - -'float_parser': function(module, exports, global, require, undefined){ - // Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; -}, - - - -'index': function(module, exports, global, require, undefined){ - try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -}, - - - -'long': function(module, exports, global, require, undefined){ - // 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; -}, - - - -'max_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; -}, - - - -'min_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; -}, - - - -'objectid': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId aswell as ObjectID -var ObjectId = ObjectID; - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = '' - , number - , value; - - for (var index = 0, len = this.id.length; index < len; index++) { - value = BinaryParser.toByte(this.id[index]); - number = value <= 15 - ? '0' + value.toString(16) - : value.toString(16); - hexString = hexString + number; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; - -}, - - - -'symbol': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; -}, - - - -'timestamp': function(module, exports, global, require, undefined){ - // 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; -}, - - }); - - -if(typeof module != 'undefined' && module.exports ){ - module.exports = bson; - - if( !module.parent ){ - bson(); - } -} - -if(typeof window != 'undefined' && typeof require == 'undefined'){ - window.require = bson.require; -} diff --git a/node_modules/mongodb/node_modules/bson/browser_build/package.json b/node_modules/mongodb/node_modules/bson/browser_build/package.json deleted file mode 100644 index 3ebb58761..000000000 --- a/node_modules/mongodb/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../lib/bson/bson" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/node_modules/mongodb/node_modules/bson/build/Makefile b/node_modules/mongodb/node_modules/bson/build/Makefile deleted file mode 100644 index 12b35d60f..000000000 --- a/node_modules/mongodb/node_modules/bson/build/Makefile +++ /dev/null @@ -1,332 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= flock $(builddir)/linker.lock $(CXX.target) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= $(CXX.host) -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,bson.target.mk)))),) - include bson.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/vagrant/lab4/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/vagrant/.node-gyp/0.10.24/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/vagrant/.node-gyp/0.10.24" "-Dmodule_root_dir=/home/vagrant/lab4/node_modules/mongodb/node_modules/bson" binding.gyp -Makefile: $(srcdir)/../../../../../.node-gyp/0.10.24/common.gypi $(srcdir)/../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d b/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d deleted file mode 100644 index 866c155bc..000000000 --- a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/bson.node := rm -rf "Release/bson.node" && cp -af "Release/obj.target/bson.node" "Release/bson.node" diff --git a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d b/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d deleted file mode 100644 index a7317de71..000000000 --- a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/bson.node := flock ./Release/linker.lock g++ -shared -pthread -rdynamic -m32 -Wl,-soname=bson.node -o Release/obj.target/bson.node -Wl,--start-group Release/obj.target/bson/ext/bson.o -Wl,--end-group diff --git a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d b/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d deleted file mode 100644 index 8859b053b..000000000 --- a/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d +++ /dev/null @@ -1,29 +0,0 @@ -cmd_Release/obj.target/bson/ext/bson.o := g++ '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/vagrant/.node-gyp/0.10.24/src -I/home/vagrant/.node-gyp/0.10.24/deps/uv/include -I/home/vagrant/.node-gyp/0.10.24/deps/v8/include -Wall -Wextra -Wno-unused-parameter -pthread -m32 -O2 -fno-strict-aliasing -fno-tree-vrp -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/bson/ext/bson.o.d.raw -c -o Release/obj.target/bson/ext/bson.o ../ext/bson.cc -Release/obj.target/bson/ext/bson.o: ../ext/bson.cc \ - /home/vagrant/.node-gyp/0.10.24/deps/v8/include/v8.h \ - /home/vagrant/.node-gyp/0.10.24/deps/v8/include/v8stdint.h \ - /home/vagrant/.node-gyp/0.10.24/src/node.h \ - /home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv.h \ - /home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h \ - /home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h \ - /home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-linux.h \ - /home/vagrant/.node-gyp/0.10.24/src/node_object_wrap.h \ - /home/vagrant/.node-gyp/0.10.24/src/node.h \ - /home/vagrant/.node-gyp/0.10.24/src/node_version.h \ - /home/vagrant/.node-gyp/0.10.24/src/node_buffer.h ../ext/bson.h \ - /home/vagrant/.node-gyp/0.10.24/src/node_object_wrap.h ../ext/nan.h -../ext/bson.cc: -/home/vagrant/.node-gyp/0.10.24/deps/v8/include/v8.h: -/home/vagrant/.node-gyp/0.10.24/deps/v8/include/v8stdint.h: -/home/vagrant/.node-gyp/0.10.24/src/node.h: -/home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv.h: -/home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h: -/home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h: -/home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-linux.h: -/home/vagrant/.node-gyp/0.10.24/src/node_object_wrap.h: -/home/vagrant/.node-gyp/0.10.24/src/node.h: -/home/vagrant/.node-gyp/0.10.24/src/node_version.h: -/home/vagrant/.node-gyp/0.10.24/src/node_buffer.h: -../ext/bson.h: -/home/vagrant/.node-gyp/0.10.24/src/node_object_wrap.h: -../ext/nan.h: diff --git a/node_modules/mongodb/node_modules/bson/build/Release/bson.node b/node_modules/mongodb/node_modules/bson/build/Release/bson.node deleted file mode 100644 index 2db1681b2..000000000 Binary files a/node_modules/mongodb/node_modules/bson/build/Release/bson.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node b/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node deleted file mode 100644 index 2db1681b2..000000000 Binary files a/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o b/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o deleted file mode 100644 index 61e532cfd..000000000 Binary files a/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/build/binding.Makefile b/node_modules/mongodb/node_modules/bson/build/binding.Makefile deleted file mode 100644 index 90bf8247b..000000000 --- a/node_modules/mongodb/node_modules/bson/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= build/./. -.PHONY: all -all: - $(MAKE) bson diff --git a/node_modules/mongodb/node_modules/bson/build/bson.target.mk b/node_modules/mongodb/node_modules/bson/build/bson.target.mk deleted file mode 100644 index 47d5b758e..000000000 --- a/node_modules/mongodb/node_modules/bson/build/bson.target.mk +++ /dev/null @@ -1,126 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := bson -DEFS_Debug := \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -pthread \ - -m32 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti - -INCS_Debug := \ - -I/home/vagrant/.node-gyp/0.10.24/src \ - -I/home/vagrant/.node-gyp/0.10.24/deps/uv/include \ - -I/home/vagrant/.node-gyp/0.10.24/deps/v8/include - -DEFS_Release := \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -pthread \ - -m32 \ - -O2 \ - -fno-strict-aliasing \ - -fno-tree-vrp \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti - -INCS_Release := \ - -I/home/vagrant/.node-gyp/0.10.24/src \ - -I/home/vagrant/.node-gyp/0.10.24/deps/uv/include \ - -I/home/vagrant/.node-gyp/0.10.24/deps/v8/include - -OBJS := \ - $(obj).target/$(TARGET)/ext/bson.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m32 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m32 - -LIBS := - -$(obj).target/bson.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/bson.node: LIBS := $(LIBS) -$(obj).target/bson.node: TOOLSET := $(TOOLSET) -$(obj).target/bson.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/bson.node -# Add target alias -.PHONY: bson -bson: $(builddir)/bson.node - -# Copy this to the executable output path. -$(builddir)/bson.node: TOOLSET := $(TOOLSET) -$(builddir)/bson.node: $(obj).target/bson.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/bson.node -# Short alias for building this executable. -.PHONY: bson.node -bson.node: $(obj).target/bson.node $(builddir)/bson.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/bson.node - diff --git a/node_modules/mongodb/node_modules/bson/build/config.gypi b/node_modules/mongodb/node_modules/bson/build/config.gypi deleted file mode 100644 index 91ce77280..000000000 --- a/node_modules/mongodb/node_modules/bson/build/config.gypi +++ /dev/null @@ -1,115 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 0, - "gcc_version": 46, - "host_arch": "ia32", - "node_install_npm": "true", - "node_prefix": "/usr/local", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "node_use_systemtap": "false", - "python": "/usr/bin/python", - "target_arch": "ia32", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "true", - "nodedir": "/home/vagrant/.node-gyp/0.10.24", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "sign_git_tag": "", - "always_auth": "", - "user_agent": "node/v0.10.24 linux ia32", - "bin_links": "true", - "key": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "user": "", - "force": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "cache_max": "null", - "userconfig": "/home/vagrant/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "tmp": "/home/vagrant/tmp", - "depth": "null", - "save_dev": "", - "usage": "", - "https_proxy": "", - "onload_script": "", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/bash", - "prefix": "/usr/local", - "registry": "https://registry.npmjs.org/", - "browser": "", - "cache_lock_wait": "10000", - "save_optional": "", - "searchopts": "", - "versions": "", - "cache": "/home/vagrant/.npm", - "ignore_scripts": "", - "searchsort": "name", - "version": "", - "local_address": "", - "viewer": "man", - "color": "true", - "fetch_retry_mintimeout": "10000", - "umask": "18", - "fetch_retry_maxtimeout": "60000", - "message": "%s", - "cert": "", - "global": "", - "link": "", - "save": "", - "unicode": "true", - "long": "", - "production": "", - "unsafe_perm": "true", - "node_version": "v0.10.24", - "tag": "latest", - "git_tag_version": "true", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "npat": "", - "proprietary_attribs": "true", - "strict_ssl": "true", - "username": "", - "dev": "", - "globalconfig": "/usr/local/etc/npmrc", - "init_module": "/home/vagrant/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/local/etc/npmignore", - "cache_lock_retries": "10", - "group": "1000", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "email": "", - "json": "" - } -} diff --git a/node_modules/mongodb/node_modules/bson/build_browser.js b/node_modules/mongodb/node_modules/bson/build_browser.js deleted file mode 100644 index bb8023844..000000000 --- a/node_modules/mongodb/node_modules/bson/build_browser.js +++ /dev/null @@ -1,7 +0,0 @@ -require('one'); - -one('./package.json') - .tie('bson', BSON) - // .exclude('buffer') - .tie('buffer', {}) - .save('./browser_build/bson.js') \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/ext/Makefile b/node_modules/mongodb/node_modules/bson/ext/Makefile deleted file mode 100644 index 435999ee9..000000000 --- a/node_modules/mongodb/node_modules/bson/ext/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -name = all -JOBS = 1 - -all: - rm -rf build .lock-wscript bson.node - node-waf configure build - cp -R ./build/Release/bson.node . || true - -all_debug: - rm -rf build .lock-wscript bson.node - node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clang: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf configure build - cp -R ./build/Release/bson.node . || true - -clang_debug: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clean: - rm -rf build .lock-wscript bson.node - -.PHONY: all \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/ext/bson.cc b/node_modules/mongodb/node_modules/bson/ext/bson.cc deleted file mode 100644 index 422fc3ee6..000000000 --- a/node_modules/mongodb/node_modules/bson/ext/bson.cc +++ /dev/null @@ -1,1045 +0,0 @@ -//=========================================================================== - -#include -#include -#include -#include -#include - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-parameter" -#endif - -#include - -// this and the above block must be around the v8.h header otherwise -// v8 is not happy -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#include -#include -#include - -#include -#include -#include -#include - -#ifdef __sun - #include -#endif - -#include "bson.h" - -using namespace v8; -using namespace node; - -//=========================================================================== - -void DataStream::WriteObjectId(const Handle& object, const Handle& key) -{ - uint16_t buffer[12]; - object->Get(key)->ToString()->Write(buffer, 0, 12); - for(uint32_t i = 0; i < 12; ++i) - { - *p++ = (char) buffer[i]; - } -} - -void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...) -{ - va_list args; - va_start(args, format); - char* string = (char*) malloc(allocationSize); - vsprintf(string, format, args); - va_end(args); - - throw string; -} - -void DataStream::CheckKey(const Local& keyName) -{ - size_t keyLength = keyName->Utf8Length(); - if(keyLength == 0) return; - - // Allocate space for the key, do not need to zero terminate as WriteUtf8 does it - char* keyStringBuffer = (char*) alloca(keyLength + 1); - // Write the key to the allocated buffer - keyName->WriteUtf8(keyStringBuffer); - // Check for the zero terminator - char* terminator = strchr(keyStringBuffer, 0x00); - - // If the location is not at the end of the string we've got an illegal 0x00 byte somewhere - if(terminator != &keyStringBuffer[keyLength]) { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer); - } - - if(keyStringBuffer[0] == '$') - { - ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer); - } - - if(strchr(keyStringBuffer, '.') != NULL) - { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer); - } -} - -template void BSONSerializer::SerializeDocument(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - Local object = bson->GetSerializeObject(value); - - // Get the object property names - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - Local propertyNames = object->GetPropertyNames(); - #else - Local propertyNames = object->GetOwnPropertyNames(); - #endif - - // Length of the property - int propertyLength = propertyNames->Length(); - for(int i = 0; i < propertyLength; ++i) - { - const Local& propertyName = propertyNames->Get(i)->ToString(); - if(checkKeys) this->CheckKey(propertyName); - - const Local& propertyValue = object->Get(propertyName); - - if(serializeFunctions || !propertyValue->IsFunction()) - { - void* typeLocation = this->BeginWriteType(); - this->WriteString(propertyName); - SerializeValue(typeLocation, propertyValue); - } - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -template void BSONSerializer::SerializeArray(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - - Local array = Local::Cast(value->ToObject()); - uint32_t arrayLength = array->Length(); - - for(uint32_t i = 0; i < arrayLength; ++i) - { - void* typeLocation = this->BeginWriteType(); - this->WriteUInt32String(i); - SerializeValue(typeLocation, array->Get(i)); - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -// This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes. -// The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths) -// and ensures that there is always consistency between bytes counted and bytes written by design. -template void BSONSerializer::SerializeValue(void* typeLocation, const Handle& value) -{ - if(value->IsNumber()) - { - double doubleValue = value->NumberValue(); - int intValue = (int) doubleValue; - if(intValue == doubleValue) - { - this->CommitType(typeLocation, BSON_TYPE_INT); - this->WriteInt32(intValue); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(doubleValue); - } - } - else if(value->IsString()) - { - this->CommitType(typeLocation, BSON_TYPE_STRING); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsBoolean()) - { - this->CommitType(typeLocation, BSON_TYPE_BOOLEAN); - this->WriteBool(value); - } - else if(value->IsArray()) - { - this->CommitType(typeLocation, BSON_TYPE_ARRAY); - SerializeArray(value); - } - else if(value->IsDate()) - { - this->CommitType(typeLocation, BSON_TYPE_DATE); - this->WriteInt64(value); - } - else if(value->IsRegExp()) - { - this->CommitType(typeLocation, BSON_TYPE_REGEXP); - const Handle& regExp = Handle::Cast(value); - - this->WriteString(regExp->GetSource()); - - int flags = regExp->GetFlags(); - if(flags & RegExp::kGlobal) this->WriteByte('s'); - if(flags & RegExp::kIgnoreCase) this->WriteByte('i'); - if(flags & RegExp::kMultiline) this->WriteByte('m'); - this->WriteByte(0); - } - else if(value->IsFunction()) - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsObject()) - { - const Local& object = value->ToObject(); - if(object->Has(NanPersistentToLocal(bson->_bsontypeString))) - { - const Local& constructorString = object->GetConstructorName(); - if(NanPersistentToLocal(bson->longString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_LONG); - this->WriteInt32(object, NanPersistentToLocal(bson->_longLowString)); - this->WriteInt32(object, NanPersistentToLocal(bson->_longHighString)); - } - else if(NanPersistentToLocal(bson->timestampString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP); - this->WriteInt32(object, NanPersistentToLocal(bson->_longLowString)); - this->WriteInt32(object, NanPersistentToLocal(bson->_longHighString)); - } - else if(NanPersistentToLocal(bson->objectIDString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OID); - this->WriteObjectId(object, NanPersistentToLocal(bson->_objectIDidString)); - } - else if(NanPersistentToLocal(bson->binaryString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - uint32_t length = object->Get(NanPersistentToLocal(bson->_binaryPositionString))->Uint32Value(); - Local bufferObj = object->Get(NanPersistentToLocal(bson->_binaryBufferString))->ToObject(); - - this->WriteInt32(length); - this->WriteByte(object, NanPersistentToLocal(bson->_binarySubTypeString)); // write subtype - // If type 0x02 write the array length aswell - if(object->Get(NanPersistentToLocal(bson->_binarySubTypeString))->Int32Value() == 0x02) { - this->WriteInt32(length); - } - // Write the actual data - this->WriteData(Buffer::Data(bufferObj), length); - } - else if(NanPersistentToLocal(bson->doubleString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(object, NanPersistentToLocal(bson->_doubleValueString)); - } - else if(NanPersistentToLocal(bson->symbolString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_SYMBOL); - this->WriteLengthPrefixedString(object->Get(NanPersistentToLocal(bson->_symbolValueString))->ToString()); - } - else if(NanPersistentToLocal(bson->codeString)->StrictEquals(constructorString)) - { - const Local& function = object->Get(NanPersistentToLocal(bson->_codeCodeString))->ToString(); - const Local& scope = object->Get(NanPersistentToLocal(bson->_codeScopeString))->ToObject(); - - // For Node < 0.6.X use the GetPropertyNames - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - uint32_t propertyNameLength = scope->GetPropertyNames()->Length(); - #else - uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length(); - #endif - - if(propertyNameLength > 0) - { - this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE); - void* codeWidthScopeSize = this->BeginWriteSize(); - this->WriteLengthPrefixedString(function->ToString()); - SerializeDocument(scope); - this->CommitSize(codeWidthScopeSize); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(function->ToString()); - } - } - else if(NanPersistentToLocal(bson->dbrefString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - - void* dbRefSize = this->BeginWriteSize(); - - void* refType = this->BeginWriteType(); - this->WriteData("$ref", 5); - SerializeValue(refType, object->Get(NanPersistentToLocal(bson->_dbRefNamespaceString))); - - void* idType = this->BeginWriteType(); - this->WriteData("$id", 4); - SerializeValue(idType, object->Get(NanPersistentToLocal(bson->_dbRefOidString))); - - const Local& refDbValue = object->Get(NanPersistentToLocal(bson->_dbRefDbString)); - if(!refDbValue->IsUndefined()) - { - void* dbType = this->BeginWriteType(); - this->WriteData("$db", 4); - SerializeValue(dbType, refDbValue); - } - - this->WriteByte(0); - this->CommitSize(dbRefSize); - } - else if(NanPersistentToLocal(bson->minKeyString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MIN_KEY); - } - else if(NanPersistentToLocal(bson->maxKeyString)->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MAX_KEY); - } - } - else if(Buffer::HasInstance(value)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(value->ToObject()); - uint32_t length = object->length(); - #else - uint32_t length = Buffer::Length(value->ToObject()); - #endif - - this->WriteInt32(length); - this->WriteByte(0); - this->WriteData(Buffer::Data(value->ToObject()), length); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - SerializeDocument(value); - } - } - else if(value->IsNull() || value->IsUndefined()) - { - this->CommitType(typeLocation, BSON_TYPE_NULL); - } -} - -// Data points to start of element list, length is length of entire document including '\0' but excluding initial size -BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length) -: bson(aBson), - pStart(data), - p(data), - pEnd(data + length - 1) -{ - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length) -: bson(parentSerializer.bson), - pStart(parentSerializer.p), - p(parentSerializer.p), - pEnd(parentSerializer.p + length - 1) -{ - parentSerializer.p += length; - if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds"); - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -Handle BSONDeserializer::ReadCString() -{ - char* start = p; - while(*p++ && (p < pEnd)) { } - if(p > pEnd) { - return Null(); - } - return String::New(start, (int32_t) (p-start-1) ); -} - -int32_t BSONDeserializer::ReadRegexOptions() -{ - int32_t options = 0; - for(;;) - { - switch(*p++) - { - case '\0': return options; - case 's': options |= RegExp::kGlobal; break; - case 'i': options |= RegExp::kIgnoreCase; break; - case 'm': options |= RegExp::kMultiline; break; - } - } -} - -uint32_t BSONDeserializer::ReadIntegerString() -{ - uint32_t value = 0; - while(*p) - { - if(*p < '0' || *p > '9') ThrowAllocatedStringException(64, "Invalid key for array"); - value = value * 10 + *p++ - '0'; - } - ++p; - return value; -} - -Local BSONDeserializer::ReadString() -{ - uint32_t length = ReadUInt32(); - char* start = p; - p += length; - return String::New(start, length-1); -} - -Local BSONDeserializer::ReadObjectId() -{ - uint16_t objectId[12]; - for(size_t i = 0; i < 12; ++i) - { - objectId[i] = *reinterpret_cast(p++); - } - return String::New(objectId, 12); -} - -Handle BSONDeserializer::DeserializeDocument(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeDocumentInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeDocumentInternal(bool promoteLongs) -{ - Local returnObject = Object::New(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - const Handle& name = ReadCString(); - if(name->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString"); - // name->Is - const Handle& value = DeserializeValue(type, promoteLongs); - returnObject->ForceSet(name, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes"); - - // From JavaScript: - // if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - if(returnObject->Has(NanPersistentToLocal(bson->_dbRefIdRefString))) - { - Local argv[] = { returnObject->Get(NanPersistentToLocal(bson->_dbRefRefString)), returnObject->Get(NanPersistentToLocal(bson->_dbRefIdRefString)), returnObject->Get(NanPersistentToLocal(bson->_dbRefDbRefString)) }; - return NanPersistentToLocal(bson->dbrefConstructor)->NewInstance(3, argv); - } - else - { - return returnObject; - } -} - -Handle BSONDeserializer::DeserializeArray(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeArrayInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeArrayInternal(bool promoteLongs) -{ - Local returnArray = Array::New(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - uint32_t index = ReadIntegerString(); - const Handle& value = DeserializeValue(type, promoteLongs); - returnArray->Set(index, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes"); - - return returnArray; -} - -Handle BSONDeserializer::DeserializeValue(BsonType type, bool promoteLongs) -{ - switch(type) - { - case BSON_TYPE_STRING: - return ReadString(); - - case BSON_TYPE_INT: - return Integer::New(ReadInt32()); - - case BSON_TYPE_NUMBER: - return Number::New(ReadDouble()); - - case BSON_TYPE_NULL: - return Null(); - - case BSON_TYPE_UNDEFINED: - return Undefined(); - - case BSON_TYPE_TIMESTAMP: - { - int32_t lowBits = ReadInt32(); - int32_t highBits = ReadInt32(); - Local argv[] = { Int32::New(lowBits), Int32::New(highBits) }; - return NanPersistentToLocal(bson->timestampConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_BOOLEAN: - return (ReadByte() != 0) ? True() : False(); - - case BSON_TYPE_REGEXP: - { - const Handle& regex = ReadCString(); - if(regex->IsNull()) ThrowAllocatedStringException(64, "Bad BSON Document: illegal CString"); - int32_t options = ReadRegexOptions(); - return RegExp::New(regex->ToString(), (RegExp::Flags) options); - } - - case BSON_TYPE_CODE: - { - const Local& code = ReadString(); - const Local& scope = Object::New(); - Local argv[] = { code, scope }; - return NanPersistentToLocal(bson->codeConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_CODE_W_SCOPE: - { - ReadUInt32(); - const Local& code = ReadString(); - const Handle& scope = DeserializeDocument(promoteLongs); - Local argv[] = { code, scope->ToObject() }; - return NanPersistentToLocal(bson->codeConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_OID: - { - Local argv[] = { ReadObjectId() }; - return NanPersistentToLocal(bson->objectIDConstructor)->NewInstance(1, argv); - } - - case BSON_TYPE_BINARY: - { - uint32_t length = ReadUInt32(); - uint32_t subType = ReadByte(); - if(subType == 0x02) { - length = ReadInt32(); - } - - Local buffer = NanNewBufferHandle(p, length); - p += length; - - Handle argv[] = { buffer, Uint32::New(subType) }; - return NanPersistentToLocal(bson->binaryConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_LONG: - { - // Read 32 bit integers - int32_t lowBits = (int32_t) ReadInt32(); - int32_t highBits = (int32_t) ReadInt32(); - - // Promote long is enabled - if(promoteLongs) { - // If value is < 2^53 and >-2^53 - if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) { - // Adjust the pointer and read as 64 bit value - p -= 8; - // Read the 64 bit value - int64_t finalValue = (int64_t) ReadInt64(); - return Number::New(finalValue); - } - } - - // Decode the Long value - Local argv[] = { Int32::New(lowBits), Int32::New(highBits) }; - return NanPersistentToLocal(bson->longConstructor)->NewInstance(2, argv); - } - - case BSON_TYPE_DATE: - return Date::New((double) ReadInt64()); - - case BSON_TYPE_ARRAY: - return DeserializeArray(promoteLongs); - - case BSON_TYPE_OBJECT: - return DeserializeDocument(promoteLongs); - - case BSON_TYPE_SYMBOL: - { - const Local& string = ReadString(); - Local argv[] = { string }; - return NanPersistentToLocal(bson->symbolConstructor)->NewInstance(1, argv); - } - - case BSON_TYPE_MIN_KEY: - return NanPersistentToLocal(bson->minKeyConstructor)->NewInstance(); - - case BSON_TYPE_MAX_KEY: - return NanPersistentToLocal(bson->maxKeyConstructor)->NewInstance(); - - default: - ThrowAllocatedStringException(64, "Unhandled BSON Type: %d", type); - } - - return v8::Null(); -} - -Persistent BSON::constructor_template; - -BSON::BSON() : ObjectWrap() -{ - // Setup pre-allocated comparision objects - NanAssignPersistent(String, _bsontypeString, String::New("_bsontype")); - NanAssignPersistent(String, _longLowString, String::New("low_")); - NanAssignPersistent(String, _longHighString, String::New("high_")); - NanAssignPersistent(String, _objectIDidString, String::New("id")); - NanAssignPersistent(String, _binaryPositionString, String::New("position")); - NanAssignPersistent(String, _binarySubTypeString, String::New("sub_type")); - NanAssignPersistent(String, _binaryBufferString, String::New("buffer")); - NanAssignPersistent(String, _doubleValueString, String::New("value")); - NanAssignPersistent(String, _symbolValueString, String::New("value")); - NanAssignPersistent(String, _dbRefRefString, String::New("$ref")); - NanAssignPersistent(String, _dbRefIdRefString, String::New("$id")); - NanAssignPersistent(String, _dbRefDbRefString, String::New("$db")); - NanAssignPersistent(String, _dbRefNamespaceString, String::New("namespace")); - NanAssignPersistent(String, _dbRefDbString, String::New("db")); - NanAssignPersistent(String, _dbRefOidString, String::New("oid")); - NanAssignPersistent(String, _codeCodeString, String::New("code")); - NanAssignPersistent(String, _codeScopeString, String::New("scope")); - NanAssignPersistent(String, _toBSONString, String::New("toBSON")); - - NanAssignPersistent(String, longString, String::New("Long")); - NanAssignPersistent(String, objectIDString, String::New("ObjectID")); - NanAssignPersistent(String, binaryString, String::New("Binary")); - NanAssignPersistent(String, codeString, String::New("Code")); - NanAssignPersistent(String, dbrefString, String::New("DBRef")); - NanAssignPersistent(String, symbolString, String::New("Symbol")); - NanAssignPersistent(String, doubleString, String::New("Double")); - NanAssignPersistent(String, timestampString, String::New("Timestamp")); - NanAssignPersistent(String, minKeyString, String::New("MinKey")); - NanAssignPersistent(String, maxKeyString, String::New("MaxKey")); -} - -void BSON::Initialize(v8::Handle target) -{ - // Grab the scope of the call from Node - NanScope(); - // Define a new function template - Local t = FunctionTemplate::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(String::NewSymbol("BSON")); - - // Instance methods - NODE_SET_PROTOTYPE_METHOD(t, "calculateObjectSize", CalculateObjectSize); - NODE_SET_PROTOTYPE_METHOD(t, "serialize", BSONSerialize); - NODE_SET_PROTOTYPE_METHOD(t, "serializeWithBufferAndIndex", SerializeWithBufferAndIndex); - NODE_SET_PROTOTYPE_METHOD(t, "deserialize", BSONDeserialize); - NODE_SET_PROTOTYPE_METHOD(t, "deserializeStream", BSONDeserializeStream); - - NanAssignPersistent(FunctionTemplate, constructor_template, t); - - target->ForceSet(String::NewSymbol("BSON"), t->GetFunction()); -} - -// Create a new instance of BSON and passing it the existing context -NAN_METHOD(BSON::New) -{ - NanScope(); - - // Check that we have an array - if(args.Length() == 1 && args[0]->IsArray()) - { - // Cast the array to a local reference - Local array = Local::Cast(args[0]); - - if(array->Length() > 0) - { - // Create a bson object instance and return it - BSON *bson = new BSON(); - - uint32_t foundClassesMask = 0; - - // Iterate over all entries to save the instantiate funtions - for(uint32_t i = 0; i < array->Length(); i++) { - // Let's get a reference to the function - Local func = Local::Cast(array->Get(i)); - Local functionName = func->GetName()->ToString(); - - // Save the functions making them persistant handles (they don't get collected) - if(functionName->StrictEquals(NanPersistentToLocal(bson->longString))) { - NanAssignPersistent(Function, bson->longConstructor, func); - foundClassesMask |= 1; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->objectIDString))) { - NanAssignPersistent(Function, bson->objectIDConstructor, func); - foundClassesMask |= 2; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->binaryString))) { - NanAssignPersistent(Function, bson->binaryConstructor, func); - foundClassesMask |= 4; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->codeString))) { - NanAssignPersistent(Function, bson->codeConstructor, func); - foundClassesMask |= 8; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->dbrefString))) { - NanAssignPersistent(Function, bson->dbrefConstructor, func); - foundClassesMask |= 0x10; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->symbolString))) { - NanAssignPersistent(Function, bson->symbolConstructor, func); - foundClassesMask |= 0x20; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->doubleString))) { - NanAssignPersistent(Function, bson->doubleConstructor, func); - foundClassesMask |= 0x40; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->timestampString))) { - NanAssignPersistent(Function, bson->timestampConstructor, func); - foundClassesMask |= 0x80; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->minKeyString))) { - NanAssignPersistent(Function, bson->minKeyConstructor, func); - foundClassesMask |= 0x100; - } else if(functionName->StrictEquals(NanPersistentToLocal(bson->maxKeyString))) { - NanAssignPersistent(Function, bson->maxKeyConstructor, func); - foundClassesMask |= 0x200; - } - } - - // Check if we have the right number of constructors otherwise throw an error - if(foundClassesMask != 0x3ff) { - delete bson; - return NanThrowError("Missing function constructor for either [Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey]"); - } else { - bson->Wrap(args.This()); - NanReturnValue(args.This()); - } - } - else - { - return NanThrowError("No types passed in"); - } - } - else - { - return NanThrowTypeError("Argument passed in must be an array of types"); - } -} - -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ - -NAN_METHOD(BSON::BSONDeserialize) -{ - NanScope(); - - // Fail if the first argument is not a string or a buffer - if(args.Length() > 1 && !args[0]->IsString() && !Buffer::HasInstance(args[0])) - return NanThrowError("First Argument must be a Buffer or String."); - - // Promote longs - bool promoteLongs = true; - - // If we have an options object - if(args.Length() == 2 && args[1]->IsObject()) { - Local options = args[1]->ToObject(); - - if(options->Has(String::New("promoteLongs"))) { - promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Define pointer to data - Local obj = args[0]->ToObject(); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // If we passed in a buffer, let's unpack it, otherwise let's unpack the string - if(Buffer::HasInstance(obj)) - { -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Validate that we have at least 5 bytes - if(length < 5) return NanThrowError("corrupt bson message < 5 bytes long"); - - try - { - BSONDeserializer deserializer(bson, data, length); - // deserializer.promoteLongs = promoteLongs; - NanReturnValue(deserializer.DeserializeDocument(promoteLongs)); - } - catch(char* exception) - { - Local error = String::New(exception); - free(exception); - return NanThrowError(error); - } - - } - else - { - // The length of the data for this encoding - ssize_t len = DecodeBytes(args[0], BINARY); - - // Validate that we have at least 5 bytes - if(len < 5) return NanThrowError("corrupt bson message < 5 bytes long"); - - // Let's define the buffer size - char* data = (char *)malloc(len); - DecodeWrite(data, len, args[0], BINARY); - - try - { - BSONDeserializer deserializer(bson, data, len); - // deserializer.promoteLongs = promoteLongs; - Handle result = deserializer.DeserializeDocument(promoteLongs); - free(data); - NanReturnValue(result); - - } - catch(char* exception) - { - Local error = String::New(exception); - free(exception); - free(data); - return NanThrowError(error); - } - } -} - -Local BSON::GetSerializeObject(const Handle& argValue) -{ - Local object = argValue->ToObject(); - if(object->Has(NanPersistentToLocal(_toBSONString))) - { - const Local& toBSON = object->Get(NanPersistentToLocal(_toBSONString)); - if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); - - Local result = Local::Cast(toBSON)->Call(object, 0, NULL); - if(!result->IsObject()) ThrowAllocatedStringException(64, "toBSON function did not return an object"); - return result->ToObject(); - } - else - { - return object; - } -} - -NAN_METHOD(BSON::BSONSerialize) -{ - NanScope(); - - if(args.Length() == 1 && !args[0]->IsObject()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 3 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean() && !args[3]->IsBoolean()) return NanThrowError("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - if(args.Length() > 4) return NanThrowError("One, two, tree or four arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - - // Check if we have an array as the object - if(args[0]->IsArray()) return NanThrowError("Only javascript objects supported"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Calculate the total size of the document in binary form to ensure we only allocate memory once - // With serialize function - bool serializeFunctions = (args.Length() >= 4) && args[3]->BooleanValue(); - - char *serialized_object = NULL; - size_t object_size; - try - { - Local object = bson->GetSerializeObject(args[0]); - - BSONSerializer counter(bson, false, serializeFunctions); - counter.SerializeDocument(object); - object_size = counter.GetSerializeSize(); - - // Allocate the memory needed for the serialization - serialized_object = (char *)malloc(object_size); - - // Check if we have a boolean value - bool checkKeys = args.Length() >= 3 && args[1]->IsBoolean() && args[1]->BooleanValue(); - BSONSerializer data(bson, checkKeys, serializeFunctions, serialized_object); - data.SerializeDocument(object); - } - catch(char *err_msg) - { - free(serialized_object); - Local error = String::New(err_msg); - free(err_msg); - return NanThrowError(error); - } - - // If we have 3 arguments - if(args.Length() == 3 || args.Length() == 4) - { - Local buffer = NanNewBufferHandle(serialized_object, object_size); - free(serialized_object); - NanReturnValue(buffer); - } - else - { - Local bin_value = Encode(serialized_object, object_size, BINARY)->ToString(); - free(serialized_object); - NanReturnValue(bin_value); - } -} - -NAN_METHOD(BSON::CalculateObjectSize) -{ - NanScope(); - // Ensure we have a valid object - if(args.Length() == 1 && !args[0]->IsObject()) return NanThrowError("One argument required - [object]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return NanThrowError("Two arguments required - [object, boolean]"); - if(args.Length() > 3) return NanThrowError("One or two arguments required - [object] or [object, boolean]"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - bool serializeFunctions = (args.Length() >= 2) && args[1]->BooleanValue(); - BSONSerializer countSerializer(bson, false, serializeFunctions); - countSerializer.SerializeDocument(args[0]); - - // Return the object size - NanReturnValue(Uint32::New((uint32_t) countSerializer.GetSerializeSize())); -} - -NAN_METHOD(BSON::SerializeWithBufferAndIndex) -{ - NanScope(); - - //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, ->, buffer, index) { - // Ensure we have the correct values - if(args.Length() > 5) return NanThrowError("Four or five parameters required [object, boolean, Buffer, int] or [object, boolean, Buffer, int, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32()) return NanThrowError("Four parameters required [object, boolean, Buffer, int]"); - if(args.Length() == 5 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32() && !args[4]->IsBoolean()) return NanThrowError("Four parameters required [object, boolean, Buffer, int, boolean]"); - - uint32_t index; - size_t object_size; - - try - { - BSON *bson = ObjectWrap::Unwrap(args.This()); - - Local obj = args[2]->ToObject(); - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); - - index = args[3]->Uint32Value(); - bool checkKeys = args.Length() >= 4 && args[1]->IsBoolean() && args[1]->BooleanValue(); - bool serializeFunctions = (args.Length() == 5) && args[4]->BooleanValue(); - - BSONSerializer dataSerializer(bson, checkKeys, serializeFunctions, data+index); - dataSerializer.SerializeDocument(bson->GetSerializeObject(args[0])); - object_size = dataSerializer.GetSerializeSize(); - - if(object_size + index > length) return NanThrowError("Serious error - overflowed buffer!!"); - } - catch(char *exception) - { - Local error = String::New(exception); - free(exception); - return NanThrowError(error); - } - - NanReturnValue(Uint32::New((uint32_t) (index + object_size - 1))); -} - -NAN_METHOD(BSON::BSONDeserializeStream) -{ - NanScope(); - - // At least 3 arguments required - if(args.Length() < 5) return NanThrowError("Arguments required (Buffer(data), Number(index in data), Number(number of documents to deserialize), Array(results), Number(index in the array), Object(optional))"); - - // If the number of argumets equals 3 - if(args.Length() >= 5) - { - if(!Buffer::HasInstance(args[0])) return NanThrowError("First argument must be Buffer instance"); - if(!args[1]->IsUint32()) return NanThrowError("Second argument must be a positive index number"); - if(!args[2]->IsUint32()) return NanThrowError("Third argument must be a positive number of documents to deserialize"); - if(!args[3]->IsArray()) return NanThrowError("Fourth argument must be an array the size of documents to deserialize"); - if(!args[4]->IsUint32()) return NanThrowError("Sixth argument must be a positive index number"); - } - - // If we have 4 arguments - if(args.Length() == 6 && !args[5]->IsObject()) return NanThrowError("Fifth argument must be an object with options"); - - // Define pointer to data - Local obj = args[0]->ToObject(); - uint32_t numberOfDocuments = args[2]->Uint32Value(); - uint32_t index = args[1]->Uint32Value(); - uint32_t resultIndex = args[4]->Uint32Value(); - bool promoteLongs = true; - - // Check for the value promoteLongs in the options object - if(args.Length() == 6) { - Local options = args[5]->ToObject(); - - // Check if we have the promoteLong variable - if(options->Has(String::New("promoteLongs"))) { - promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Unpack the buffer variable -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Local buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Fetch the documents - Local documents = args[3]->ToObject(); - - BSONDeserializer deserializer(bson, data+index, length-index); - for(uint32_t i = 0; i < numberOfDocuments; i++) - { - try - { - documents->Set(i + resultIndex, deserializer.DeserializeDocument(promoteLongs)); - } - catch (char* exception) - { - Local error = String::New(exception); - free(exception); - return NanThrowError(error); - } - } - - // Return new index of parsing - NanReturnValue(Uint32::New((uint32_t) (index + deserializer.GetSerializeSize()))); -} - -// Exporting function -extern "C" void init(Handle target) -{ - NanScope(); - BSON::Initialize(target); -} - -NODE_MODULE(bson, BSON::Initialize); diff --git a/node_modules/mongodb/node_modules/bson/ext/bson.h b/node_modules/mongodb/node_modules/bson/ext/bson.h deleted file mode 100644 index dad8412ac..000000000 --- a/node_modules/mongodb/node_modules/bson/ext/bson.h +++ /dev/null @@ -1,278 +0,0 @@ -//=========================================================================== - -#ifndef BSON_H_ -#define BSON_H_ - -//=========================================================================== - -#ifdef __arm__ -#define USE_MISALIGNED_MEMORY_ACCESS 0 -#else -#define USE_MISALIGNED_MEMORY_ACCESS 1 -#endif - -#include -#include -#include -#include "nan.h" - -using namespace v8; -using namespace node; - -//=========================================================================== - -enum BsonType -{ - BSON_TYPE_NUMBER = 1, - BSON_TYPE_STRING = 2, - BSON_TYPE_OBJECT = 3, - BSON_TYPE_ARRAY = 4, - BSON_TYPE_BINARY = 5, - BSON_TYPE_UNDEFINED = 6, - BSON_TYPE_OID = 7, - BSON_TYPE_BOOLEAN = 8, - BSON_TYPE_DATE = 9, - BSON_TYPE_NULL = 10, - BSON_TYPE_REGEXP = 11, - BSON_TYPE_CODE = 13, - BSON_TYPE_SYMBOL = 14, - BSON_TYPE_CODE_W_SCOPE = 15, - BSON_TYPE_INT = 16, - BSON_TYPE_TIMESTAMP = 17, - BSON_TYPE_LONG = 18, - BSON_TYPE_MAX_KEY = 0x7f, - BSON_TYPE_MIN_KEY = 0xff -}; - -//=========================================================================== - -template class BSONSerializer; - -class BSON : public ObjectWrap { -public: - BSON(); - ~BSON() {} - - static void Initialize(Handle target); - static NAN_METHOD(BSONDeserializeStream); - - // JS based objects - static NAN_METHOD(BSONSerialize); - static NAN_METHOD(BSONDeserialize); - - // Calculate size of function - static NAN_METHOD(CalculateObjectSize); - static NAN_METHOD(SerializeWithBufferAndIndex); - - // Constructor used for creating new BSON objects from C++ - static Persistent constructor_template; - -private: - static NAN_METHOD(New); - static Handle deserialize(BSON *bson, char *data, uint32_t dataLength, uint32_t startIndex, bool is_array_item); - - // BSON type instantiate functions - Persistent longConstructor; - Persistent objectIDConstructor; - Persistent binaryConstructor; - Persistent codeConstructor; - Persistent dbrefConstructor; - Persistent symbolConstructor; - Persistent doubleConstructor; - Persistent timestampConstructor; - Persistent minKeyConstructor; - Persistent maxKeyConstructor; - - // Equality Objects - Persistent longString; - Persistent objectIDString; - Persistent binaryString; - Persistent codeString; - Persistent dbrefString; - Persistent symbolString; - Persistent doubleString; - Persistent timestampString; - Persistent minKeyString; - Persistent maxKeyString; - - // Equality speed up comparison objects - Persistent _bsontypeString; - Persistent _longLowString; - Persistent _longHighString; - Persistent _objectIDidString; - Persistent _binaryPositionString; - Persistent _binarySubTypeString; - Persistent _binaryBufferString; - Persistent _doubleValueString; - Persistent _symbolValueString; - - Persistent _dbRefRefString; - Persistent _dbRefIdRefString; - Persistent _dbRefDbRefString; - Persistent _dbRefNamespaceString; - Persistent _dbRefDbString; - Persistent _dbRefOidString; - - Persistent _codeCodeString; - Persistent _codeScopeString; - Persistent _toBSONString; - - Local GetSerializeObject(const Handle& object); - - template friend class BSONSerializer; - friend class BSONDeserializer; -}; - -//=========================================================================== - -class CountStream -{ -public: - CountStream() : count(0) { } - - void WriteByte(int value) { ++count; } - void WriteByte(const Handle&, const Handle&) { ++count; } - void WriteBool(const Handle& value) { ++count; } - void WriteInt32(int32_t value) { count += 4; } - void WriteInt32(const Handle& value) { count += 4; } - void WriteInt32(const Handle& object, const Handle& key) { count += 4; } - void WriteInt64(int64_t value) { count += 8; } - void WriteInt64(const Handle& value) { count += 8; } - void WriteDouble(double value) { count += 8; } - void WriteDouble(const Handle& value) { count += 8; } - void WriteDouble(const Handle&, const Handle&) { count += 8; } - void WriteUInt32String(uint32_t name) { char buffer[32]; count += sprintf(buffer, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { count += value->Utf8Length()+5; } - void WriteObjectId(const Handle& object, const Handle& key) { count += 12; } - void WriteString(const Local& value) { count += value->Utf8Length() + 1; } // This returns the number of bytes exclusive of the NULL terminator - void WriteData(const char* data, size_t length) { count += length; } - - void* BeginWriteType() { ++count; return NULL; } - void CommitType(void*, BsonType) { } - void* BeginWriteSize() { count += 4; return NULL; } - void CommitSize(void*) { } - - size_t GetSerializeSize() const { return count; } - - // Do nothing. CheckKey is implemented for DataStream - void CheckKey(const Local&) { } - -private: - size_t count; -}; - -class DataStream -{ -public: - DataStream(char* aDestinationBuffer) : destinationBuffer(aDestinationBuffer), p(aDestinationBuffer) { } - - void WriteByte(int value) { *p++ = value; } - void WriteByte(const Handle& object, const Handle& key) { *p++ = object->Get(key)->Int32Value(); } -#if USE_MISALIGNED_MEMORY_ACCESS - void WriteInt32(int32_t value) { *reinterpret_cast(p) = value; p += 4; } - void WriteInt64(int64_t value) { *reinterpret_cast(p) = value; p += 8; } - void WriteDouble(double value) { *reinterpret_cast(p) = value; p += 8; } -#else - void WriteInt32(int32_t value) { memcpy(p, &value, 4); p += 4; } - void WriteInt64(int64_t value) { memcpy(p, &value, 8); p += 8; } - void WriteDouble(double value) { memcpy(p, &value, 8); p += 8; } -#endif - void WriteBool(const Handle& value) { WriteByte(value->BooleanValue() ? 1 : 0); } - void WriteInt32(const Handle& value) { WriteInt32(value->Int32Value()); } - void WriteInt32(const Handle& object, const Handle& key) { WriteInt32(object->Get(key)); } - void WriteInt64(const Handle& value) { WriteInt64(value->IntegerValue()); } - void WriteDouble(const Handle& value) { WriteDouble(value->NumberValue()); } - void WriteDouble(const Handle& object, const Handle& key) { WriteDouble(object->Get(key)); } - void WriteUInt32String(uint32_t name) { p += sprintf(p, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { WriteInt32(value->Utf8Length()+1); WriteString(value); } - void WriteObjectId(const Handle& object, const Handle& key); - void WriteString(const Local& value) { p += value->WriteUtf8(p); } // This returns the number of bytes inclusive of the NULL terminator. - void WriteData(const char* data, size_t length) { memcpy(p, data, length); p += length; } - - void* BeginWriteType() { void* returnValue = p; p++; return returnValue; } - void CommitType(void* beginPoint, BsonType value) { *reinterpret_cast(beginPoint) = value; } - void* BeginWriteSize() { void* returnValue = p; p += 4; return returnValue; } - -#if USE_MISALIGNED_MEMORY_ACCESS - void CommitSize(void* beginPoint) { *reinterpret_cast(beginPoint) = (int32_t) (p - (char*) beginPoint); } -#else - void CommitSize(void* beginPoint) { int32_t value = (int32_t) (p - (char*) beginPoint); memcpy(beginPoint, &value, 4); } -#endif - - size_t GetSerializeSize() const { return p - destinationBuffer; } - - void CheckKey(const Local& keyName); - -protected: - char *const destinationBuffer; // base, never changes - char* p; // cursor into buffer -}; - -template class BSONSerializer : public T -{ -private: - typedef T Inherited; - -public: - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions) : Inherited(), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions, char* parentParam) : Inherited(parentParam), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - - void SerializeDocument(const Handle& value); - void SerializeArray(const Handle& value); - void SerializeValue(void* typeLocation, const Handle& value); - -private: - bool checkKeys; - bool serializeFunctions; - BSON* bson; -}; - -//=========================================================================== - -class BSONDeserializer -{ -public: - BSONDeserializer(BSON* aBson, char* data, size_t length); - BSONDeserializer(BSONDeserializer& parentSerializer, size_t length); - - Handle DeserializeDocument(bool promoteLongs); - - bool HasMoreData() const { return p < pEnd; } - Handle ReadCString(); - uint32_t ReadIntegerString(); - int32_t ReadRegexOptions(); - Local ReadString(); - Local ReadObjectId(); - - unsigned char ReadByte() { return *reinterpret_cast(p++); } -#if USE_MISALIGNED_MEMORY_ACCESS - int32_t ReadInt32() { int32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue = *reinterpret_cast(p); p += 8; return returnValue; } - double ReadDouble() { double returnValue = *reinterpret_cast(p); p += 8; return returnValue; } -#else - int32_t ReadInt32() { int32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } - double ReadDouble() { double returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } -#endif - - size_t GetSerializeSize() const { return p - pStart; } - -private: - Handle DeserializeArray(bool promoteLongs); - Handle DeserializeValue(BsonType type, bool promoteLongs); - Handle DeserializeDocumentInternal(bool promoteLongs); - Handle DeserializeArrayInternal(bool promoteLongs); - - BSON* bson; - char* const pStart; - char* p; - char* const pEnd; -}; - -//=========================================================================== - -#endif // BSON_H_ - -//=========================================================================== diff --git a/node_modules/mongodb/node_modules/bson/ext/index.js b/node_modules/mongodb/node_modules/bson/ext/index.js deleted file mode 100644 index 65affae43..000000000 --- a/node_modules/mongodb/node_modules/bson/ext/index.js +++ /dev/null @@ -1,35 +0,0 @@ -var bson = null; - -try { - // Load the precompiled win32 binary - if(process.platform == "win32" && process.arch == "x64") { - bson = require('./win32/x64/bson'); - } else if(process.platform == "win32" && process.arch == "ia32") { - bson = require('./win32/ia32/bson'); - } else { - bson = require('../build/Release/bson'); - } -} catch(err) { - console.error("Failed to load c++ bson extension, using pure JS version"); - bson = require('../lib/bson/bson'); -} - -exports.BSON = bson.BSON; -exports.Long = require('../lib/bson/long').Long; -exports.ObjectID = require('../lib/bson/objectid').ObjectID; -exports.DBRef = require('../lib/bson/db_ref').DBRef; -exports.Code = require('../lib/bson/code').Code; -exports.Timestamp = require('../lib/bson/timestamp').Timestamp; -exports.Binary = require('../lib/bson/binary').Binary; -exports.Double = require('../lib/bson/double').Double; -exports.MaxKey = require('../lib/bson/max_key').MaxKey; -exports.MinKey = require('../lib/bson/min_key').MinKey; -exports.Symbol = require('../lib/bson/symbol').Symbol; - -// Just add constants tot he Native BSON parser -exports.BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -exports.BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -exports.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -exports.BSON.BSON_BINARY_SUBTYPE_UUID = 3; -exports.BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -exports.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/node_modules/mongodb/node_modules/bson/ext/nan.h b/node_modules/mongodb/node_modules/bson/ext/nan.h deleted file mode 100644 index 822cb4dad..000000000 --- a/node_modules/mongodb/node_modules/bson/ext/nan.h +++ /dev/null @@ -1,1196 +0,0 @@ -/********************************************************************************** - * NAN - Native Abstractions for Node.js - * - * Copyright (c) 2014 NAN contributors: - * - Rod Vagg - * - Benjamin Byholm - * - Trevor Norris - * - Nathan Rajlich - * - Brett Lawson - * - Ben Noordhuis - * - * MIT +no-false-attribs License - * - * Version 0.8.0 (current Node unstable: 0.11.10, Node stable: 0.10.24) - * - * ChangeLog: - * * 0.8.0 Jan 9 2014 - * - NanDispose -> NanDisposePersistent, deprecate NanDispose - * - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() - * - * * 0.7.1 Jan 9 2014 - * - Fixes to work against debug builds of Node - * - Safer NanPersistentToLocal (avoid reinterpret_cast) - * - Speed up common NanRawString case by only extracting flattened string when necessary - * - * * 0.7.0 Dec 17 2013 - * - New no-arg form of NanCallback() constructor. - * - NanCallback#Call takes Handle rather than Local - * - Removed deprecated NanCallback#Run method, use NanCallback#Call instead - * - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS - * - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() - * - Introduce NanRawString() for char* (or appropriate void*) from v8::String - * (replacement for NanFromV8String) - * - Introduce NanCString() for null-terminated char* from v8::String - * - * * 0.6.0 Nov 21 2013 - * - Introduce NanNewLocal(v8::Handle value) for use in place of - * v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - * - * * 0.5.2 Nov 16 2013 - * - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - * - * * 0.5.1 Nov 12 2013 - * - Use node::MakeCallback() instead of direct v8::Function::Call() - * - * * 0.5.0 Nov 11 2013 - * - Added @TooTallNate as collaborator - * - New, much simpler, "include_dirs" for binding.gyp - * - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - * - * * 0.4.4 Nov 2 2013 - * - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - * - * * 0.4.3 Nov 2 2013 - * - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - * - * * 0.4.2 Nov 2 2013 - * - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - * Node 0.11.8 release. - * - * * 0.4.1 Sep 16 2013 - * - Added explicit `#include ` as it was removed from node.h for v0.11.8 - * - * * 0.4.0 Sep 2 2013 - * - Added NAN_INLINE and NAN_DEPRECATED and made use of them - * - Added NanError, NanTypeError and NanRangeError - * - Cleaned up code - * - * * 0.3.2 Aug 30 2013 - * - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - * in NanAsyncWorker - * - * * 0.3.1 Aug 20 2013 - * - fix "not all control paths return a value" compile warning on some platforms - * - * * 0.3.0 Aug 19 2013 - * - Made NAN work with NPM - * - Lots of fixes to NanFromV8String, pulling in features from new Node core - * - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - * - Added optional error number argument for NanThrowError() - * - Added NanInitPersistent() - * - Added NanReturnNull() and NanReturnEmptyString() - * - Added NanLocker and NanUnlocker - * - Added missing scopes - * - Made sure to clear disposed Persistent handles - * - Changed NanAsyncWorker to allocate error messages on the heap - * - Changed NanThrowError(Local) to NanThrowError(Handle) - * - Fixed leak in NanAsyncWorker when errmsg is used - * - * * 0.2.2 Aug 5 2013 - * - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - * - * * 0.2.1 Aug 5 2013 - * - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - * NanFromV8String() - * - * * 0.2.0 Aug 5 2013 - * - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - * NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - * - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - * _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - * _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - * _NAN_PROPERTY_QUERY_ARGS - * - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - * - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - * NAN_WEAK_CALLBACK_DATA, NanMakeWeak - * - Renamed THROW_ERROR to _NAN_THROW_ERROR - * - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - * - Added NanBufferUse(char*, uint32_t) - * - Added NanNewContextHandle(v8::ExtensionConfiguration*, - * v8::Handle, v8::Handle) - * - Fixed broken NanCallback#GetFunction() - * - Added optional encoding and size arguments to NanFromV8String() - * - Added NanGetPointerSafe() and NanSetPointerSafe() - * - Added initial test suite (to be expanded) - * - Allow NanUInt32OptionValue to convert any Number object - * - * * 0.1.0 Jul 21 2013 - * - Added `NAN_GETTER`, `NAN_SETTER` - * - Added `NanThrowError` with single Local argument - * - Added `NanNewBufferHandle` with single uint32_t argument - * - Added `NanHasInstance(Persistent&, Handle)` - * - Added `Local NanCallback#GetFunction()` - * - Added `NanCallback#Call(int, Local[])` - * - Deprecated `NanCallback#Run(int, Local[])` in favour of Call - * - * See https://github.com/rvagg/nan for the latest update to this file - **********************************************************************************/ - -#ifndef NAN_H -#define NAN_H - -#include -#include -#include -#include -#include -#include - -#if defined(__GNUC__) && !defined(DEBUG) -# define NAN_INLINE(declarator) inline __attribute__((always_inline)) declarator -#elif defined(_MSC_VER) && !defined(DEBUG) -# define NAN_INLINE(declarator) __forceinline declarator -#else -# define NAN_INLINE(declarator) inline declarator -#endif - -#if defined(__GNUC__) && !V8_DISABLE_DEPRECATIONS -# define NAN_DEPRECATED(declarator) __attribute__((deprecated)) declarator -#elif defined(_MSC_VER) && !V8_DISABLE_DEPRECATIONS -# define NAN_DEPRECATED(declarator) __declspec(deprecated) declarator -#else -# define NAN_DEPRECATED(declarator) declarator -#endif - -// some generic helpers - -template static NAN_INLINE(bool NanSetPointerSafe( - T *var - , T val -)) { - if (var) { - *var = val; - return true; - } else { - return false; - } -} - -template static NAN_INLINE(T NanGetPointerSafe( - T *var - , T fallback = reinterpret_cast(0) -)) { - if (var) { - return *var; - } else { - return fallback; - } -} - -#define NanSymbol(value) v8::String::NewSymbol(value) - -static NAN_INLINE(bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt, bool def -)) { - if (def) { - return optionsObj.IsEmpty() - || !optionsObj->Has(opt) - || optionsObj->Get(opt)->BooleanValue(); - } else { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->BooleanValue(); - } -} - -static NAN_INLINE(bool NanBooleanOptionValue( - v8::Local optionsObj - , v8::Handle opt -)) { - return NanBooleanOptionValue(optionsObj, opt, false); -} - -static NAN_INLINE(uint32_t NanUInt32OptionValue( - v8::Local optionsObj - , v8::Handle opt - , uint32_t def -)) { - return !optionsObj.IsEmpty() - && optionsObj->Has(opt) - && optionsObj->Get(opt)->IsNumber() - ? optionsObj->Get(opt)->Uint32Value() - : def; -} - -#if (NODE_MODULE_VERSION > 0x000B) -// Node 0.11+ (0.11.3 and below won't compile with these) - -static v8::Isolate* nan_isolate = v8::Isolate::GetCurrent(); - -# define _NAN_METHOD_ARGS_TYPE const v8::FunctionCallbackInfo& -# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args -# define _NAN_METHOD_RETURN_TYPE void - -# define _NAN_GETTER_ARGS_TYPE const v8::PropertyCallbackInfo& -# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args -# define _NAN_GETTER_RETURN_TYPE void - -# define _NAN_SETTER_ARGS_TYPE const v8::PropertyCallbackInfo& -# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args -# define _NAN_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_GETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args -# define _NAN_PROPERTY_GETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_SETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args -# define _NAN_PROPERTY_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args -# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE void - -# define _NAN_PROPERTY_DELETER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_DELETER_ARGS \ - _NAN_PROPERTY_DELETER_ARGS_TYPE args -# define _NAN_PROPERTY_DELETER_RETURN_TYPE void - -# define _NAN_PROPERTY_QUERY_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args -# define _NAN_PROPERTY_QUERY_RETURN_TYPE void - -# define _NAN_INDEX_GETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args -# define _NAN_INDEX_GETTER_RETURN_TYPE void - -# define _NAN_INDEX_SETTER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args -# define _NAN_INDEX_SETTER_RETURN_TYPE void - -# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args -# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE void - -# define _NAN_INDEX_DELETER_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args -# define _NAN_INDEX_DELETER_RETURN_TYPE void - -# define _NAN_INDEX_QUERY_ARGS_TYPE \ - const v8::PropertyCallbackInfo& -# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args -# define _NAN_INDEX_QUERY_RETURN_TYPE void - -# define NanGetInternalFieldPointer(object, index) \ - object->GetAlignedPointerFromInternalField(index) -# define NanSetInternalFieldPointer(object, index, value) \ - object->SetAlignedPointerInInternalField(index, value) - -# define NAN_WEAK_CALLBACK(type, name) \ - void name( \ - v8::Isolate* isolate \ - , v8::Persistent* object \ - , type data) -# define NAN_WEAK_CALLBACK_OBJECT (*object) -# define NAN_WEAK_CALLBACK_DATA(type) ((type) data) - -# define NanScope() v8::HandleScope scope(nan_isolate) -# define NanLocker() v8::Locker locker(nan_isolate) -# define NanUnlocker() v8::Unlocker unlocker(nan_isolate) -# define NanReturnValue(value) return args.GetReturnValue().Set(value) -# define NanReturnUndefined() return -# define NanReturnNull() return args.GetReturnValue().SetNull() -# define NanReturnEmptyString() return args.GetReturnValue().SetEmptyString() -# define NanAssignPersistent(type, handle, obj) handle.Reset(nan_isolate, obj) -# define NanInitPersistent(type, name, obj) \ - v8::Persistent name(nan_isolate, obj) -# define NanObjectWrapHandle(obj) obj->handle() - -//TODO: remove <0.11.8 support when 0.12 is released -#if NODE_VERSION_AT_LEAST(0, 11, 8) -# define NanMakeWeak(handle, parameter, callback) \ - handle.MakeWeak(parameter, callback) -#else -# define NanMakeWeak(handle, parameter, callback) \ - handle.MakeWeak(nan_isolate, parameter, callback) -#endif - -# define _NAN_ERROR(fun, errmsg) fun(v8::String::New(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - v8::ThrowException(_NAN_ERROR(fun, errmsg)); \ - } while (0); - - template static NAN_INLINE(v8::Local NanNewLocal( - v8::Handle val - )) { -//TODO: remove <0.11.9 support when 0.12 is released -#if NODE_VERSION_AT_LEAST(0, 11, 9) - return v8::Local::New(nan_isolate, val); -#else - return v8::Local::New(val); -#endif - } - - static NAN_INLINE(v8::Handle NanError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - static NAN_INLINE(void NanThrowError(const char* errmsg)) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - static NAN_INLINE(void NanThrowError(v8::Handle error)) { - NanScope(); - v8::ThrowException(error); - } - - static NAN_INLINE(v8::Handle NanError( - const char *msg - , const int errorNumber - )) { - v8::Local err = v8::Exception::Error(v8::String::New(msg)); - v8::Local obj = err.As(); - obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); - return err; - } - - static NAN_INLINE(void NanThrowError( - const char *msg - , const int errorNumber - )) { - NanThrowError(NanError(msg, errorNumber)); - } - - static NAN_INLINE(v8::Handle NanTypeError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - static NAN_INLINE(void NanThrowTypeError(const char* errmsg)) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - static NAN_INLINE(v8::Handle NanRangeError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - static NAN_INLINE(void NanThrowRangeError(const char* errmsg)) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template static NAN_INLINE(void NanDisposePersistent( - v8::Persistent &handle - )) { - -//TODO: remove <0.11.8 support when 0.12 is released -# if NODE_VERSION_AT_LEAST(0, 11, 8) - handle.Reset(); -# else - handle.Dispose(nan_isolate); -# endif - handle.Clear(); - } - - template static NAN_DEPRECATED(void NanDispose( - v8::Persistent &handle - )) { - NanDisposePersistent(handle); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::smalloc::FreeCallback callback - , void *hint - )) { - return node::Buffer::New(data, length, callback, hint); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle ( - char *data - , uint32_t size - )) { - return node::Buffer::New(data, size); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle (uint32_t size)) { - return node::Buffer::New(size); - } - - static NAN_INLINE(v8::Local NanBufferUse( - char* data - , uint32_t size - )) { - return node::Buffer::Use(data, size); - } - - template - static NAN_INLINE(v8::Local NanPersistentToLocal( - const v8::Persistent& persistent - )) { - return v8::Local::New(nan_isolate, persistent); - } - - static NAN_INLINE(bool NanHasInstance( - v8::Persistent& function_template - , v8::Handle value - )) { - return NanPersistentToLocal(function_template)->HasInstance(value); - } - - static NAN_INLINE(v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - )) { - return v8::Local::New( - nan_isolate - , v8::Context::New(nan_isolate, extensions, tmpl, obj) - ); - } - -#else -// Node 0.8 and 0.10 - -# define _NAN_METHOD_ARGS_TYPE const v8::Arguments& -# define _NAN_METHOD_ARGS _NAN_METHOD_ARGS_TYPE args -# define _NAN_METHOD_RETURN_TYPE v8::Handle - -# define _NAN_GETTER_ARGS_TYPE const v8::AccessorInfo & -# define _NAN_GETTER_ARGS _NAN_GETTER_ARGS_TYPE args -# define _NAN_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_SETTER_ARGS_TYPE const v8::AccessorInfo & -# define _NAN_SETTER_ARGS _NAN_SETTER_ARGS_TYPE args -# define _NAN_SETTER_RETURN_TYPE void - -# define _NAN_PROPERTY_GETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_GETTER_ARGS _NAN_PROPERTY_GETTER_ARGS_TYPE args -# define _NAN_PROPERTY_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_SETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_SETTER_ARGS _NAN_PROPERTY_SETTER_ARGS_TYPE args -# define _NAN_PROPERTY_SETTER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_ENUMERATOR_ARGS _NAN_PROPERTY_ENUMERATOR_ARGS_TYPE args -# define _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_DELETER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_DELETER_ARGS _NAN_PROPERTY_DELETER_ARGS_TYPE args -# define _NAN_PROPERTY_DELETER_RETURN_TYPE v8::Handle - -# define _NAN_PROPERTY_QUERY_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_PROPERTY_QUERY_ARGS _NAN_PROPERTY_QUERY_ARGS_TYPE args -# define _NAN_PROPERTY_QUERY_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_GETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_GETTER_ARGS _NAN_INDEX_GETTER_ARGS_TYPE args -# define _NAN_INDEX_GETTER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_SETTER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_SETTER_ARGS _NAN_INDEX_SETTER_ARGS_TYPE args -# define _NAN_INDEX_SETTER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_ENUMERATOR_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_ENUMERATOR_ARGS _NAN_INDEX_ENUMERATOR_ARGS_TYPE args -# define _NAN_INDEX_ENUMERATOR_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_DELETER_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_DELETER_ARGS _NAN_INDEX_DELETER_ARGS_TYPE args -# define _NAN_INDEX_DELETER_RETURN_TYPE v8::Handle - -# define _NAN_INDEX_QUERY_ARGS_TYPE const v8::AccessorInfo& -# define _NAN_INDEX_QUERY_ARGS _NAN_INDEX_QUERY_ARGS_TYPE args -# define _NAN_INDEX_QUERY_RETURN_TYPE v8::Handle - -# define NanGetInternalFieldPointer(object, index) \ - object->GetPointerFromInternalField(index) -# define NanSetInternalFieldPointer(object, index, value) \ - object->SetPointerInInternalField(index, value) -# define NAN_WEAK_CALLBACK(type, name) \ - void name( \ - v8::Persistent object \ - , void *data) -# define NAN_WEAK_CALLBACK_OBJECT object -# define NAN_WEAK_CALLBACK_DATA(type) ((type) data) - -# define NanScope() v8::HandleScope scope -# define NanLocker() v8::Locker locker -# define NanUnlocker() v8::Unlocker unlocker -# define NanReturnValue(value) return scope.Close(value) -# define NanReturnUndefined() return v8::Undefined() -# define NanReturnNull() return v8::Null() -# define NanReturnEmptyString() return v8::String::Empty() -# define NanInitPersistent(type, name, obj) \ - v8::Persistent name = v8::Persistent::New(obj) -# define NanAssignPersistent(type, handle, obj) \ - handle = v8::Persistent::New(obj) -# define NanObjectWrapHandle(obj) obj->handle_ -# define NanMakeWeak(handle, parameters, callback) \ - handle.MakeWeak(parameters, callback) - -# define _NAN_ERROR(fun, errmsg) \ - fun(v8::String::New(errmsg)) - -# define _NAN_THROW_ERROR(fun, errmsg) \ - do { \ - NanScope(); \ - return v8::ThrowException(_NAN_ERROR(fun, errmsg)); \ - } while (0); - - template static NAN_INLINE(v8::Local NanNewLocal( - v8::Handle val - )) { - return v8::Local::New(val); - } - - static NAN_INLINE(v8::Handle NanError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::Error, errmsg); - } - - static NAN_INLINE(v8::Handle NanThrowError(const char* errmsg)) { - _NAN_THROW_ERROR(v8::Exception::Error, errmsg); - } - - static NAN_INLINE(v8::Handle NanThrowError( - v8::Handle error - )) { - NanScope(); - return v8::ThrowException(error); - } - - static NAN_INLINE(v8::Handle NanError( - const char *msg - , const int errorNumber - )) { - v8::Local err = v8::Exception::Error(v8::String::New(msg)); - v8::Local obj = err.As(); - obj->Set(v8::String::New("code"), v8::Int32::New(errorNumber)); - return err; - } - - static NAN_INLINE(v8::Handle NanThrowError( - const char *msg - , const int errorNumber - )) { - return NanThrowError(NanError(msg, errorNumber)); - } - - static NAN_INLINE(v8::Handle NanTypeError(const char* errmsg)) { - return _NAN_ERROR(v8::Exception::TypeError, errmsg); - } - - static NAN_INLINE(v8::Handle NanThrowTypeError( - const char* errmsg - )) { - _NAN_THROW_ERROR(v8::Exception::TypeError, errmsg); - } - - static NAN_INLINE(v8::Handle NanRangeError( - const char* errmsg - )) { - return _NAN_ERROR(v8::Exception::RangeError, errmsg); - } - - static NAN_INLINE(v8::Handle NanThrowRangeError( - const char* errmsg - )) { - _NAN_THROW_ERROR(v8::Exception::RangeError, errmsg); - } - - template static NAN_INLINE(void NanDisposePersistent( - v8::Persistent &handle - )) { - handle.Dispose(); - handle.Clear(); - } - - template static NAN_DEPRECATED(void NanDispose( - v8::Persistent &handle - )) { - NanDisposePersistent(handle); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle ( - char *data - , size_t length - , node::Buffer::free_callback callback - , void *hint - )) { - return NanNewLocal( - node::Buffer::New(data, length, callback, hint)->handle_); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle ( - char *data - , uint32_t size - )) { - return NanNewLocal(node::Buffer::New(data, size)->handle_); - } - - static NAN_INLINE(v8::Local NanNewBufferHandle (uint32_t size)) { - return NanNewLocal(node::Buffer::New(size)->handle_); - } - - static NAN_INLINE(void FreeData(char *data, void *hint)) { - delete[] data; - } - - static NAN_INLINE(v8::Local NanBufferUse( - char* data - , uint32_t size - )) { - return NanNewLocal( - node::Buffer::New(data, size, FreeData, NULL)->handle_); - } - - template - static NAN_INLINE(v8::Local NanPersistentToLocal( - const v8::Persistent& persistent - )) { - return NanNewLocal(persistent); - } - - static NAN_INLINE(bool NanHasInstance( - v8::Persistent& function_template - , v8::Handle value - )) { - return function_template->HasInstance(value); - } - - static NAN_INLINE(v8::Local NanNewContextHandle( - v8::ExtensionConfiguration* extensions = NULL - , v8::Handle tmpl = v8::Handle() - , v8::Handle obj = v8::Handle() - )) { - v8::Persistent ctx = v8::Context::New(extensions, tmpl, obj); - v8::Local lctx = NanNewLocal(ctx); - ctx.Dispose(); - return lctx; - } - -#endif // node version - -#define NAN_METHOD(name) _NAN_METHOD_RETURN_TYPE name(_NAN_METHOD_ARGS) -#define NAN_GETTER(name) \ - _NAN_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_GETTER_ARGS) -#define NAN_SETTER(name) \ - _NAN_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_SETTER_ARGS) -#define NAN_PROPERTY_GETTER(name) \ - _NAN_PROPERTY_GETTER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_GETTER_ARGS) -#define NAN_PROPERTY_SETTER(name) \ - _NAN_PROPERTY_SETTER_RETURN_TYPE name( \ - v8::Local property \ - , v8::Local value \ - , _NAN_PROPERTY_SETTER_ARGS) -#define NAN_PROPERTY_ENUMERATOR(name) \ - _NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name(_NAN_PROPERTY_ENUMERATOR_ARGS) -#define NAN_PROPERTY_DELETER(name) \ - _NAN_PROPERTY_DELETER_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_DELETER_ARGS) -#define NAN_PROPERTY_QUERY(name) \ - _NAN_PROPERTY_QUERY_RETURN_TYPE name( \ - v8::Local property \ - , _NAN_PROPERTY_QUERY_ARGS) -# define NAN_INDEX_GETTER(name) \ - _NAN_INDEX_GETTER_RETURN_TYPE name(uint32_t index, _NAN_INDEX_GETTER_ARGS) -#define NAN_INDEX_SETTER(name) \ - _NAN_INDEX_SETTER_RETURN_TYPE name( \ - uint32_t index \ - , v8::Local value \ - , _NAN_INDEX_SETTER_ARGS) -#define NAN_INDEX_ENUMERATOR(name) \ - _NAN_INDEX_ENUMERATOR_RETURN_TYPE name(_NAN_INDEX_ENUMERATOR_ARGS) -#define NAN_INDEX_DELETER(name) \ - _NAN_INDEX_DELETER_RETURN_TYPE name( \ - uint32_t index \ - , _NAN_INDEX_DELETER_ARGS) -#define NAN_INDEX_QUERY(name) \ - _NAN_INDEX_QUERY_RETURN_TYPE name(uint32_t index, _NAN_INDEX_QUERY_ARGS) - -class NanCallback { - public: - NanCallback() { - NanScope(); - v8::Local obj = v8::Object::New(); - NanAssignPersistent(v8::Object, handle, obj); - } - - NanCallback(const v8::Handle &fn) { - NanScope(); - v8::Local obj = v8::Object::New(); - NanAssignPersistent(v8::Object, handle, obj); - SetFunction(fn); - } - - ~NanCallback() { - if (handle.IsEmpty()) return; - handle.Dispose(); - handle.Clear(); - } - - NAN_INLINE(void SetFunction(const v8::Handle &fn)) { - NanScope(); - NanPersistentToLocal(handle)->Set(NanSymbol("callback"), fn); - } - - NAN_INLINE(v8::Local GetFunction ()) { - return NanPersistentToLocal(handle)->Get(NanSymbol("callback")) - .As(); - } - - void Call(int argc, v8::Handle argv[]) { - NanScope(); - -#if NODE_VERSION_AT_LEAST(0, 8, 0) - v8::Local callback = NanPersistentToLocal(handle)-> - Get(NanSymbol("callback")).As(); - node::MakeCallback( - v8::Context::GetCurrent()->Global() - , callback - , argc - , argv - ); -#else - node::MakeCallback(handle, "callback", argc, argv); -#endif - } - - private: - v8::Persistent handle; -}; - -/* abstract */ class NanAsyncWorker { -public: - NanAsyncWorker (NanCallback *callback) : callback(callback) { - request.data = this; - errmsg = NULL; - } - - virtual ~NanAsyncWorker () { - NanScope(); - - if (!persistentHandle.IsEmpty()) - NanDisposePersistent(persistentHandle); - if (callback) - delete callback; - if (errmsg) - delete errmsg; - } - - virtual void WorkComplete () { - NanScope(); - - if (errmsg == NULL) - HandleOKCallback(); - else - HandleErrorCallback(); - delete callback; - callback = NULL; - } - - void SavePersistent(const char *key, v8::Local &obj) { - NanScope(); - - v8::Local handle = NanPersistentToLocal(persistentHandle); - handle->Set(NanSymbol(key), obj); - } - - v8::Local GetFromPersistent(const char *key) { - NanScope(); - - v8::Local handle = NanPersistentToLocal(persistentHandle); - return handle->Get(NanSymbol(key)).As(); - } - - virtual void Execute () =0; - - uv_work_t request; - -protected: - v8::Persistent persistentHandle; - NanCallback *callback; - const char *errmsg; - - virtual void HandleOKCallback () { - NanScope(); - - callback->Call(0, NULL); - }; - - virtual void HandleErrorCallback () { - NanScope(); - - v8::Local argv[] = { - v8::Exception::Error(v8::String::New(errmsg)) - }; - callback->Call(1, argv); - } -}; - -NAN_INLINE(void NanAsyncExecute (uv_work_t* req)) { - NanAsyncWorker *worker = static_cast(req->data); - worker->Execute(); -} - -NAN_INLINE(void NanAsyncExecuteComplete (uv_work_t* req)) { - NanAsyncWorker* worker = static_cast(req->data); - worker->WorkComplete(); - delete worker; -} - -NAN_INLINE(void NanAsyncQueueWorker (NanAsyncWorker* worker)) { - uv_queue_work( - uv_default_loop() - , &worker->request - , NanAsyncExecute - , (uv_after_work_cb)NanAsyncExecuteComplete - ); -} - -//// Base 64 //// - -#define _nan_base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) - -// Doesn't check for padding at the end. Can be 1-2 bytes over. -static NAN_INLINE(size_t _nan_base64_decoded_size_fast(size_t size)) { - size_t remainder = size % 4; - - size = (size / 4) * 3; - if (remainder) { - if (size == 0 && remainder == 1) { - // special case: 1-byte input cannot be decoded - size = 0; - } else { - // non-padded input, add 1 or 2 extra bytes - size += 1 + (remainder == 3); - } - } - - return size; -} - -template -static NAN_INLINE(size_t _nan_base64_decoded_size( - const TypeName* src - , size_t size -)) { - if (size == 0) - return 0; - - if (src[size - 1] == '=') - size--; - if (size > 0 && src[size - 1] == '=') - size--; - - return _nan_base64_decoded_size_fast(size); -} - -// supports regular and URL-safe base64 -static const int _nan_unbase64_table[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63 - , 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1 - , -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 - , 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63 - , -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 - , 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 - , -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 -}; - -#define _nan_unbase64(x) _nan_unbase64_table[(uint8_t)(x)] - -template static size_t _nan_base64_decode( - char* buf - , size_t len - , const TypeName* src - , const size_t srcLen -) { - char* dst = buf; - char* dstEnd = buf + len; - const TypeName* srcEnd = src + srcLen; - - while (src < srcEnd && dst < dstEnd) { - int remaining = srcEnd - src; - char a, b, c, d; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining == 0 || *src == '=') break; - a = _nan_unbase64(*src++); - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 1 || *src == '=') break; - b = _nan_unbase64(*src++); - - *dst++ = (a << 2) | ((b & 0x30) >> 4); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 2 || *src == '=') break; - c = _nan_unbase64(*src++); - - *dst++ = ((b & 0x0F) << 4) | ((c & 0x3C) >> 2); - if (dst == dstEnd) break; - - while (_nan_unbase64(*src) < 0 && src < srcEnd) src++, remaining--; - if (remaining <= 3 || *src == '=') break; - d = _nan_unbase64(*src++); - - *dst++ = ((c & 0x03) << 6) | (d & 0x3F); - } - - return dst - buf; -} - -//// HEX //// - -template unsigned _nan_hex2bin(TypeName c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); - if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); - return static_cast(-1); -} - -template static size_t _nan_hex_decode( - char* buf - , size_t len - , const TypeName* src - , const size_t srcLen -) { - size_t i; - for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { - unsigned a = _nan_hex2bin(src[i * 2 + 0]); - unsigned b = _nan_hex2bin(src[i * 2 + 1]); - if (!~a || !~b) return i; - buf[i] = a * 16 + b; - } - - return i; -} - -static bool _NanGetExternalParts( - v8::Handle val - , const char** data - , size_t* len -) { - if (node::Buffer::HasInstance(val)) { - *data = node::Buffer::Data(val.As()); - *len = node::Buffer::Length(val.As()); - return true; - } - - assert(val->IsString()); - v8::Local str = NanNewLocal(val.As()); - - if (str->IsExternalAscii()) { - const v8::String::ExternalAsciiStringResource* ext; - ext = str->GetExternalAsciiStringResource(); - *data = ext->data(); - *len = ext->length(); - return true; - - } else if (str->IsExternal()) { - const v8::String::ExternalStringResource* ext; - ext = str->GetExternalStringResource(); - *data = reinterpret_cast(ext->data()); - *len = ext->length(); - return true; - } - - return false; -} - -namespace Nan { - enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; -} - -static NAN_INLINE(void* NanRawString( - v8::Handle from - , enum Nan::Encoding encoding - , size_t *datalen - , void *buf - , size_t buflen - , int flags -)) { - NanScope(); - - size_t sz_; - size_t term_len = !(flags & v8::String::NO_NULL_TERMINATION); - char *data = NULL; - size_t len; - bool is_extern = _NanGetExternalParts( - from - , const_cast(&data) - , &len); - - if (is_extern && !term_len) { - NanSetPointerSafe(datalen, len); - return data; - } - - v8::Local toStr = from->ToString(); - - char *to = (char*)buf; - - switch(encoding) { - case Nan::ASCII: -#if NODE_MODULE_VERSION < 0x0C - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteAscii(to, 0, sz_ + term_len, flags)); - return to; -#endif - case Nan::BINARY: - case Nan::BUFFER: - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } -#if NODE_MODULE_VERSION < 0x0C - // TODO(isaacs): THIS IS AWFUL!!! - // AGREE(kkoopa) - { - uint16_t* twobytebuf = new uint16_t[sz_ + term_len]; - - size_t len = toStr->Write(twobytebuf, 0, sz_ + term_len, flags); - - for (size_t i = 0; i < sz_ + term_len && i < len + term_len; i++) { - unsigned char *b = reinterpret_cast(&twobytebuf[i]); - to[i] = *b; - } - - NanSetPointerSafe(datalen, len); - - delete[] twobytebuf; - return to; - } -#else - NanSetPointerSafe( - datalen, - toStr->WriteOneByte( - reinterpret_cast(to) - , 0 - , sz_ + term_len - , flags)); - return to; -#endif - case Nan::UTF8: - sz_ = toStr->Utf8Length(); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , toStr->WriteUtf8(to, sz_ + term_len, NULL, flags) - term_len); - return to; - case Nan::BASE64: - { - v8::String::Value value(toStr); - sz_ = _nan_base64_decoded_size(*value, value.length()); - if (to == NULL) { - to = new char[sz_ + term_len]; - } else { - assert(buflen >= sz_ + term_len); - } - NanSetPointerSafe( - datalen - , _nan_base64_decode(to, sz_, *value, value.length())); - if (term_len) { - to[sz_] = '\0'; - } - return to; - } - case Nan::UCS2: - { - sz_ = toStr->Length(); - if (to == NULL) { - to = new char[(sz_ + term_len) * 2]; - } else { - assert(buflen >= (sz_ + term_len) * 2 && "too small buffer"); - } - - int bc = 2 * toStr->Write( - reinterpret_cast(to) - , 0 - , sz_ + term_len - , flags); - NanSetPointerSafe(datalen, bc); - return to; - } - case Nan::HEX: - { - v8::String::Value value(toStr); - sz_ = value.length(); - assert(!(sz_ & 1) && "bad hex data"); - if (to == NULL) { - to = new char[sz_ / 2 + term_len]; - } else { - assert(buflen >= sz_ / 2 + term_len && "too small buffer"); - } - NanSetPointerSafe( - datalen - , _nan_hex_decode(to, sz_ / 2, *value, value.length())); - } - if (term_len) { - to[sz_ / 2] = '\0'; - } - return to; - default: - assert(0 && "unknown encoding"); - } - return to; -} - -static NAN_INLINE(char* NanFromV8String( - v8::Handle from - , enum Nan::Encoding encoding = Nan::UTF8 - , size_t *datalen = NULL - , char *buf = NULL - , size_t buflen = 0 - , int flags = - v8::String::NO_NULL_TERMINATION | v8::String::HINT_MANY_WRITES_EXPECTED -)) { - return (char *) NanRawString(from, encoding, datalen, buf, buflen, flags); -} - -static NAN_INLINE(char* NanCString( - v8::Handle from - , size_t *datalen - , char *buf = NULL - , size_t buflen = 0 - , int flags = v8::String::NO_OPTIONS -)) { - return (char *) NanRawString(from, Nan::UTF8, datalen, buf, buflen, flags); -} - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node b/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node deleted file mode 100644 index 7f54835e7..000000000 Binary files a/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node b/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node deleted file mode 100644 index f01f8be35..000000000 Binary files a/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/bson/ext/wscript b/node_modules/mongodb/node_modules/bson/ext/wscript deleted file mode 100644 index 40f5317f1..000000000 --- a/node_modules/mongodb/node_modules/bson/ext/wscript +++ /dev/null @@ -1,39 +0,0 @@ -import Options -from os import unlink, symlink, popen -from os.path import exists - -srcdir = "." -blddir = "build" -VERSION = "0.1.0" - -def set_options(opt): - opt.tool_options("compiler_cxx") - opt.add_option( '--debug' - , action='store_true' - , default=False - , help='Build debug variant [Default: False]' - , dest='debug' - ) - -def configure(conf): - conf.check_tool("compiler_cxx") - conf.check_tool("node_addon") - conf.env.append_value('CXXFLAGS', ['-O3', '-funroll-loops']) - - # conf.env.append_value('CXXFLAGS', ['-DDEBUG', '-g', '-O0', '-Wall', '-Wextra']) - # conf.check(lib='node', libpath=['/usr/lib', '/usr/local/lib'], uselib_store='NODE') - -def build(bld): - obj = bld.new_task_gen("cxx", "shlib", "node_addon") - obj.target = "bson" - obj.source = ["bson.cc"] - # obj.uselib = "NODE" - -def shutdown(): - # HACK to get compress.node out of build directory. - # better way to do this? - if Options.commands['clean']: - if exists('bson.node'): unlink('bson.node') - else: - if exists('build/default/bson.node') and not exists('bson.node'): - symlink('build/default/bson.node', 'bson.node') diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/binary.js b/node_modules/mongodb/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 82d4d04c1..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,339 +0,0 @@ -/** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js b/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js deleted file mode 100644 index d2fc811f4..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/bson.js b/node_modules/mongodb/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 7df6896a7..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,1543 +0,0 @@ -var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/code.js b/node_modules/mongodb/node_modules/bson/lib/bson/code.js deleted file mode 100644 index 69b56a3ff..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js b/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index 56b651029..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/double.js b/node_modules/mongodb/node_modules/bson/lib/bson/double.js deleted file mode 100644 index ae5146378..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js b/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 6fca3924f..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/index.js b/node_modules/mongodb/node_modules/bson/lib/bson/index.js deleted file mode 100644 index 950fcad34..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/index.js +++ /dev/null @@ -1,74 +0,0 @@ -try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/long.js b/node_modules/mongodb/node_modules/bson/lib/bson/long.js deleted file mode 100644 index f8f37a6b8..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,854 +0,0 @@ -// 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js b/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index 0825408d0..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js b/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 230c2e64a..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js b/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 844763cf8..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,249 +0,0 @@ -/** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - if(!(this instanceof ObjectID)) return new ObjectID(id); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId aswell as ObjectID -var ObjectId = ObjectID; - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = '' - , number - , value; - - for (var index = 0, len = this.id.length; index < len; index++) { - value = BinaryParser.toByte(this.id[index]); - number = value <= 15 - ? '0' + value.toString(16) - : value.toString(16); - hexString = hexString + number; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' != typeof time) { - time = parseInt(Date.now()/1000,10); - } - - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js b/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index 8e2838d17..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js b/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index c650d1536..000000000 --- a/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,853 +0,0 @@ -// 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/bson/package.json b/node_modules/mongodb/node_modules/bson/package.json deleted file mode 100644 index 4038b4154..000000000 --- a/node_modules/mongodb/node_modules/bson/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "version": "0.2.5", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/mongodb/js-bson.git" - }, - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "devDependencies": { - "nodeunit": "0.8.2", - "gleak": "0.2.3", - "one": "2.X.X" - }, - "config": { - "native": false - }, - "main": "./lib/bson/index", - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" - }, - "browser": "lib/bson/bson.js", - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "readme": "Javascript + C++ BSON parser\n============================\n\nThis BSON parser is primarily meant for usage with the `mongodb` node.js driver. However thanks to such wonderful tools at `onejs` we are able to package up a BSON parser that will work in the browser aswell. The current build is located in the `browser_build/bson.js` file.\n\nA simple example on how to use it\n\n \n \n \n \n \n \n\n It's got two simple methods to use in your application.\n\n * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions)\n * @param {Object} object the Javascript object to serialize.\n * @param {Boolean} checkKeys the serializer will check if keys are valid.\n * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**.\n * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**\n * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports\n \n * BSON.deserialize(buffer, options, isArray)\n * Options\n * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.\n * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.\n * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.\n * @param {TypedArray/Array} a TypedArray/Array containing the BSON data\n * @param {Object} [options] additional options used for the deserialization.\n * @param {Boolean} [isArray] ignore used for recursive parsing.\n * @return {Object} returns the deserialized Javascript Object.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/mongodb/js-bson", - "_id": "bson@0.2.5", - "dist": { - "shasum": "1181da970e78992c777ee0006559dcc3b3178c4b" - }, - "_from": "bson@0.2.5", - "_resolved": "https://registry.npmjs.org/bson/-/bson-0.2.5.tgz" -} diff --git a/node_modules/mongodb/node_modules/bson/tools/gleak.js b/node_modules/mongodb/node_modules/bson/tools/gleak.js deleted file mode 100644 index c707cfcb5..000000000 --- a/node_modules/mongodb/node_modules/bson/tools/gleak.js +++ /dev/null @@ -1,21 +0,0 @@ - -var gleak = require('gleak')(); -gleak.ignore('AssertionError'); -gleak.ignore('testFullSpec_param_found'); -gleak.ignore('events'); -gleak.ignore('Uint8Array'); -gleak.ignore('Uint8ClampedArray'); -gleak.ignore('TAP_Global_Harness'); -gleak.ignore('setImmediate'); -gleak.ignore('clearImmediate'); - -gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); -gleak.ignore('DTRACE_NET_STREAM_END'); -gleak.ignore('DTRACE_NET_SOCKET_READ'); -gleak.ignore('DTRACE_NET_SOCKET_WRITE'); -gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); -gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); -gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); -gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); - -module.exports = gleak; diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE deleted file mode 100644 index 7c435baae..000000000 --- a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2011 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js deleted file mode 100644 index 73834010f..000000000 --- a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js +++ /dev/null @@ -1,190 +0,0 @@ -jasmine.TrivialReporter = function(doc) { - this.document = doc || document; - this.suiteDivs = {}; - this.logRunningSpecs = false; -}; - -jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { el.appendChild(child); } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { - var showPassed, showSkipped; - - this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' }, - this.createDom('div', { className: 'banner' }, - this.createDom('div', { className: 'logo' }, - this.createDom('span', { className: 'title' }, "Jasmine"), - this.createDom('span', { className: 'version' }, runner.env.versionString())), - this.createDom('div', { className: 'options' }, - "Show ", - showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), - showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") - ) - ), - - this.runnerDiv = this.createDom('div', { className: 'runner running' }, - this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), - this.runnerMessageSpan = this.createDom('span', {}, "Running..."), - this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) - ); - - this.document.body.appendChild(this.outerDiv); - - var suites = runner.suites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - var suiteDiv = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); - this.suiteDivs[suite.id] = suiteDiv; - var parentDiv = this.outerDiv; - if (suite.parentSuite) { - parentDiv = this.suiteDivs[suite.parentSuite.id]; - } - parentDiv.appendChild(suiteDiv); - } - - this.startedAt = new Date(); - - var self = this; - showPassed.onclick = function(evt) { - if (showPassed.checked) { - self.outerDiv.className += ' show-passed'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); - } - }; - - showSkipped.onclick = function(evt) { - if (showSkipped.checked) { - self.outerDiv.className += ' show-skipped'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); - } - }; -}; - -jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { - var results = runner.results(); - var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; - this.runnerDiv.setAttribute("class", className); - //do it twice for IE - this.runnerDiv.setAttribute("className", className); - var specs = runner.specs(); - var specCount = 0; - for (var i = 0; i < specs.length; i++) { - if (this.specFilter(specs[i])) { - specCount++; - } - } - var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); - message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; - this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); - - this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); -}; - -jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { - var results = suite.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.totalCount === 0) { // todo: change this to check results.skipped - status = 'skipped'; - } - this.suiteDivs[suite.id].className += " " + status; -}; - -jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { - if (this.logRunningSpecs) { - this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } -}; - -jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { - var results = spec.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - var specDiv = this.createDom('div', { className: 'spec ' + status }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(spec.getFullName()), - title: spec.getFullName() - }, spec.description)); - - - var resultItems = results.getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - specDiv.appendChild(messagesDiv); - } - - this.suiteDivs[spec.suite.id].appendChild(specDiv); -}; - -jasmine.TrivialReporter.prototype.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } -}; - -jasmine.TrivialReporter.prototype.getLocation = function() { - return this.document.location; -}; - -jasmine.TrivialReporter.prototype.specFilter = function(spec) { - var paramMap = {}; - var params = this.getLocation().search.substring(1).split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - if (!paramMap.spec) { - return true; - } - return spec.getFullName().indexOf(paramMap.spec) === 0; -}; diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css deleted file mode 100644 index 6583fe7c6..000000000 --- a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css +++ /dev/null @@ -1,166 +0,0 @@ -body { - font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; -} - - -.jasmine_reporter a:visited, .jasmine_reporter a { - color: #303; -} - -.jasmine_reporter a:hover, .jasmine_reporter a:active { - color: blue; -} - -.run_spec { - float:right; - padding-right: 5px; - font-size: .8em; - text-decoration: none; -} - -.jasmine_reporter { - margin: 0 5px; -} - -.banner { - color: #303; - background-color: #fef; - padding: 5px; -} - -.logo { - float: left; - font-size: 1.1em; - padding-left: 5px; -} - -.logo .version { - font-size: .6em; - padding-left: 1em; -} - -.runner.running { - background-color: yellow; -} - - -.options { - text-align: right; - font-size: .8em; -} - - - - -.suite { - border: 1px outset gray; - margin: 5px 0; - padding-left: 1em; -} - -.suite .suite { - margin: 5px; -} - -.suite.passed { - background-color: #dfd; -} - -.suite.failed { - background-color: #fdd; -} - -.spec { - margin: 5px; - padding-left: 1em; - clear: both; -} - -.spec.failed, .spec.passed, .spec.skipped { - padding-bottom: 5px; - border: 1px solid gray; -} - -.spec.failed { - background-color: #fbb; - border-color: red; -} - -.spec.passed { - background-color: #bfb; - border-color: green; -} - -.spec.skipped { - background-color: #bbb; -} - -.messages { - border-left: 1px dashed gray; - padding-left: 1em; - padding-right: 1em; -} - -.passed { - background-color: #cfc; - display: none; -} - -.failed { - background-color: #fbb; -} - -.skipped { - color: #777; - background-color: #eee; - display: none; -} - - -/*.resultMessage {*/ - /*white-space: pre;*/ -/*}*/ - -.resultMessage span.result { - display: block; - line-height: 2em; - color: black; -} - -.resultMessage .mismatch { - color: black; -} - -.stackTrace { - white-space: pre; - font-size: .8em; - margin-left: 10px; - max-height: 5em; - overflow: auto; - border: 1px inset red; - padding: 1em; - background: #eef; -} - -.finished-at { - padding-left: 1em; - font-size: .6em; -} - -.show-passed .passed, -.show-skipped .skipped { - display: block; -} - - -#jasmine_content { - position:fixed; - right: 100%; -} - -.runner { - border: 1px solid gray; - display: block; - margin: 5px 0; - padding: 2px 0 2px 10px; -} diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js deleted file mode 100644 index c3d2dc7d2..000000000 --- a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js +++ /dev/null @@ -1,2476 +0,0 @@ -var isCommonJS = typeof window == "undefined"; - -/** - * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. - * - * @namespace - */ -var jasmine = {}; -if (isCommonJS) exports.jasmine = jasmine; -/** - * @private - */ -jasmine.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); -}; - -/** - * Use jasmine.undefined instead of undefined, since undefined is just - * a plain old variable and may be redefined by somebody else. - * - * @private - */ -jasmine.undefined = jasmine.___undefined___; - -/** - * Show diagnostic messages in the console if set to true - * - */ -jasmine.VERBOSE = false; - -/** - * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. - * - */ -jasmine.DEFAULT_UPDATE_INTERVAL = 250; - -/** - * Default timeout interval in milliseconds for waitsFor() blocks. - */ -jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; - -jasmine.getGlobal = function() { - function getGlobal() { - return this; - } - - return getGlobal(); -}; - -/** - * Allows for bound functions to be compared. Internal use only. - * - * @ignore - * @private - * @param base {Object} bound 'this' for the function - * @param name {Function} function to find - */ -jasmine.bindOriginal_ = function(base, name) { - var original = base[name]; - if (original.apply) { - return function() { - return original.apply(base, arguments); - }; - } else { - // IE support - return jasmine.getGlobal()[name]; - } -}; - -jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); -jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); -jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); -jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); - -jasmine.MessageResult = function(values) { - this.type = 'log'; - this.values = values; - this.trace = new Error(); // todo: test better -}; - -jasmine.MessageResult.prototype.toString = function() { - var text = ""; - for (var i = 0; i < this.values.length; i++) { - if (i > 0) text += " "; - if (jasmine.isString_(this.values[i])) { - text += this.values[i]; - } else { - text += jasmine.pp(this.values[i]); - } - } - return text; -}; - -jasmine.ExpectationResult = function(params) { - this.type = 'expect'; - this.matcherName = params.matcherName; - this.passed_ = params.passed; - this.expected = params.expected; - this.actual = params.actual; - this.message = this.passed_ ? 'Passed.' : params.message; - - var trace = (params.trace || new Error(this.message)); - this.trace = this.passed_ ? '' : trace; -}; - -jasmine.ExpectationResult.prototype.toString = function () { - return this.message; -}; - -jasmine.ExpectationResult.prototype.passed = function () { - return this.passed_; -}; - -/** - * Getter for the Jasmine environment. Ensures one gets created - */ -jasmine.getEnv = function() { - var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); - return env; -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isArray_ = function(value) { - return jasmine.isA_("Array", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isString_ = function(value) { - return jasmine.isA_("String", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isNumber_ = function(value) { - return jasmine.isA_("Number", value); -}; - -/** - * @ignore - * @private - * @param {String} typeName - * @param value - * @returns {Boolean} - */ -jasmine.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; -}; - -/** - * Pretty printer for expecations. Takes any object and turns it into a human-readable string. - * - * @param value {Object} an object to be outputted - * @returns {String} - */ -jasmine.pp = function(value) { - var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; -}; - -/** - * Returns true if the object is a DOM Node. - * - * @param {Object} obj object to check - * @returns {Boolean} - */ -jasmine.isDomNode = function(obj) { - return obj.nodeType > 0; -}; - -/** - * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. - * - * @example - * // don't care about which function is passed in, as long as it's a function - * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); - * - * @param {Class} clazz - * @returns matchable object of the type clazz - */ -jasmine.any = function(clazz) { - return new jasmine.Matchers.Any(clazz); -}; - -/** - * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. - * - * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine - * expectation syntax. Spies can be checked if they were called or not and what the calling params were. - * - * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). - * - * Spies are torn down at the end of every spec. - * - * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. - * - * @example - * // a stub - * var myStub = jasmine.createSpy('myStub'); // can be used anywhere - * - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // actual foo.not will not be called, execution stops - * spyOn(foo, 'not'); - - // foo.not spied upon, execution will continue to implementation - * spyOn(foo, 'not').andCallThrough(); - * - * // fake example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // foo.not(val) will return val - * spyOn(foo, 'not').andCallFake(function(value) {return value;}); - * - * // mock example - * foo.not(7 == 7); - * expect(foo.not).toHaveBeenCalled(); - * expect(foo.not).toHaveBeenCalledWith(true); - * - * @constructor - * @see spyOn, jasmine.createSpy, jasmine.createSpyObj - * @param {String} name - */ -jasmine.Spy = function(name) { - /** - * The name of the spy, if provided. - */ - this.identity = name || 'unknown'; - /** - * Is this Object a spy? - */ - this.isSpy = true; - /** - * The actual function this spy stubs. - */ - this.plan = function() { - }; - /** - * Tracking of the most recent call to the spy. - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy.mostRecentCall.args = [1, 2]; - */ - this.mostRecentCall = {}; - - /** - * Holds arguments for each call to the spy, indexed by call count - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy(7, 8); - * mySpy.mostRecentCall.args = [7, 8]; - * mySpy.argsForCall[0] = [1, 2]; - * mySpy.argsForCall[1] = [7, 8]; - */ - this.argsForCall = []; - this.calls = []; -}; - -/** - * Tells a spy to call through to the actual implemenatation. - * - * @example - * var foo = { - * bar: function() { // do some stuff } - * } - * - * // defining a spy on an existing property: foo.bar - * spyOn(foo, 'bar').andCallThrough(); - */ -jasmine.Spy.prototype.andCallThrough = function() { - this.plan = this.originalValue; - return this; -}; - -/** - * For setting the return value of a spy. - * - * @example - * // defining a spy from scratch: foo() returns 'baz' - * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); - * - * // defining a spy on an existing property: foo.bar() returns 'baz' - * spyOn(foo, 'bar').andReturn('baz'); - * - * @param {Object} value - */ -jasmine.Spy.prototype.andReturn = function(value) { - this.plan = function() { - return value; - }; - return this; -}; - -/** - * For throwing an exception when a spy is called. - * - * @example - * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' - * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); - * - * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' - * spyOn(foo, 'bar').andThrow('baz'); - * - * @param {String} exceptionMsg - */ -jasmine.Spy.prototype.andThrow = function(exceptionMsg) { - this.plan = function() { - throw exceptionMsg; - }; - return this; -}; - -/** - * Calls an alternate implementation when a spy is called. - * - * @example - * var baz = function() { - * // do some stuff, return something - * } - * // defining a spy from scratch: foo() calls the function baz - * var foo = jasmine.createSpy('spy on foo').andCall(baz); - * - * // defining a spy on an existing property: foo.bar() calls an anonymnous function - * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); - * - * @param {Function} fakeFunc - */ -jasmine.Spy.prototype.andCallFake = function(fakeFunc) { - this.plan = fakeFunc; - return this; -}; - -/** - * Resets all of a spy's the tracking variables so that it can be used again. - * - * @example - * spyOn(foo, 'bar'); - * - * foo.bar(); - * - * expect(foo.bar.callCount).toEqual(1); - * - * foo.bar.reset(); - * - * expect(foo.bar.callCount).toEqual(0); - */ -jasmine.Spy.prototype.reset = function() { - this.wasCalled = false; - this.callCount = 0; - this.argsForCall = []; - this.calls = []; - this.mostRecentCall = {}; -}; - -jasmine.createSpy = function(name) { - - var spyObj = function() { - spyObj.wasCalled = true; - spyObj.callCount++; - var args = jasmine.util.argsToArray(arguments); - spyObj.mostRecentCall.object = this; - spyObj.mostRecentCall.args = args; - spyObj.argsForCall.push(args); - spyObj.calls.push({object: this, args: args}); - return spyObj.plan.apply(this, arguments); - }; - - var spy = new jasmine.Spy(name); - - for (var prop in spy) { - spyObj[prop] = spy[prop]; - } - - spyObj.reset(); - - return spyObj; -}; - -/** - * Determines whether an object is a spy. - * - * @param {jasmine.Spy|Object} putativeSpy - * @returns {Boolean} - */ -jasmine.isSpy = function(putativeSpy) { - return putativeSpy && putativeSpy.isSpy; -}; - -/** - * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something - * large in one call. - * - * @param {String} baseName name of spy class - * @param {Array} methodNames array of names of methods to make spies - */ -jasmine.createSpyObj = function(baseName, methodNames) { - if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { - throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); - } - var obj = {}; - for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); - } - return obj; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the current spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.log = function() { - var spec = jasmine.getEnv().currentSpec; - spec.log.apply(spec, arguments); -}; - -/** - * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. - * - * @example - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops - * - * @see jasmine.createSpy - * @param obj - * @param methodName - * @returns a Jasmine spy that can be chained with all spy methods - */ -var spyOn = function(obj, methodName) { - return jasmine.getEnv().currentSpec.spyOn(obj, methodName); -}; -if (isCommonJS) exports.spyOn = spyOn; - -/** - * Creates a Jasmine spec that will be added to the current suite. - * - * // TODO: pending tests - * - * @example - * it('should be true', function() { - * expect(true).toEqual(true); - * }); - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var it = function(desc, func) { - return jasmine.getEnv().it(desc, func); -}; -if (isCommonJS) exports.it = it; - -/** - * Creates a disabled Jasmine spec. - * - * A convenience method that allows existing specs to be disabled temporarily during development. - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var xit = function(desc, func) { - return jasmine.getEnv().xit(desc, func); -}; -if (isCommonJS) exports.xit = xit; - -/** - * Starts a chain for a Jasmine expectation. - * - * It is passed an Object that is the actual value and should chain to one of the many - * jasmine.Matchers functions. - * - * @param {Object} actual Actual value to test against and expected value - */ -var expect = function(actual) { - return jasmine.getEnv().currentSpec.expect(actual); -}; -if (isCommonJS) exports.expect = expect; - -/** - * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. - * - * @param {Function} func Function that defines part of a jasmine spec. - */ -var runs = function(func) { - jasmine.getEnv().currentSpec.runs(func); -}; -if (isCommonJS) exports.runs = runs; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -var waits = function(timeout) { - jasmine.getEnv().currentSpec.waits(timeout); -}; -if (isCommonJS) exports.waits = waits; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); -}; -if (isCommonJS) exports.waitsFor = waitsFor; - -/** - * A function that is called before each spec in a suite. - * - * Used for spec setup, including validating assumptions. - * - * @param {Function} beforeEachFunction - */ -var beforeEach = function(beforeEachFunction) { - jasmine.getEnv().beforeEach(beforeEachFunction); -}; -if (isCommonJS) exports.beforeEach = beforeEach; - -/** - * A function that is called after each spec in a suite. - * - * Used for restoring any state that is hijacked during spec execution. - * - * @param {Function} afterEachFunction - */ -var afterEach = function(afterEachFunction) { - jasmine.getEnv().afterEach(afterEachFunction); -}; -if (isCommonJS) exports.afterEach = afterEach; - -/** - * Defines a suite of specifications. - * - * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared - * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization - * of setup in some tests. - * - * @example - * // TODO: a simple suite - * - * // TODO: a simple suite with a nested describe block - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var describe = function(description, specDefinitions) { - return jasmine.getEnv().describe(description, specDefinitions); -}; -if (isCommonJS) exports.describe = describe; - -/** - * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var xdescribe = function(description, specDefinitions) { - return jasmine.getEnv().xdescribe(description, specDefinitions); -}; -if (isCommonJS) exports.xdescribe = xdescribe; - - -// Provide the XMLHttpRequest class for IE 5.x-6.x: -jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { - function tryIt(f) { - try { - return f(); - } catch(e) { - } - return null; - } - - var xhr = tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.6.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.3.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP"); - }) || - tryIt(function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }); - - if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); - - return xhr; -} : XMLHttpRequest; -/** - * @namespace - */ -jasmine.util = {}; - -/** - * Declare that a child class inherit it's prototype from the parent class. - * - * @private - * @param {Function} childClass - * @param {Function} parentClass - */ -jasmine.util.inherit = function(childClass, parentClass) { - /** - * @private - */ - var subclass = function() { - }; - subclass.prototype = parentClass.prototype; - childClass.prototype = new subclass(); -}; - -jasmine.util.formatException = function(e) { - var lineNumber; - if (e.line) { - lineNumber = e.line; - } - else if (e.lineNumber) { - lineNumber = e.lineNumber; - } - - var file; - - if (e.sourceURL) { - file = e.sourceURL; - } - else if (e.fileName) { - file = e.fileName; - } - - var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); - - if (file && lineNumber) { - message += ' in ' + file + ' (line ' + lineNumber + ')'; - } - - return message; -}; - -jasmine.util.htmlEscape = function(str) { - if (!str) return str; - return str.replace(/&/g, '&') - .replace(//g, '>'); -}; - -jasmine.util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); - return arrayOfArgs; -}; - -jasmine.util.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; -}; - -/** - * Environment for Jasmine - * - * @constructor - */ -jasmine.Env = function() { - this.currentSpec = null; - this.currentSuite = null; - this.currentRunner_ = new jasmine.Runner(this); - - this.reporter = new jasmine.MultiReporter(); - - this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; - this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; - this.lastUpdate = 0; - this.specFilter = function() { - return true; - }; - - this.nextSpecId_ = 0; - this.nextSuiteId_ = 0; - this.equalityTesters_ = []; - - // wrap matchers - this.matchersClass = function() { - jasmine.Matchers.apply(this, arguments); - }; - jasmine.util.inherit(this.matchersClass, jasmine.Matchers); - - jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); -}; - - -jasmine.Env.prototype.setTimeout = jasmine.setTimeout; -jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; -jasmine.Env.prototype.setInterval = jasmine.setInterval; -jasmine.Env.prototype.clearInterval = jasmine.clearInterval; - -/** - * @returns an object containing jasmine version build info, if set. - */ -jasmine.Env.prototype.version = function () { - if (jasmine.version_) { - return jasmine.version_; - } else { - throw new Error('Version not set'); - } -}; - -/** - * @returns string containing jasmine version build info, if set. - */ -jasmine.Env.prototype.versionString = function() { - if (!jasmine.version_) { - return "version unknown"; - } - - var version = this.version(); - var versionString = version.major + "." + version.minor + "." + version.build; - if (version.release_candidate) { - versionString += ".rc" + version.release_candidate; - } - versionString += " revision " + version.revision; - return versionString; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSpecId = function () { - return this.nextSpecId_++; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSuiteId = function () { - return this.nextSuiteId_++; -}; - -/** - * Register a reporter to receive status updates from Jasmine. - * @param {jasmine.Reporter} reporter An object which will receive status updates. - */ -jasmine.Env.prototype.addReporter = function(reporter) { - this.reporter.addReporter(reporter); -}; - -jasmine.Env.prototype.execute = function() { - this.currentRunner_.execute(); -}; - -jasmine.Env.prototype.describe = function(description, specDefinitions) { - var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); - - var parentSuite = this.currentSuite; - if (parentSuite) { - parentSuite.add(suite); - } else { - this.currentRunner_.add(suite); - } - - this.currentSuite = suite; - - var declarationError = null; - try { - specDefinitions.call(suite); - } catch(e) { - declarationError = e; - } - - if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); - } - - this.currentSuite = parentSuite; - - return suite; -}; - -jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { - if (this.currentSuite) { - this.currentSuite.beforeEach(beforeEachFunction); - } else { - this.currentRunner_.beforeEach(beforeEachFunction); - } -}; - -jasmine.Env.prototype.currentRunner = function () { - return this.currentRunner_; -}; - -jasmine.Env.prototype.afterEach = function(afterEachFunction) { - if (this.currentSuite) { - this.currentSuite.afterEach(afterEachFunction); - } else { - this.currentRunner_.afterEach(afterEachFunction); - } - -}; - -jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { - return { - execute: function() { - } - }; -}; - -jasmine.Env.prototype.it = function(description, func) { - var spec = new jasmine.Spec(this, this.currentSuite, description); - this.currentSuite.add(spec); - this.currentSpec = spec; - - if (func) { - spec.runs(func); - } - - return spec; -}; - -jasmine.Env.prototype.xit = function(desc, func) { - return { - id: this.nextSpecId(), - runs: function() { - } - }; -}; - -jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { - return true; - } - - a.__Jasmine_been_here_before__ = b; - b.__Jasmine_been_here_before__ = a; - - var hasKey = function(obj, keyName) { - return obj !== null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in b) { - if (!hasKey(a, property) && hasKey(b, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - } - for (property in a) { - if (!hasKey(b, property) && hasKey(a, property)) { - mismatchKeys.push("expected missing key '" + property + "', but present in actual."); - } - } - for (property in b) { - if (property == '__Jasmine_been_here_before__') continue; - if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); - } - } - - if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { - mismatchValues.push("arrays were not the same length"); - } - - delete a.__Jasmine_been_here_before__; - delete b.__Jasmine_been_here_before__; - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - for (var i = 0; i < this.equalityTesters_.length; i++) { - var equalityTester = this.equalityTesters_[i]; - var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); - if (result !== jasmine.undefined) return result; - } - - if (a === b) return true; - - if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { - return (a == jasmine.undefined && b == jasmine.undefined); - } - - if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { - return a === b; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() == b.getTime(); - } - - if (a instanceof jasmine.Matchers.Any) { - return a.matches(b); - } - - if (b instanceof jasmine.Matchers.Any) { - return b.matches(a); - } - - if (jasmine.isString_(a) && jasmine.isString_(b)) { - return (a == b); - } - - if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { - return (a == b); - } - - if (typeof a === "object" && typeof b === "object") { - return this.compareObjects_(a, b, mismatchKeys, mismatchValues); - } - - //Straight check - return (a === b); -}; - -jasmine.Env.prototype.contains_ = function(haystack, needle) { - if (jasmine.isArray_(haystack)) { - for (var i = 0; i < haystack.length; i++) { - if (this.equals_(haystack[i], needle)) return true; - } - return false; - } - return haystack.indexOf(needle) >= 0; -}; - -jasmine.Env.prototype.addEqualityTester = function(equalityTester) { - this.equalityTesters_.push(equalityTester); -}; -/** No-op base class for Jasmine reporters. - * - * @constructor - */ -jasmine.Reporter = function() { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerResults = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecStarting = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecResults = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.log = function(str) { -}; - -/** - * Blocks are functions with executable code that make up a spec. - * - * @constructor - * @param {jasmine.Env} env - * @param {Function} func - * @param {jasmine.Spec} spec - */ -jasmine.Block = function(env, func, spec) { - this.env = env; - this.func = func; - this.spec = spec; -}; - -jasmine.Block.prototype.execute = function(onComplete) { - try { - this.func.apply(this.spec); - } catch (e) { - this.spec.fail(e); - } - onComplete(); -}; -/** JavaScript API reporter. - * - * @constructor - */ -jasmine.JsApiReporter = function() { - this.started = false; - this.finished = false; - this.suites_ = []; - this.results_ = {}; -}; - -jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { - this.started = true; - var suites = runner.topLevelSuites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - this.suites_.push(this.summarize_(suite)); - } -}; - -jasmine.JsApiReporter.prototype.suites = function() { - return this.suites_; -}; - -jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { - var isSuite = suiteOrSpec instanceof jasmine.Suite; - var summary = { - id: suiteOrSpec.id, - name: suiteOrSpec.description, - type: isSuite ? 'suite' : 'spec', - children: [] - }; - - if (isSuite) { - var children = suiteOrSpec.children(); - for (var i = 0; i < children.length; i++) { - summary.children.push(this.summarize_(children[i])); - } - } - return summary; -}; - -jasmine.JsApiReporter.prototype.results = function() { - return this.results_; -}; - -jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { - return this.results_[specId]; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { - this.finished = true; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { - this.results_[spec.id] = { - messages: spec.results().getItems(), - result: spec.results().failedCount > 0 ? "failed" : "passed" - }; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.log = function(str) { -}; - -jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ - var results = {}; - for (var i = 0; i < specIds.length; i++) { - var specId = specIds[i]; - results[specId] = this.summarizeResult_(this.results_[specId]); - } - return results; -}; - -jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ - var summaryMessages = []; - var messagesLength = result.messages.length; - for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { - var resultMessage = result.messages[messageIndex]; - summaryMessages.push({ - text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, - passed: resultMessage.passed ? resultMessage.passed() : true, - type: resultMessage.type, - message: resultMessage.message, - trace: { - stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined - } - }); - } - - return { - result : result.result, - messages : summaryMessages - }; -}; - -/** - * @constructor - * @param {jasmine.Env} env - * @param actual - * @param {jasmine.Spec} spec - */ -jasmine.Matchers = function(env, actual, spec, opt_isNot) { - this.env = env; - this.actual = actual; - this.spec = spec; - this.isNot = opt_isNot || false; - this.reportWasCalled_ = false; -}; - -// todo: @deprecated as of Jasmine 0.11, remove soon [xw] -jasmine.Matchers.pp = function(str) { - throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); -}; - -// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] -jasmine.Matchers.prototype.report = function(result, failing_message, details) { - throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); -}; - -jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { - for (var methodName in prototype) { - if (methodName == 'report') continue; - var orig = prototype[methodName]; - matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); - } -}; - -jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { - return function() { - var matcherArgs = jasmine.util.argsToArray(arguments); - var result = matcherFunction.apply(this, arguments); - - if (this.isNot) { - result = !result; - } - - if (this.reportWasCalled_) return result; - - var message; - if (!result) { - if (this.message) { - message = this.message.apply(this, arguments); - if (jasmine.isArray_(message)) { - message = message[this.isNot ? 1 : 0]; - } - } else { - var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; - if (matcherArgs.length > 0) { - for (var i = 0; i < matcherArgs.length; i++) { - if (i > 0) message += ","; - message += " " + jasmine.pp(matcherArgs[i]); - } - } - message += "."; - } - } - var expectationResult = new jasmine.ExpectationResult({ - matcherName: matcherName, - passed: result, - expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], - actual: this.actual, - message: message - }); - this.spec.addMatcherResult(expectationResult); - return jasmine.undefined; - }; -}; - - - - -/** - * toBe: compares the actual to the expected using === - * @param expected - */ -jasmine.Matchers.prototype.toBe = function(expected) { - return this.actual === expected; -}; - -/** - * toNotBe: compares the actual to the expected using !== - * @param expected - * @deprecated as of 1.0. Use not.toBe() instead. - */ -jasmine.Matchers.prototype.toNotBe = function(expected) { - return this.actual !== expected; -}; - -/** - * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. - * - * @param expected - */ -jasmine.Matchers.prototype.toEqual = function(expected) { - return this.env.equals_(this.actual, expected); -}; - -/** - * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual - * @param expected - * @deprecated as of 1.0. Use not.toNotEqual() instead. - */ -jasmine.Matchers.prototype.toNotEqual = function(expected) { - return !this.env.equals_(this.actual, expected); -}; - -/** - * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes - * a pattern or a String. - * - * @param expected - */ -jasmine.Matchers.prototype.toMatch = function(expected) { - return new RegExp(expected).test(this.actual); -}; - -/** - * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch - * @param expected - * @deprecated as of 1.0. Use not.toMatch() instead. - */ -jasmine.Matchers.prototype.toNotMatch = function(expected) { - return !(new RegExp(expected).test(this.actual)); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeDefined = function() { - return (this.actual !== jasmine.undefined); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeUndefined = function() { - return (this.actual === jasmine.undefined); -}; - -/** - * Matcher that compares the actual to null. - */ -jasmine.Matchers.prototype.toBeNull = function() { - return (this.actual === null); -}; - -/** - * Matcher that boolean not-nots the actual. - */ -jasmine.Matchers.prototype.toBeTruthy = function() { - return !!this.actual; -}; - - -/** - * Matcher that boolean nots the actual. - */ -jasmine.Matchers.prototype.toBeFalsy = function() { - return !this.actual; -}; - - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called. - */ -jasmine.Matchers.prototype.toHaveBeenCalled = function() { - if (arguments.length > 0) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to have been called.", - "Expected spy " + this.actual.identity + " not to have been called." - ]; - }; - - return this.actual.wasCalled; -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was not called. - * - * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead - */ -jasmine.Matchers.prototype.wasNotCalled = function() { - if (arguments.length > 0) { - throw new Error('wasNotCalled does not take arguments'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to not have been called.", - "Expected spy " + this.actual.identity + " to have been called." - ]; - }; - - return !this.actual.wasCalled; -}; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. - * - * @example - * - */ -jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - this.message = function() { - if (this.actual.callCount === 0) { - // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was." - ]; - } else { - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) - ]; - } - }; - - return this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; - -/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasNotCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", - "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" - ]; - }; - - return !this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** - * Matcher that checks that the expected item is an element in the actual Array. - * - * @param {Object} expected - */ -jasmine.Matchers.prototype.toContain = function(expected) { - return this.env.contains_(this.actual, expected); -}; - -/** - * Matcher that checks that the expected item is NOT an element in the actual Array. - * - * @param {Object} expected - * @deprecated as of 1.0. Use not.toNotContain() instead. - */ -jasmine.Matchers.prototype.toNotContain = function(expected) { - return !this.env.contains_(this.actual, expected); -}; - -jasmine.Matchers.prototype.toBeLessThan = function(expected) { - return this.actual < expected; -}; - -jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { - return this.actual > expected; -}; - -/** - * Matcher that checks that the expected item is equal to the actual item - * up to a given level of decimal precision (default 2). - * - * @param {Number} expected - * @param {Number} precision - */ -jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { - if (!(precision === 0)) { - precision = precision || 2; - } - var multiplier = Math.pow(10, precision); - var actual = Math.round(this.actual * multiplier); - expected = Math.round(expected * multiplier); - return expected == actual; -}; - -/** - * Matcher that checks that the expected exception was thrown by the actual. - * - * @param {String} expected - */ -jasmine.Matchers.prototype.toThrow = function(expected) { - var result = false; - var exception; - if (typeof this.actual != 'function') { - throw new Error('Actual is not a function'); - } - try { - this.actual(); - } catch (e) { - exception = e; - } - if (exception) { - result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); - } - - var not = this.isNot ? "not " : ""; - - this.message = function() { - if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { - return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); - } else { - return "Expected function to throw an exception."; - } - }; - - return result; -}; - -jasmine.Matchers.Any = function(expectedClass) { - this.expectedClass = expectedClass; -}; - -jasmine.Matchers.Any.prototype.matches = function(other) { - if (this.expectedClass == String) { - return typeof other == 'string' || other instanceof String; - } - - if (this.expectedClass == Number) { - return typeof other == 'number' || other instanceof Number; - } - - if (this.expectedClass == Function) { - return typeof other == 'function' || other instanceof Function; - } - - if (this.expectedClass == Object) { - return typeof other == 'object'; - } - - return other instanceof this.expectedClass; -}; - -jasmine.Matchers.Any.prototype.toString = function() { - return ''; -}; - -/** - * @constructor - */ -jasmine.MultiReporter = function() { - this.subReporters_ = []; -}; -jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); - -jasmine.MultiReporter.prototype.addReporter = function(reporter) { - this.subReporters_.push(reporter); -}; - -(function() { - var functionNames = [ - "reportRunnerStarting", - "reportRunnerResults", - "reportSuiteResults", - "reportSpecStarting", - "reportSpecResults", - "log" - ]; - for (var i = 0; i < functionNames.length; i++) { - var functionName = functionNames[i]; - jasmine.MultiReporter.prototype[functionName] = (function(functionName) { - return function() { - for (var j = 0; j < this.subReporters_.length; j++) { - var subReporter = this.subReporters_[j]; - if (subReporter[functionName]) { - subReporter[functionName].apply(subReporter, arguments); - } - } - }; - })(functionName); - } -})(); -/** - * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults - * - * @constructor - */ -jasmine.NestedResults = function() { - /** - * The total count of results - */ - this.totalCount = 0; - /** - * Number of passed results - */ - this.passedCount = 0; - /** - * Number of failed results - */ - this.failedCount = 0; - /** - * Was this suite/spec skipped? - */ - this.skipped = false; - /** - * @ignore - */ - this.items_ = []; -}; - -/** - * Roll up the result counts. - * - * @param result - */ -jasmine.NestedResults.prototype.rollupCounts = function(result) { - this.totalCount += result.totalCount; - this.passedCount += result.passedCount; - this.failedCount += result.failedCount; -}; - -/** - * Adds a log message. - * @param values Array of message parts which will be concatenated later. - */ -jasmine.NestedResults.prototype.log = function(values) { - this.items_.push(new jasmine.MessageResult(values)); -}; - -/** - * Getter for the results: message & results. - */ -jasmine.NestedResults.prototype.getItems = function() { - return this.items_; -}; - -/** - * Adds a result, tracking counts (total, passed, & failed) - * @param {jasmine.ExpectationResult|jasmine.NestedResults} result - */ -jasmine.NestedResults.prototype.addResult = function(result) { - if (result.type != 'log') { - if (result.items_) { - this.rollupCounts(result); - } else { - this.totalCount++; - if (result.passed()) { - this.passedCount++; - } else { - this.failedCount++; - } - } - } - this.items_.push(result); -}; - -/** - * @returns {Boolean} True if everything below passed - */ -jasmine.NestedResults.prototype.passed = function() { - return this.passedCount === this.totalCount; -}; -/** - * Base class for pretty printing for expectation results. - */ -jasmine.PrettyPrinter = function() { - this.ppNestLevel_ = 0; -}; - -/** - * Formats a value in a nice, human-readable string. - * - * @param value - */ -jasmine.PrettyPrinter.prototype.format = function(value) { - if (this.ppNestLevel_ > 40) { - throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); - } - - this.ppNestLevel_++; - try { - if (value === jasmine.undefined) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === jasmine.getGlobal()) { - this.emitScalar(''); - } else if (value instanceof jasmine.Matchers.Any) { - this.emitScalar(value.toString()); - } else if (typeof value === 'string') { - this.emitString(value); - } else if (jasmine.isSpy(value)) { - this.emitScalar("spy on " + value.identity); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (jasmine.isArray_(value) || typeof value == 'object') { - value.__Jasmine_been_here_before__ = true; - if (jasmine.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - delete value.__Jasmine_been_here_before__; - } else { - this.emitScalar(value.toString()); - } - } finally { - this.ppNestLevel_--; - } -}; - -jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { - for (var property in obj) { - if (property == '__Jasmine_been_here_before__') continue; - fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && - obj.__lookupGetter__(property) !== null) : false); - } -}; - -jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; - -jasmine.StringPrettyPrinter = function() { - jasmine.PrettyPrinter.call(this); - - this.string = ''; -}; -jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); - -jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); -}; - -jasmine.StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); -}; - -jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { - this.append('[ '); - for (var i = 0; i < array.length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - this.append(' ]'); -}; - -jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { - var self = this; - this.append('{ '); - var first = true; - - this.iterateObject(obj, function(property, isGetter) { - if (first) { - first = false; - } else { - self.append(', '); - } - - self.append(property); - self.append(' : '); - if (isGetter) { - self.append(''); - } else { - self.format(obj[property]); - } - }); - - this.append(' }'); -}; - -jasmine.StringPrettyPrinter.prototype.append = function(value) { - this.string += value; -}; -jasmine.Queue = function(env) { - this.env = env; - this.blocks = []; - this.running = false; - this.index = 0; - this.offset = 0; - this.abort = false; -}; - -jasmine.Queue.prototype.addBefore = function(block) { - this.blocks.unshift(block); -}; - -jasmine.Queue.prototype.add = function(block) { - this.blocks.push(block); -}; - -jasmine.Queue.prototype.insertNext = function(block) { - this.blocks.splice((this.index + this.offset + 1), 0, block); - this.offset++; -}; - -jasmine.Queue.prototype.start = function(onComplete) { - this.running = true; - this.onComplete = onComplete; - this.next_(); -}; - -jasmine.Queue.prototype.isRunning = function() { - return this.running; -}; - -jasmine.Queue.LOOP_DONT_RECURSE = true; - -jasmine.Queue.prototype.next_ = function() { - var self = this; - var goAgain = true; - - while (goAgain) { - goAgain = false; - - if (self.index < self.blocks.length && !this.abort) { - var calledSynchronously = true; - var completedSynchronously = false; - - var onComplete = function () { - if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { - completedSynchronously = true; - return; - } - - if (self.blocks[self.index].abort) { - self.abort = true; - } - - self.offset = 0; - self.index++; - - var now = new Date().getTime(); - if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { - self.env.lastUpdate = now; - self.env.setTimeout(function() { - self.next_(); - }, 0); - } else { - if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { - goAgain = true; - } else { - self.next_(); - } - } - }; - self.blocks[self.index].execute(onComplete); - - calledSynchronously = false; - if (completedSynchronously) { - onComplete(); - } - - } else { - self.running = false; - if (self.onComplete) { - self.onComplete(); - } - } - } -}; - -jasmine.Queue.prototype.results = function() { - var results = new jasmine.NestedResults(); - for (var i = 0; i < this.blocks.length; i++) { - if (this.blocks[i].results) { - results.addResult(this.blocks[i].results()); - } - } - return results; -}; - - -/** - * Runner - * - * @constructor - * @param {jasmine.Env} env - */ -jasmine.Runner = function(env) { - var self = this; - self.env = env; - self.queue = new jasmine.Queue(env); - self.before_ = []; - self.after_ = []; - self.suites_ = []; -}; - -jasmine.Runner.prototype.execute = function() { - var self = this; - if (self.env.reporter.reportRunnerStarting) { - self.env.reporter.reportRunnerStarting(this); - } - self.queue.start(function () { - self.finishCallback(); - }); -}; - -jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.splice(0,0,beforeEachFunction); -}; - -jasmine.Runner.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.splice(0,0,afterEachFunction); -}; - - -jasmine.Runner.prototype.finishCallback = function() { - this.env.reporter.reportRunnerResults(this); -}; - -jasmine.Runner.prototype.addSuite = function(suite) { - this.suites_.push(suite); -}; - -jasmine.Runner.prototype.add = function(block) { - if (block instanceof jasmine.Suite) { - this.addSuite(block); - } - this.queue.add(block); -}; - -jasmine.Runner.prototype.specs = function () { - var suites = this.suites(); - var specs = []; - for (var i = 0; i < suites.length; i++) { - specs = specs.concat(suites[i].specs()); - } - return specs; -}; - -jasmine.Runner.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Runner.prototype.topLevelSuites = function() { - var topLevelSuites = []; - for (var i = 0; i < this.suites_.length; i++) { - if (!this.suites_[i].parentSuite) { - topLevelSuites.push(this.suites_[i]); - } - } - return topLevelSuites; -}; - -jasmine.Runner.prototype.results = function() { - return this.queue.results(); -}; -/** - * Internal representation of a Jasmine specification, or test. - * - * @constructor - * @param {jasmine.Env} env - * @param {jasmine.Suite} suite - * @param {String} description - */ -jasmine.Spec = function(env, suite, description) { - if (!env) { - throw new Error('jasmine.Env() required'); - } - if (!suite) { - throw new Error('jasmine.Suite() required'); - } - var spec = this; - spec.id = env.nextSpecId ? env.nextSpecId() : null; - spec.env = env; - spec.suite = suite; - spec.description = description; - spec.queue = new jasmine.Queue(env); - - spec.afterCallbacks = []; - spec.spies_ = []; - - spec.results_ = new jasmine.NestedResults(); - spec.results_.description = description; - spec.matchersClass = null; -}; - -jasmine.Spec.prototype.getFullName = function() { - return this.suite.getFullName() + ' ' + this.description + '.'; -}; - - -jasmine.Spec.prototype.results = function() { - return this.results_; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.Spec.prototype.log = function() { - return this.results_.log(arguments); -}; - -jasmine.Spec.prototype.runs = function (func) { - var block = new jasmine.Block(this.env, func, this); - this.addToQueue(block); - return this; -}; - -jasmine.Spec.prototype.addToQueue = function (block) { - if (this.queue.isRunning()) { - this.queue.insertNext(block); - } else { - this.queue.add(block); - } -}; - -/** - * @param {jasmine.ExpectationResult} result - */ -jasmine.Spec.prototype.addMatcherResult = function(result) { - this.results_.addResult(result); -}; - -jasmine.Spec.prototype.expect = function(actual) { - var positive = new (this.getMatchersClass_())(this.env, actual, this); - positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); - return positive; -}; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -jasmine.Spec.prototype.waits = function(timeout) { - var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); - this.addToQueue(waitsFunc); - return this; -}; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - var latchFunction_ = null; - var optional_timeoutMessage_ = null; - var optional_timeout_ = null; - - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; - switch (typeof arg) { - case 'function': - latchFunction_ = arg; - break; - case 'string': - optional_timeoutMessage_ = arg; - break; - case 'number': - optional_timeout_ = arg; - break; - } - } - - var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); - this.addToQueue(waitsForFunc); - return this; -}; - -jasmine.Spec.prototype.fail = function (e) { - var expectationResult = new jasmine.ExpectationResult({ - passed: false, - message: e ? jasmine.util.formatException(e) : 'Exception', - trace: { stack: e.stack } - }); - this.results_.addResult(expectationResult); -}; - -jasmine.Spec.prototype.getMatchersClass_ = function() { - return this.matchersClass || this.env.matchersClass; -}; - -jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { - var parent = this.getMatchersClass_(); - var newMatchersClass = function() { - parent.apply(this, arguments); - }; - jasmine.util.inherit(newMatchersClass, parent); - jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); - this.matchersClass = newMatchersClass; -}; - -jasmine.Spec.prototype.finishCallback = function() { - this.env.reporter.reportSpecResults(this); -}; - -jasmine.Spec.prototype.finish = function(onComplete) { - this.removeAllSpies(); - this.finishCallback(); - if (onComplete) { - onComplete(); - } -}; - -jasmine.Spec.prototype.after = function(doAfter) { - if (this.queue.isRunning()) { - this.queue.add(new jasmine.Block(this.env, doAfter, this)); - } else { - this.afterCallbacks.unshift(doAfter); - } -}; - -jasmine.Spec.prototype.execute = function(onComplete) { - var spec = this; - if (!spec.env.specFilter(spec)) { - spec.results_.skipped = true; - spec.finish(onComplete); - return; - } - - this.env.reporter.reportSpecStarting(this); - - spec.env.currentSpec = spec; - - spec.addBeforesAndAftersToQueue(); - - spec.queue.start(function () { - spec.finish(onComplete); - }); -}; - -jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { - var runner = this.env.currentRunner(); - var i; - - for (var suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); - } - } - for (i = 0; i < runner.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); - } - for (i = 0; i < this.afterCallbacks.length; i++) { - this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); - } - for (suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); - } - } - for (i = 0; i < runner.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); - } -}; - -jasmine.Spec.prototype.explodes = function() { - throw 'explodes function should not have been called'; -}; - -jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { - if (obj == jasmine.undefined) { - throw "spyOn could not find an object to spy upon for " + methodName + "()"; - } - - if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { - throw methodName + '() method does not exist'; - } - - if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { - throw new Error(methodName + ' has already been spied upon'); - } - - var spyObj = jasmine.createSpy(methodName); - - this.spies_.push(spyObj); - spyObj.baseObj = obj; - spyObj.methodName = methodName; - spyObj.originalValue = obj[methodName]; - - obj[methodName] = spyObj; - - return spyObj; -}; - -jasmine.Spec.prototype.removeAllSpies = function() { - for (var i = 0; i < this.spies_.length; i++) { - var spy = this.spies_[i]; - spy.baseObj[spy.methodName] = spy.originalValue; - } - this.spies_ = []; -}; - -/** - * Internal representation of a Jasmine suite. - * - * @constructor - * @param {jasmine.Env} env - * @param {String} description - * @param {Function} specDefinitions - * @param {jasmine.Suite} parentSuite - */ -jasmine.Suite = function(env, description, specDefinitions, parentSuite) { - var self = this; - self.id = env.nextSuiteId ? env.nextSuiteId() : null; - self.description = description; - self.queue = new jasmine.Queue(env); - self.parentSuite = parentSuite; - self.env = env; - self.before_ = []; - self.after_ = []; - self.children_ = []; - self.suites_ = []; - self.specs_ = []; -}; - -jasmine.Suite.prototype.getFullName = function() { - var fullName = this.description; - for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; - } - return fullName; -}; - -jasmine.Suite.prototype.finish = function(onComplete) { - this.env.reporter.reportSuiteResults(this); - this.finished = true; - if (typeof(onComplete) == 'function') { - onComplete(); - } -}; - -jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.unshift(beforeEachFunction); -}; - -jasmine.Suite.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.unshift(afterEachFunction); -}; - -jasmine.Suite.prototype.results = function() { - return this.queue.results(); -}; - -jasmine.Suite.prototype.add = function(suiteOrSpec) { - this.children_.push(suiteOrSpec); - if (suiteOrSpec instanceof jasmine.Suite) { - this.suites_.push(suiteOrSpec); - this.env.currentRunner().addSuite(suiteOrSpec); - } else { - this.specs_.push(suiteOrSpec); - } - this.queue.add(suiteOrSpec); -}; - -jasmine.Suite.prototype.specs = function() { - return this.specs_; -}; - -jasmine.Suite.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Suite.prototype.children = function() { - return this.children_; -}; - -jasmine.Suite.prototype.execute = function(onComplete) { - var self = this; - this.queue.start(function () { - self.finish(onComplete); - }); -}; -jasmine.WaitsBlock = function(env, timeout, spec) { - this.timeout = timeout; - jasmine.Block.call(this, env, null, spec); -}; - -jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); - -jasmine.WaitsBlock.prototype.execute = function (onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); - } - this.env.setTimeout(function () { - onComplete(); - }, this.timeout); -}; -/** - * A block which waits for some condition to become true, with timeout. - * - * @constructor - * @extends jasmine.Block - * @param {jasmine.Env} env The Jasmine environment. - * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. - * @param {Function} latchFunction A function which returns true when the desired condition has been met. - * @param {String} message The message to display if the desired condition hasn't been met within the given time period. - * @param {jasmine.Spec} spec The Jasmine spec. - */ -jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { - this.timeout = timeout || env.defaultTimeoutInterval; - this.latchFunction = latchFunction; - this.message = message; - this.totalTimeSpentWaitingForLatch = 0; - jasmine.Block.call(this, env, null, spec); -}; -jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); - -jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; - -jasmine.WaitsForBlock.prototype.execute = function(onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); - } - var latchFunctionResult; - try { - latchFunctionResult = this.latchFunction.apply(this.spec); - } catch (e) { - this.spec.fail(e); - onComplete(); - return; - } - - if (latchFunctionResult) { - onComplete(); - } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { - var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); - this.spec.fail({ - name: 'timeout', - message: message - }); - - this.abort = true; - onComplete(); - } else { - this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; - var self = this; - this.env.setTimeout(function() { - self.execute(onComplete); - }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); - } -}; -// Mock setTimeout, clearTimeout -// Contributed by Pivotal Computer Systems, www.pivotalsf.com - -jasmine.FakeTimer = function() { - this.reset(); - - var self = this; - self.setTimeout = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); - return self.timeoutsMade; - }; - - self.setInterval = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); - return self.timeoutsMade; - }; - - self.clearTimeout = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - - self.clearInterval = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - -}; - -jasmine.FakeTimer.prototype.reset = function() { - this.timeoutsMade = 0; - this.scheduledFunctions = {}; - this.nowMillis = 0; -}; - -jasmine.FakeTimer.prototype.tick = function(millis) { - var oldMillis = this.nowMillis; - var newMillis = oldMillis + millis; - this.runFunctionsWithinRange(oldMillis, newMillis); - this.nowMillis = newMillis; -}; - -jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { - var scheduledFunc; - var funcsToRun = []; - for (var timeoutKey in this.scheduledFunctions) { - scheduledFunc = this.scheduledFunctions[timeoutKey]; - if (scheduledFunc != jasmine.undefined && - scheduledFunc.runAtMillis >= oldMillis && - scheduledFunc.runAtMillis <= nowMillis) { - funcsToRun.push(scheduledFunc); - this.scheduledFunctions[timeoutKey] = jasmine.undefined; - } - } - - if (funcsToRun.length > 0) { - funcsToRun.sort(function(a, b) { - return a.runAtMillis - b.runAtMillis; - }); - for (var i = 0; i < funcsToRun.length; ++i) { - try { - var funcToRun = funcsToRun[i]; - this.nowMillis = funcToRun.runAtMillis; - funcToRun.funcToCall(); - if (funcToRun.recurring) { - this.scheduleFunction(funcToRun.timeoutKey, - funcToRun.funcToCall, - funcToRun.millis, - true); - } - } catch(e) { - } - } - this.runFunctionsWithinRange(oldMillis, nowMillis); - } -}; - -jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { - this.scheduledFunctions[timeoutKey] = { - runAtMillis: this.nowMillis + millis, - funcToCall: funcToCall, - recurring: recurring, - timeoutKey: timeoutKey, - millis: millis - }; -}; - -/** - * @namespace - */ -jasmine.Clock = { - defaultFakeTimer: new jasmine.FakeTimer(), - - reset: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.reset(); - }, - - tick: function(millis) { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.tick(millis); - }, - - runFunctionsWithinRange: function(oldMillis, nowMillis) { - jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); - }, - - scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { - jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); - }, - - useMock: function() { - if (!jasmine.Clock.isInstalled()) { - var spec = jasmine.getEnv().currentSpec; - spec.after(jasmine.Clock.uninstallMock); - - jasmine.Clock.installMock(); - } - }, - - installMock: function() { - jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; - }, - - uninstallMock: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.installed = jasmine.Clock.real; - }, - - real: { - setTimeout: jasmine.getGlobal().setTimeout, - clearTimeout: jasmine.getGlobal().clearTimeout, - setInterval: jasmine.getGlobal().setInterval, - clearInterval: jasmine.getGlobal().clearInterval - }, - - assertInstalled: function() { - if (!jasmine.Clock.isInstalled()) { - throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); - } - }, - - isInstalled: function() { - return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; - }, - - installed: null -}; -jasmine.Clock.installed = jasmine.Clock.real; - -//else for IE support -jasmine.getGlobal().setTimeout = function(funcToCall, millis) { - if (jasmine.Clock.installed.setTimeout.apply) { - return jasmine.Clock.installed.setTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.setTimeout(funcToCall, millis); - } -}; - -jasmine.getGlobal().setInterval = function(funcToCall, millis) { - if (jasmine.Clock.installed.setInterval.apply) { - return jasmine.Clock.installed.setInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.setInterval(funcToCall, millis); - } -}; - -jasmine.getGlobal().clearTimeout = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearTimeout(timeoutKey); - } -}; - -jasmine.getGlobal().clearInterval = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearInterval(timeoutKey); - } -}; - -jasmine.version_= { - "major": 1, - "minor": 1, - "build": 0, - "revision": 1315677058 -}; diff --git a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png b/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png deleted file mode 100644 index 218f3b437..000000000 Binary files a/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/LICENSE b/node_modules/mongodb/node_modules/kerberos/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/node_modules/mongodb/node_modules/kerberos/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/node_modules/mongodb/node_modules/kerberos/README.md b/node_modules/mongodb/node_modules/kerberos/README.md deleted file mode 100644 index 7428b0d0e..000000000 --- a/node_modules/mongodb/node_modules/kerberos/README.md +++ /dev/null @@ -1,4 +0,0 @@ -kerberos -======== - -Kerberos library for node.js \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/binding.gyp b/node_modules/mongodb/node_modules/kerberos/binding.gyp deleted file mode 100644 index 027a70f20..000000000 --- a/node_modules/mongodb/node_modules/kerberos/binding.gyp +++ /dev/null @@ -1,41 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'kerberos', - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'conditions': [ - ['OS=="mac"', { - 'sources': [ 'lib/kerberos.cc', 'lib/worker.cc', 'lib/kerberosgss.c', 'lib/base64.c', 'lib/kerberos_context.cc' ], - 'defines': [ - '__MACOSX_CORE__' - ], - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' - }, - "link_settings": { - "libraries": [ - "-lkrb5" - ] - } - }], - ['OS=="win"', { - 'sources': [ - 'lib/win32/kerberos.cc', - 'lib/win32/base64.c', - 'lib/win32/worker.cc', - 'lib/win32/kerberos_sspi.c', - 'lib/win32/wrappers/security_buffer.cc', - 'lib/win32/wrappers/security_buffer_descriptor.cc', - 'lib/win32/wrappers/security_context.cc', - 'lib/win32/wrappers/security_credentials.cc' - ], - "link_settings": { - "libraries": [ - ] - } - }] - ] - } - ] -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/build/Makefile b/node_modules/mongodb/node_modules/kerberos/build/Makefile deleted file mode 100644 index 5d8753212..000000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Makefile +++ /dev/null @@ -1,332 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= flock $(builddir)/linker.lock $(CXX.target) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= $(CXX.host) -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,kerberos.target.mk)))),) - include kerberos.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/vagrant/lab4/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/vagrant/.node-gyp/0.10.24/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/vagrant/.node-gyp/0.10.24" "-Dmodule_root_dir=/home/vagrant/lab4/node_modules/mongodb/node_modules/kerberos" binding.gyp -Makefile: $(srcdir)/../../../../../.node-gyp/0.10.24/common.gypi $(srcdir)/../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d deleted file mode 100644 index 0bc320607..000000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/kerberos.node := rm -rf "Release/kerberos.node" && cp -af "Release/obj.target/kerberos.node" "Release/kerberos.node" diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d b/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d deleted file mode 100644 index ba6dec80c..000000000 --- a/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/kerberos.node := flock ./Release/linker.lock g++ -shared -pthread -rdynamic -m32 -Wl,-soname=kerberos.node -o Release/obj.target/kerberos.node -Wl,--start-group -Wl,--end-group diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node b/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node deleted file mode 100644 index 5d872403f..000000000 Binary files a/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock b/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock deleted file mode 100644 index e69de29bb..000000000 diff --git a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos.node b/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos.node deleted file mode 100644 index 5d872403f..000000000 Binary files a/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos.node and /dev/null differ diff --git a/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile b/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile deleted file mode 100644 index d0d9c64a7..000000000 --- a/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= build/./. -.PHONY: all -all: - $(MAKE) kerberos diff --git a/node_modules/mongodb/node_modules/kerberos/build/config.gypi b/node_modules/mongodb/node_modules/kerberos/build/config.gypi deleted file mode 100644 index 91ce77280..000000000 --- a/node_modules/mongodb/node_modules/kerberos/build/config.gypi +++ /dev/null @@ -1,115 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 0, - "gcc_version": 46, - "host_arch": "ia32", - "node_install_npm": "true", - "node_prefix": "/usr/local", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "node_use_systemtap": "false", - "python": "/usr/bin/python", - "target_arch": "ia32", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "true", - "nodedir": "/home/vagrant/.node-gyp/0.10.24", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "sign_git_tag": "", - "always_auth": "", - "user_agent": "node/v0.10.24 linux ia32", - "bin_links": "true", - "key": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "user": "", - "force": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "cache_max": "null", - "userconfig": "/home/vagrant/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "tmp": "/home/vagrant/tmp", - "depth": "null", - "save_dev": "", - "usage": "", - "https_proxy": "", - "onload_script": "", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/bash", - "prefix": "/usr/local", - "registry": "https://registry.npmjs.org/", - "browser": "", - "cache_lock_wait": "10000", - "save_optional": "", - "searchopts": "", - "versions": "", - "cache": "/home/vagrant/.npm", - "ignore_scripts": "", - "searchsort": "name", - "version": "", - "local_address": "", - "viewer": "man", - "color": "true", - "fetch_retry_mintimeout": "10000", - "umask": "18", - "fetch_retry_maxtimeout": "60000", - "message": "%s", - "cert": "", - "global": "", - "link": "", - "save": "", - "unicode": "true", - "long": "", - "production": "", - "unsafe_perm": "true", - "node_version": "v0.10.24", - "tag": "latest", - "git_tag_version": "true", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "npat": "", - "proprietary_attribs": "true", - "strict_ssl": "true", - "username": "", - "dev": "", - "globalconfig": "/usr/local/etc/npmrc", - "init_module": "/home/vagrant/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/local/etc/npmignore", - "cache_lock_retries": "10", - "group": "1000", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "email": "", - "json": "" - } -} diff --git a/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk b/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk deleted file mode 100644 index d2ce49b92..000000000 --- a/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk +++ /dev/null @@ -1,42 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := kerberos -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m32 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m32 - -LIBS := - -$(obj).target/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/kerberos.node: LIBS := $(LIBS) -$(obj).target/kerberos.node: TOOLSET := $(TOOLSET) -$(obj).target/kerberos.node: FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/kerberos.node -# Add target alias -.PHONY: kerberos -kerberos: $(builddir)/kerberos.node - -# Copy this to the executable output path. -$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) -$(builddir)/kerberos.node: $(obj).target/kerberos.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/kerberos.node -# Short alias for building this executable. -.PHONY: kerberos.node -kerberos.node: $(obj).target/kerberos.node $(builddir)/kerberos.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/kerberos.node - diff --git a/node_modules/mongodb/node_modules/kerberos/index.js b/node_modules/mongodb/node_modules/kerberos/index.js deleted file mode 100644 index b8c853276..000000000 --- a/node_modules/mongodb/node_modules/kerberos/index.js +++ /dev/null @@ -1,6 +0,0 @@ -// Get the Kerberos library -module.exports = require('./lib/kerberos'); -// Set up the auth processes -module.exports['processes'] = { - MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js b/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js deleted file mode 100644 index f1e9231a7..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js +++ /dev/null @@ -1,281 +0,0 @@ -var format = require('util').format; - -var MongoAuthProcess = function(host, port, service_name) { - // Check what system we are on - if(process.platform == 'win32') { - this._processor = new Win32MongoProcessor(host, port, service_name); - } else { - this._processor = new UnixMongoProcessor(host, port, service_name); - } -} - -MongoAuthProcess.prototype.init = function(username, password, callback) { - this._processor.init(username, password, callback); -} - -MongoAuthProcess.prototype.transition = function(payload, callback) { - this._processor.transition(payload, callback); -} - -/******************************************************************* - * - * Win32 SSIP Processor for MongoDB - * - *******************************************************************/ -var Win32MongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.ssip = require("../kerberos").SSIP; - // Set up first transition - this._transition = Win32MongoProcessor.first_transition(this); - // Set up service name - service_name = service_name || "mongodb"; - // Set up target - this.target = format("%s/%s", service_name, host); - // Number of retries - this.retries = 10; -} - -Win32MongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - // Save the values used later - this.username = username; - this.password = password; - // Aquire credentials - this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { - if(err) return callback(err); - // Save credentials - self.security_credentials = security_credentials; - // Callback with success - callback(null); - }); -} - -Win32MongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -Win32MongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.ssip.SecurityContext.initialize( - self.security_credentials, - self.target, - payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.second_transition(self); - self.security_context = security_context; - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.second_transition = function(self) { - return function(payload, callback) { - // Perform a step - self.security_context.initialize(self.target, payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - self._transition = Win32MongoProcessor.first_transition(self); - // Retry - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.third_transition(self); - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.third_transition = function(self) { - return function(payload, callback) { - var messageLength = 0; - // Get the raw bytes - var encryptedBytes = new Buffer(payload, 'base64'); - var encryptedMessage = new Buffer(messageLength); - // Copy first byte - encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); - // Set up trailer - var securityTrailerLength = encryptedBytes.length - messageLength; - var securityTrailer = new Buffer(securityTrailerLength); - // Copy the bytes - encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); - - // Types used - var SecurityBuffer = self.ssip.SecurityBuffer; - var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; - - // Set up security buffers - var buffers = [ - new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) - , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) - ]; - - // Set up the descriptor - var descriptor = new SecurityBufferDescriptor(buffers); - - // Decrypt the data - self.security_context.decryptMessage(descriptor, function(err, security_context) { - if(err) return callback(err); - - var length = 4; - if(self.username != null) { - length += self.username.length; - } - - var bytesReceivedFromServer = new Buffer(length); - bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION - bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION - - if(self.username != null) { - var authorization_id_bytes = new Buffer(self.username, 'utf8'); - authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); - } - - self.security_context.queryContextAttributes(0x00, function(err, sizes) { - if(err) return callback(err); - - var buffers = [ - new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) - , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) - , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) - ] - - var descriptor = new SecurityBufferDescriptor(buffers); - - self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { - if(err) return callback(err); - callback(null, security_context.payload); - }); - }); - }); - } -} - -/******************************************************************* - * - * UNIX MIT Kerberos processor - * - *******************************************************************/ -var UnixMongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.Kerberos = require("../kerberos").Kerberos; - this.kerberos = new this.Kerberos(); - service_name = service_name || "mongodb"; - // Set up first transition - this._transition = UnixMongoProcessor.first_transition(this); - // Set up target - this.target = format("%s@%s", service_name, host); - // Number of retries - this.retries = 10; -} - -UnixMongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - this.username = username; - this.password = password; - // Call client initiate - this.kerberos.authGSSClientInit( - self.target - , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - self.context = context; - // Return the context - callback(null, context); - }); -} - -UnixMongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -UnixMongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, '', function(err, result) { - if(err) return callback(err); - // Set up the next step - self._transition = UnixMongoProcessor.second_transition(self); - // Return the payload - callback(null, self.context.response); - }) - } -} - -UnixMongoProcessor.second_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { - if(err && self.retries == 0) return callback(err); - // Attempt to re-establish a context - if(err) { - // Adjust the number of retries - self.retries = self.retries - 1; - // Call same step again - return self.transition(payload, callback); - } - - // Set up the next step - self._transition = UnixMongoProcessor.third_transition(self); - // Return the payload - callback(null, self.context.response || ''); - }); - } -} - -UnixMongoProcessor.third_transition = function(self) { - return function(payload, callback) { - // GSS Client Unwrap - self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { - if(err) return callback(err, false); - - // Wrap the response - self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { - if(err) return callback(err, false); - // Set up the next step - self._transition = UnixMongoProcessor.fourth_transition(self); - // Return the payload - callback(null, self.context.response); - }); - }); - } -} - -UnixMongoProcessor.fourth_transition = function(self) { - return function(payload, callback) { - // Clean up context - self.kerberos.authGSSClientClean(self.context, function(err, result) { - if(err) return callback(err, false); - // Set the transition to null - self._transition = null; - // Callback with valid authentication - callback(null, true); - }); - } -} - -// Set the process -exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/base64.c b/node_modules/mongodb/node_modules/kerberos/lib/base64.c deleted file mode 100644 index 4232106b9..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/base64.c +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - unsigned char oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - *rlen = 0; - int c1, c2, c3, c4; - - int vlen = strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/base64.h b/node_modules/mongodb/node_modules/kerberos/lib/base64.h deleted file mode 100644 index f0e1f0616..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc b/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc deleted file mode 100644 index 08eda82b2..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc +++ /dev/null @@ -1,563 +0,0 @@ -#include "kerberos.h" -#include -#include "worker.h" -#include "kerberos_context.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -Persistent Kerberos::constructor_template; - -// Call structs -typedef struct AuthGSSClientCall { - uint32_t flags; - char *uri; -} AuthGSSClientCall; - -typedef struct AuthGSSClientStepCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientStepCall; - -typedef struct AuthGSSClientUnwrapCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientUnwrapCall; - -typedef struct AuthGSSClientWrapCall { - KerberosContext *context; - char *challenge; - char *user_name; -} AuthGSSClientWrapCall; - -typedef struct AuthGSSClientCleanCall { - KerberosContext *context; -} AuthGSSClientCleanCall; - -// VException object (causes throw in calling code) -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(Kerberos::New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("Kerberos")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientInit", AuthGSSClientInit); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientStep", AuthGSSClientStep); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientUnwrap", AuthGSSClientUnwrap); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientWrap", AuthGSSClientWrap); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientClean", AuthGSSClientClean); - - // Set the symbol - target->ForceSet(String::NewSymbol("Kerberos"), constructor_template->GetFunction()); -} - -Handle Kerberos::New(const Arguments &args) { - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - return args.This(); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientInit(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_client_state *)malloc(sizeof(gss_client_state)); - - // Unpack the parameter data struct - AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; - // Start the kerberos client - response = authenticate_gss_client_init(call->uri, call->flags, state); - - // Release the parameter struct memory - free(call->uri); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Handle _map_authGSSClientInit(Worker *worker) { - HandleScope scope; - - KerberosContext *context = KerberosContext::New(); - context->state = (gss_client_state *)worker->return_value; - // Persistent _context = Persistent::New(context->handle_); - return scope.Close(context->handle_); -} - -// Initialize method -Handle Kerberos::AuthGSSClientInit(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 3) return VException("Requires a service string uri, integer flags and a callback function"); - if(args.Length() == 3 && !args[0]->IsString() && !args[1]->IsInt32() && !args[2]->IsFunction()) - return VException("Requires a service string uri, integer flags and a callback function"); - - Local service = args[0]->ToString(); - // Convert uri string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - service->WriteUtf8(service_str); - - // Allocate a structure - AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); - call->flags =args[1]->ToInt32()->Uint32Value(); - call->uri = service_str; - - // Unpack the callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientInit; - worker->mapper = _map_authGSSClientInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientStep(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; - // Get the state - state = call->context->state; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_step(state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientStep(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientStep(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0])) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString()) return VException("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientStep; - worker->mapper = _map_authGSSClientStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientUnwrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientUnwrap(Worker *worker) { - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_unwrap(call->context->state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientUnwrap(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientUnwrap(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callback = args.Length() == 3 ? Local::Cast(args[2]) : Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientUnwrap; - worker->mapper = _map_authGSSClientUnwrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientWrap(Worker *worker) { - gss_client_response *response; - char *user_name = NULL; - - // Unpack the parameter data struct - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; - user_name = call->user_name; - - // Check what kind of challenge we have - if(call->user_name == NULL) { - user_name = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - if(call->user_name != NULL) free(call->user_name); - free(call); - free(response); -} - -static Handle _map_authGSSClientWrap(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientWrap(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 3 && args.Length() != 4) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 4 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - - // Challenge string - char *challenge_str = NULL; - char *user_name_str = NULL; - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - // If we have a user string - if(args.Length() == 4) { - // Unpack user name - Local user_name = args[2]->ToString(); - // Convert uri string to c-string - user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - user_name->WriteUtf8(user_name_str); - } - - // Allocate a structure - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - call->user_name = user_name_str; - - // Unpack the callback - Local callback = args.Length() == 4 ? Local::Cast(args[3]) : Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientWrap; - worker->mapper = _map_authGSSClientWrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_client_clean(call->context->state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Handle _map_authGSSClientClean(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientClean(const Arguments &args) { - HandleScope scope; - - // // Ensure valid call - if(args.Length() != 2) return VException("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return VException("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Allocate a structure - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); - call->context = kerberos_context; - - // Unpack the callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientClean; - worker->mapper = _map_authGSSClientClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Kerberos::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void Kerberos::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - delete worker; -} - -// Exporting function -extern "C" void init(Handle target) { - HandleScope scope; - Kerberos::Initialize(target); - KerberosContext::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h b/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h deleted file mode 100644 index 061995700..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include - -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static Handle AuthGSSClientInit(const Arguments &args); - static Handle AuthGSSClientStep(const Arguments &args); - static Handle AuthGSSClientUnwrap(const Arguments &args); - static Handle AuthGSSClientWrap(const Arguments &args); - static Handle AuthGSSClientClean(const Arguments &args); - -private: - static Handle New(const Arguments &args); - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js b/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js deleted file mode 100644 index b1a701ba0..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js +++ /dev/null @@ -1,91 +0,0 @@ -var kerberos = require('../build/Release/kerberos') - , KerberosNative = kerberos.Kerberos; - -var Kerberos = function() { - this._native_kerberos = new KerberosNative(); -} - -Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { - return this._native_kerberos.authGSSClientInit(uri, flags, callback); -} - -Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientStep(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { - if(typeof user_name == 'function') { - callback = user_name; - user_name = ''; - } - - return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); -} - -Kerberos.prototype.authGSSClientClean = function(context, callback) { - return this._native_kerberos.authGSSClientClean(context, callback); -} - -Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { - return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); -} - -Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { - return this._native_kerberos.prepareOutboundPackage(principal, inputdata); -} - -Kerberos.prototype.decryptMessage = function(challenge) { - return this._native_kerberos.decryptMessage(challenge); -} - -Kerberos.prototype.encryptMessage = function(challenge) { - return this._native_kerberos.encryptMessage(challenge); -} - -Kerberos.prototype.queryContextAttribute = function(attribute) { - if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); - return this._native_kerberos.queryContextAttribute(attribute); -} - -// Some useful result codes -Kerberos.AUTH_GSS_CONTINUE = 0; -Kerberos.AUTH_GSS_COMPLETE = 1; - -// Some useful gss flags -Kerberos.GSS_C_DELEG_FLAG = 1; -Kerberos.GSS_C_MUTUAL_FLAG = 2; -Kerberos.GSS_C_REPLAY_FLAG = 4; -Kerberos.GSS_C_SEQUENCE_FLAG = 8; -Kerberos.GSS_C_CONF_FLAG = 16; -Kerberos.GSS_C_INTEG_FLAG = 32; -Kerberos.GSS_C_ANON_FLAG = 64; -Kerberos.GSS_C_PROT_READY_FLAG = 128; -Kerberos.GSS_C_TRANS_FLAG = 256; - -// Export Kerberos class -exports.Kerberos = Kerberos; - -// If we have SSPI (windows) -if(kerberos.SecurityCredentials) { - // Put all SSPI classes in it's own namespace - exports.SSIP = { - SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext: require('./win32/wrappers/security_context').SecurityContext - , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - } -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc b/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc deleted file mode 100644 index 7a5f4eb8d..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc +++ /dev/null @@ -1,74 +0,0 @@ -#include "kerberos_context.h" - -Persistent KerberosContext::constructor_template; - -KerberosContext::KerberosContext() : ObjectWrap() { -} - -KerberosContext::~KerberosContext() { -} - -KerberosContext* KerberosContext::New() { - HandleScope scope; - - Local obj = constructor_template->GetFunction()->NewInstance(); - KerberosContext *kerberos_context = ObjectWrap::Unwrap(obj); - - return kerberos_context; -} - -Handle KerberosContext::New(const Arguments &args) { - HandleScope scope; - // Create code object - KerberosContext *kerberos_context = new KerberosContext(); - // Wrap it - kerberos_context->Wrap(args.This()); - // Return the object - return args.This(); -} - -static Persistent response_symbol; - -void KerberosContext::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("KerberosContext")); - - // Property symbols - response_symbol = NODE_PSYMBOL("response"); - - // Getter for the response - constructor_template->InstanceTemplate()->SetAccessor(response_symbol, ResponseGetter); - - // Set up the Symbol for the Class on the Module - target->Set(String::NewSymbol("KerberosContext"), constructor_template->GetFunction()); -} - -// -// Response Setter / Getter -Handle KerberosContext::ResponseGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - gss_client_state *state; - - // Unpack the object - KerberosContext *context = ObjectWrap::Unwrap(info.Holder()); - // Let's grab the response - state = context->state; - // No state no response - if(state == NULL || state->response == NULL) return scope.Close(Null()); - // Return the response - return scope.Close(String::New(state->response)); -} - - - - - - - - - diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h b/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h deleted file mode 100644 index 8becef6d3..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef KERBEROS_CONTEXT_H -#define KERBEROS_CONTEXT_H - -#include -#include -#include -#include - -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class KerberosContext : public ObjectWrap { - -public: - KerberosContext(); - ~KerberosContext(); - - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Public constructor - static KerberosContext* New(); - - // Handle to the kerberos context - gss_client_state *state; - -private: - static Handle New(const Arguments &args); - - static Handle ResponseGetter(Local property, const AccessorInfo& info); -}; -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c b/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c deleted file mode 100644 index f17003db3..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c +++ /dev/null @@ -1,666 +0,0 @@ -/** - * Copyright (c) 2006-2010 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "kerberosgss.h" - -#include "base64.h" - -#include -#include -#include -#include - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min); - -/*extern PyObject *GssException_class; -extern PyObject *KrbException_class; - -char* server_principal_details(const char* service, const char* hostname) -{ - char match[1024]; - int match_len = 0; - char* result = NULL; - - int code; - krb5_context kcontext; - krb5_keytab kt = NULL; - krb5_kt_cursor cursor = NULL; - krb5_keytab_entry entry; - char* pname = NULL; - - // Generate the principal prefix we want to match - snprintf(match, 1024, "%s/%s@", service, hostname); - match_len = strlen(match); - - code = krb5_init_context(&kcontext); - if (code) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot initialize Kerberos5 context", code)); - return NULL; - } - - if ((code = krb5_kt_default(kcontext, &kt))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get default keytab", code)); - goto end; - } - - if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get sequence cursor from keytab", code)); - goto end; - } - - while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) - { - if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot parse principal name from keytab", code)); - goto end; - } - - if (strncmp(pname, match, match_len) == 0) - { - result = malloc(strlen(pname) + 1); - strcpy(result, pname); - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - break; - } - - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - } - - if (result == NULL) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Principal not found in keytab", -1)); - } - -end: - if (cursor) - krb5_kt_end_seq_get(kcontext, kt, &cursor); - if (kt) - krb5_kt_close(kcontext, kt); - krb5_free_context(kcontext); - - return result; -} -*/ -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_COMPLETE; - - state->server_name = GSS_C_NO_NAME; - state->context = GSS_C_NO_CONTEXT; - state->gss_flags = gss_flags; - state->username = NULL; - state->response = NULL; - - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if(state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - - if(state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - - if(state->username != NULL) { - free(state->username); - state->username = NULL; - } - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_init_sec_context(&min_stat, - GSS_C_NO_CREDENTIAL, - &state->context, - state->server_name, - GSS_C_NO_OID, - (OM_uint32)state->gss_flags, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - NULL, - &output_token, - NULL, - NULL); - - if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; - // Grab the client response to send back to the server - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Try to get the user name if we have completed all GSS operations - if (ret == AUTH_GSS_COMPLETE) { - gss_name_t gssuser = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); - - if(GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - gss_buffer_desc name_token; - name_token.length = 0; - maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); - - if(GSS_ERROR(maj_stat)) { - if(name_token.value) - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - state->username = (char *)malloc(name_token.length + 1); - strncpy(state->username, (char*) name_token.value, name_token.length); - state->username[name_token.length] = 0; - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - } - } - -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_unwrap(&min_stat, - state->context, - &input_token, - &output_token, - NULL, - NULL); - - if(maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - ret = AUTH_GSS_COMPLETE; - } - - // Grab the client response - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - char buf[4096], server_conf_flags; - unsigned long buf_size; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - if(user) { - // get bufsize - server_conf_flags = ((char*) input_token.value)[0]; - ((char*) input_token.value)[0] = 0; - buf_size = ntohl(*((long *) input_token.value)); - free(input_token.value); -#ifdef PRINTFS - printf("User: %s, %c%c%c\n", user, - server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', - server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', - server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); - printf("Maximum GSS token size is %ld\n", buf_size); -#endif - - // agree to terms (hack!) - buf_size = htonl(buf_size); // not relevant without integrity/privacy - memcpy(buf, &buf_size, 4); - buf[0] = GSS_AUTH_P_NONE; - // server decides if principal can log in as user - strncpy(buf + 4, user, sizeof(buf) - 4); - input_token.value = buf; - input_token.length = 4 + strlen(user); - } - - // Do GSSAPI wrap - maj_stat = gss_wrap(&min_stat, - state->context, - 0, - GSS_C_QOP_DEFAULT, - &input_token, - NULL, - &output_token); - - if (maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else - ret = AUTH_GSS_COMPLETE; - // Grab the client response to send back to the server - if (output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -int authenticate_gss_server_init(const char *service, gss_server_state *state) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_COMPLETE; - - state->context = GSS_C_NO_CONTEXT; - state->server_name = GSS_C_NO_NAME; - state->client_name = GSS_C_NO_NAME; - state->server_creds = GSS_C_NO_CREDENTIAL; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->targetname = NULL; - state->response = NULL; - - // Server name may be empty which means we aren't going to create our own creds - size_t service_len = strlen(service); - if (service_len != 0) - { - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Get credentials - maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, GSS_C_ACCEPT, &state->server_creds, NULL, NULL); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - } - -end: - return ret; -} - -int authenticate_gss_server_clean(gss_server_state *state) -{ - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->client_name); - if (state->server_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->server_creds); - if (state->client_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) - { - free(state->username); - state->username = NULL; - } - if (state->targetname != NULL) - { - free(state->targetname); - state->targetname = NULL; - } - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - return ret; -} - -/*int authenticate_gss_server_step(gss_server_state *state, const char *challenge) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) - { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - else - { - PyErr_SetString(KrbException_class, "No challenge parameter in request from client"); - ret = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_accept_sec_context(&min_stat, - &state->context, - state->server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &state->client_name, - NULL, - &output_token, - NULL, - NULL, - &state->client_creds); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Grab the server response to send back to the client - if (output_token.length) - { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Get the user name - maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->username = (char *)malloc(output_token.length + 1); - strncpy(state->username, (char*) output_token.value, output_token.length); - state->username[output_token.length] = 0; - - // Get the target name if no server creds were supplied - if (state->server_creds == GSS_C_NO_CREDENTIAL) - { - gss_name_t target_name = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->targetname = (char *)malloc(output_token.length + 1); - strncpy(state->targetname, (char*) output_token.value, output_token.length); - state->targetname[output_token.length] = 0; - } - - ret = AUTH_GSS_COMPLETE; - -end: - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - return ret; -} -*/ - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char buf_maj[512]; - char buf_min[512]; - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, sizeof(buf_maj)); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if (!GSS_ERROR(maj_stat)) { - - strncpy(buf_min, (char*) status_string.value , sizeof(buf_min)); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); -} - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char *buf_maj = calloc(512, sizeof(char)); - char *buf_min = calloc(512, sizeof(char)); - char *message = NULL; - gss_client_response *response = calloc(1, sizeof(gss_client_response)); - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, 512); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if(!GSS_ERROR(maj_stat)) { - strncpy(buf_min, (char*) status_string.value , 512); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); - - // Join the strings - message = calloc(1026, 1); - // Join the two messages - sprintf(message, "%s, %s", buf_maj, buf_min); - // Free data - free(buf_min); - free(buf_maj); - // Set the message - response->message = message; - // Return the message - return response; -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h b/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h deleted file mode 100644 index 58ac0b714..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2006-2009 Apple Inc. All rights reserved. - * - * 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. - **/ -#ifndef KERBEROS_GSS_H -#define KERBEROS_GSS_H - -#include -#include -#include - -#define krb5_get_err_text(context,code) error_message(code) - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -#define GSS_AUTH_P_NONE 1 -#define GSS_AUTH_P_INTEGRITY 2 -#define GSS_AUTH_P_PRIVACY 4 - -typedef struct { - int return_code; - char *message; -} gss_client_response; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - long int gss_flags; - char* username; - char* response; -} gss_client_state; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_name_t client_name; - gss_cred_id_t server_creds; - gss_cred_id_t client_creds; - char* username; - char* targetname; - char* response; -} gss_server_state; - -// char* server_principal_details(const char* service, const char* hostname); - -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); -gss_client_response *authenticate_gss_client_clean(gss_client_state *state); -gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); -gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); - -int authenticate_gss_server_init(const char* service, gss_server_state* state); -int authenticate_gss_server_clean(gss_server_state *state); -// int authenticate_gss_server_step(gss_server_state *state, const char *challenge); - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min); -#endif diff --git a/node_modules/mongodb/node_modules/kerberos/lib/sspi.js b/node_modules/mongodb/node_modules/kerberos/lib/sspi.js deleted file mode 100644 index d9120fba3..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/sspi.js +++ /dev/null @@ -1,15 +0,0 @@ -// Load the native SSPI classes -var kerberos = require('../build/Release/kerberos') - , Kerberos = kerberos.Kerberos - , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; -var SSPI = function() { -} - -exports.SSPI = SSPI; -exports.SecurityBuffer = SecurityBuffer; -exports.SecurityBufferDescriptor = SecurityBufferDescriptor; -exports.SecurityCredentials = SecurityCredentials; -exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c b/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c deleted file mode 100644 index 502a021c8..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - unsigned char oval; - - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - int c1, c2, c3, c4; - int vlen = (int)strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - *rlen = 0; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h deleted file mode 100644 index f0e1f0616..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc deleted file mode 100644 index 7fd521b8a..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "base64.h" -#include "wrappers/security_buffer.h" -#include "wrappers/security_buffer_descriptor.h" -#include "wrappers/security_context.h" -#include "wrappers/security_credentials.h" - -Persistent Kerberos::constructor_template; - -// VException object (causes throw in calling code) -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(Kerberos::New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("Kerberos")); - // Set the symbol - target->ForceSet(String::NewSymbol("Kerberos"), constructor_template->GetFunction()); -} - -Handle Kerberos::New(const Arguments &args) { - // Load the security.dll library - load_library(); - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - return args.This(); -} - -// Exporting function -extern "C" void init(Handle target) { - HandleScope scope; - Kerberos::Initialize(target); - SecurityContext::Initialize(target); - SecurityBuffer::Initialize(target); - SecurityBufferDescriptor::Initialize(target); - SecurityCredentials::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h deleted file mode 100644 index 8443e78ab..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include - -extern "C" { - #include "kerberos_sspi.h" - #include "base64.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static Handle AcquireAlternateCredentials(const Arguments &args); - static Handle PrepareOutboundPackage(const Arguments &args); - static Handle DecryptMessage(const Arguments &args); - static Handle EncryptMessage(const Arguments &args); - static Handle QueryContextAttributes(const Arguments &args); - -private: - static Handle New(const Arguments &args); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - // package info - SecPkgInfo m_PkgInfo; - // context - CtxtHandle m_Context; - // Do we have a context - bool m_HaveContext; - // Attributes - DWORD CtxtAttr; - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c b/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c deleted file mode 100644 index d75c9ab0a..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c +++ /dev/null @@ -1,244 +0,0 @@ -#include "kerberos_sspi.h" -#include -#include - -static HINSTANCE _sspi_security_dll = NULL; -static HINSTANCE _sspi_secur32_dll = NULL; - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { - // Create function pointer instance - encryptMessage_fn pfn_encryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function to library method - pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); - // Check if the we managed to map function pointer - if(!pfn_encryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); -} - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); - #else - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_acquireCredentialsHandle) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Status - status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, - pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry - ); - - // Call the function - return status; -} - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { - // Create function pointer instance - deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); - - // Check if the we managed to map function pointer - if(!pfn_deleteSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_deleteSecurityContext)(phContext); -} - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { - // Create function pointer instance - decryptMessage_fn pfn_decryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); - - // Check if the we managed to map function pointer - if(!pfn_decryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); -} - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, PCtxtHandle phContext, - LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, - PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, - unsigned long * pfContextAttr, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); - #else - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_initializeSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Execute intialize context - status = (*pfn_initializeSecurityContext)( - phCredential, phContext, pszTargetName, fContextReq, - Reserved1, TargetDataRep, pInput, Reserved2, - phNewContext, pOutput, pfContextAttr, ptsExpiry - ); - - // Call the function - return status; -} -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer -) { - // Create function pointer instance - queryContextAttributes_fn pfn_queryContextAttributes = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - #ifdef _UNICODE - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); - #else - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_queryContextAttributes) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_queryContextAttributes)( - phContext, ulAttribute, pBuffer - ); -} - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface() { - INIT_SECURITY_INTERFACE InitSecurityInterface; - PSecurityFunctionTable pSecurityInterface = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return NULL; - - #ifdef _UNICODE - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceW")); - #else - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceA")); - #endif - - if(!InitSecurityInterface) { - printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); - return NULL; - } - - // Use InitSecurityInterface to get the function table. - pSecurityInterface = (*InitSecurityInterface)(); - - if(!pSecurityInterface) { - printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); - return NULL; - } - - return pSecurityInterface; -} - -/** - * Load security.dll dynamically - */ -int load_library() { - DWORD err; - // Load the library - _sspi_security_dll = LoadLibrary("security.dll"); - - // Check if the library loaded - if(_sspi_security_dll == NULL) { - err = GetLastError(); - return err; - } - - // Load the library - _sspi_secur32_dll = LoadLibrary("secur32.dll"); - - // Check if the library loaded - if(_sspi_secur32_dll == NULL) { - err = GetLastError(); - return err; - } - - return 0; -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h deleted file mode 100644 index a3008dc53..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef SSPI_C_H -#define SSPI_C_H - -#define SECURITY_WIN32 1 - -#include -#include - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); - -typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, // Name of principal - LPSTR pszPackage, // Name of package - unsigned long fCredentialUse, // Flags indicating use - void * pvLogonId, // Pointer to logon ID - void * pAuthData, // Package specific data - SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func - void * pvGetKeyArgument, // Value to pass to GetKey() - PCredHandle phCredential, // (out) Cred Handle - PTimeStamp ptsExpiry // (out) Lifetime (optional) -); - -typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry - ); - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( - PCtxtHandle phContext // Context to delete -); - -typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( - PCtxtHandle phContext, - PSecBufferDesc pMessage, - unsigned long MessageSeqNo, - unsigned long pfQOP -); - -typedef DWORD (WINAPI *decryptMessage_fn)( - PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, // Cred to base context - PCtxtHandle phContext, // Existing context (OPT) - LPSTR pszTargetName, // Name of target - unsigned long fContextReq, // Context Requirements - unsigned long Reserved1, // Reserved, MBZ - unsigned long TargetDataRep, // Data rep of target - PSecBufferDesc pInput, // Input Buffers - unsigned long Reserved2, // Reserved, MBZ - PCtxtHandle phNewContext, // (out) New Context handle - PSecBufferDesc pOutput, // (inout) Output Buffers - unsigned long * pfContextAttr, // (out) Context attrs - PTimeStamp ptsExpiry // (out) Life span (OPT) -); - -typedef DWORD (WINAPI *initializeSecurityContext_fn)( - PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); - -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, // Context to query - unsigned long ulAttribute, // Attribute to query - void * pBuffer // Buffer for attributes -); - -typedef DWORD (WINAPI *queryContextAttributes_fn)( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface(); - -typedef DWORD (WINAPI *initSecurityInterface_fn) (); - -/** - * Load security.dll dynamically - */ -int load_library(); - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc deleted file mode 100644 index e7a472f67..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h deleted file mode 100644 index f73a4a768..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - v8::Persistent callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc deleted file mode 100644 index dd38b5928..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_buffer.h" - -using namespace node; - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -Persistent SecurityBuffer::constructor_template; - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : ObjectWrap() { - this->size = size; - this->data = calloc(size, sizeof(char)); - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : ObjectWrap() { - this->size = size; - this->data = data; - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::~SecurityBuffer() { - free(this->data); -} - -Handle SecurityBuffer::New(const Arguments &args) { - HandleScope scope; - SecurityBuffer *security_obj; - - if(args.Length() != 2) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[0]->IsInt32()) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[1]->IsInt32() && !Buffer::HasInstance(args[1])) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - // Unpack buffer type - uint32_t buffer_type = args[0]->ToUint32()->Value(); - - // If we have an integer - if(args[1]->IsInt32()) { - security_obj = new SecurityBuffer(buffer_type, args[1]->ToUint32()->Value()); - } else { - // Get the length of the Buffer - size_t length = Buffer::Length(args[1]->ToObject()); - // Allocate space for the internal void data pointer - void *data = calloc(length, sizeof(char)); - // Write the data to out of V8 heap space - memcpy(data, Buffer::Data(args[1]->ToObject()), length); - // Create new SecurityBuffer - security_obj = new SecurityBuffer(buffer_type, length, data); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityBuffer::ToBuffer(const Arguments &args) { - HandleScope scope; - - // Unpack the Security Buffer object - SecurityBuffer *security_obj = ObjectWrap::Unwrap(args.This()); - // Create a Buffer - Buffer *buffer = Buffer::New((char *)security_obj->data, (size_t)security_obj->size); - - // Return the buffer - return scope.Close(buffer->handle_); -} - -void SecurityBuffer::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityBuffer")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer); - - // Set up class - target->Set(String::NewSymbol("SecurityBuffer"), constructor_template->GetFunction()); -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h deleted file mode 100644 index d6a567510..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SECURITY_BUFFER_H -#define SECURITY_BUFFER_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBuffer : public ObjectWrap { - public: - SecurityBuffer(uint32_t security_type, size_t size); - SecurityBuffer(uint32_t security_type, size_t size, void *data); - ~SecurityBuffer(); - - // Internal values - void *data; - size_t size; - uint32_t security_type; - SecBuffer sec_buffer; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static Handle ToBuffer(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static Handle New(const Arguments &args); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js deleted file mode 100644 index 4996163c9..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js +++ /dev/null @@ -1,12 +0,0 @@ -var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; - -// Add some attributes -SecurityBufferNative.VERSION = 0; -SecurityBufferNative.EMPTY = 0; -SecurityBufferNative.DATA = 1; -SecurityBufferNative.TOKEN = 2; -SecurityBufferNative.PADDING = 9; -SecurityBufferNative.STREAM = 10; - -// Export the modified class -exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc deleted file mode 100644 index 560ef50cf..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc +++ /dev/null @@ -1,177 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include "security_buffer_descriptor.h" -#include "security_buffer.h" - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -Persistent SecurityBufferDescriptor::constructor_template; - -SecurityBufferDescriptor::SecurityBufferDescriptor() : ObjectWrap() { -} - -SecurityBufferDescriptor::SecurityBufferDescriptor(Persistent arrayObject) : ObjectWrap() { - SecurityBuffer *security_obj = NULL; - // Safe reference to array - this->arrayObject = arrayObject; - - // Unpack the array and ensure we have a valid descriptor - this->secBufferDesc.cBuffers = arrayObject->Length(); - this->secBufferDesc.ulVersion = SECBUFFER_VERSION; - - if(arrayObject->Length() == 1) { - // Unwrap the buffer - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - // Assign the buffer - this->secBufferDesc.pBuffers = &security_obj->sec_buffer; - } else { - this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; - this->secBufferDesc.cBuffers = arrayObject->Length(); - - // Assign the buffers - for(uint32_t i = 0; i < arrayObject->Length(); i++) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); - this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; - this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; - this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; - } - } -} - -SecurityBufferDescriptor::~SecurityBufferDescriptor() { -} - -size_t SecurityBufferDescriptor::bufferSize() { - SecurityBuffer *security_obj = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - return security_obj->size; - } else { - int bytesToAllocate = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return total size - return bytesToAllocate; - } -} - -char *SecurityBufferDescriptor::toBuffer() { - SecurityBuffer *security_obj = NULL; - char *data = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - data = (char *)malloc(security_obj->size * sizeof(char)); - memcpy(data, security_obj->data, security_obj->size); - } else { - size_t bytesToAllocate = this->bufferSize(); - char *data = (char *)calloc(bytesToAllocate, sizeof(char)); - int offset = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); - offset +=this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return the data - return data; - } - - return data; -} - -Handle SecurityBufferDescriptor::New(const Arguments &args) { - HandleScope scope; - SecurityBufferDescriptor *security_obj; - Persistent arrayObject; - - if(args.Length() != 1) - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(!args[0]->IsInt32() && !args[0]->IsArray()) - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(args[0]->IsArray()) { - Handle array = Handle::Cast(args[0]); - // Iterate over all items and ensure we the right type - for(uint32_t i = 0; i < array->Length(); i++) { - if(!SecurityBuffer::HasInstance(array->Get(i))) { - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - } - } - } - - // We have a single integer - if(args[0]->IsInt32()) { - // Create new SecurityBuffer instance - Local argv[] = {Int32::New(0x02), args[0]}; - Handle security_buffer = SecurityBuffer::constructor_template->GetFunction()->NewInstance(2, argv); - // Create a new array - Local array = Array::New(1); - // Set the first value - array->Set(0, security_buffer); - // Create persistent handle - arrayObject = Persistent::New(array); - // Create descriptor - security_obj = new SecurityBufferDescriptor(arrayObject); - } else { - arrayObject = Persistent::New(Handle::Cast(args[0])); - security_obj = new SecurityBufferDescriptor(arrayObject); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityBufferDescriptor::ToBuffer(const Arguments &args) { - HandleScope scope; - - // Unpack the Security Buffer object - SecurityBufferDescriptor *security_obj = ObjectWrap::Unwrap(args.This()); - - // Get the buffer - char *buffer_data = security_obj->toBuffer(); - size_t buffer_size = security_obj->bufferSize(); - - // Create a Buffer - Buffer *buffer = Buffer::New(buffer_data, buffer_size); - - // Return the buffer - return scope.Close(buffer->handle_); -} - -void SecurityBufferDescriptor::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityBufferDescriptor")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer); - - target->Set(String::NewSymbol("SecurityBufferDescriptor"), constructor_template->GetFunction()); -} diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h deleted file mode 100644 index 858863259..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef SECURITY_BUFFER_DESCRIPTOR_H -#define SECURITY_BUFFER_DESCRIPTOR_H - -#include -#include -#include - -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBufferDescriptor : public ObjectWrap { - public: - Persistent arrayObject; - SecBufferDesc secBufferDesc; - - SecurityBufferDescriptor(); - SecurityBufferDescriptor(Persistent arrayObject); - ~SecurityBufferDescriptor(); - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - char *toBuffer(); - size_t bufferSize(); - - // Functions available from V8 - static void Initialize(Handle target); - static Handle ToBuffer(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static Handle New(const Arguments &args); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js deleted file mode 100644 index 9421392ea..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; -// Export the modified class -exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc deleted file mode 100644 index 8c3691a7e..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc +++ /dev/null @@ -1,1211 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_context.h" -#include "security_buffer_descriptor.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -static Handle VExceptionErrNo(const char *msg, const int errorNumber) { - HandleScope scope; - - Local err = Exception::Error(String::New(msg)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(errorNumber)); - return ThrowException(err); -}; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -static void After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - free(worker->parameters); - delete worker; -} - -Persistent SecurityContext::constructor_template; - -SecurityContext::SecurityContext() : ObjectWrap() { -} - -SecurityContext::~SecurityContext() { - if(this->hasContext) { - _sspi_DeleteSecurityContext(&this->m_Context); - } -} - -Handle SecurityContext::New(const Arguments &args) { - HandleScope scope; - - PSecurityFunctionTable pSecurityInterface = NULL; - DWORD dwNumOfPkgs; - SECURITY_STATUS status; - - // Create code object - SecurityContext *security_obj = new SecurityContext(); - // Get security table interface - pSecurityInterface = _ssip_InitSecurityInterface(); - // Call the security interface - status = (*pSecurityInterface->EnumerateSecurityPackages)( - &dwNumOfPkgs, - &security_obj->m_PkgInfo); - if(status != SEC_E_OK) { - printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); - return VException("Failed in retrieving security packages"); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityContext::InitializeContextSync(const Arguments &args) { - HandleScope scope; - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - BYTE *out_bound_data_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - // Status of operation - SECURITY_STATUS status; - - // We need 3 parameters - if(args.Length() != 3) - return VException("Initialize must be called with either [credential:SecurityCredential, servicePrincipalName:string, input:string]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return VException("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create Security context instance - Local security_context_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = security_context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(input->Utf8Length() > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = decoded_input_str_length; - ib.pvBuffer = decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &security_credentials->m_Credentials - , NULL - , const_cast(service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , input->Utf8Length() > 0 ? &ibd : NULL - , 0 - , &security_context->m_Context - , &obd - , &security_context->CtxtAttr - , &security_context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - security_context->hasContext = true; - security_context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - // Return security context - return scope.Close(security_context_value); -} - -// -// Async InitializeContext -// -typedef struct SecurityContextStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStaticInitializeCall; - -static void _initializeContext(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - BYTE *out_bound_data_str = NULL; - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &call->context->security_credentials->m_Credentials - , NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length > 0 ? &ibd : NULL - , 0 - , &call->context->m_Context - , &obd - , &call->context->CtxtAttr - , &call->context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - call->context->hasContext = true; - call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - - // Set the context - worker->return_code = status; - worker->return_value = call->context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContext(Worker *worker) { - HandleScope scope; - - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::InitializeContext(const Arguments &args) { - HandleScope scope; - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - - // We need 3 parameters - if(args.Length() != 4) - return VException("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return VException("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a callback - if(!args[3]->IsFunction()) - return VException("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free original allocation - free(input_str); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create Security context instance - Local security_context_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Build the call function - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[3]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _initializeContext; - worker->mapper = _map_initializeContext; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value - return scope.Close(Undefined()); -} - -Handle SecurityContext::PayloadGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(info.Holder()); - // Return the low bits - return scope.Close(String::New(context->payload)); -} - -Handle SecurityContext::HasContextGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(info.Holder()); - // Return the low bits - return scope.Close(Boolean::New(context->hasContext)); -} - -// -// Async InitializeContextStep -// -typedef struct SecurityContextStepStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStepStaticInitializeCall; - -static void _initializeContextStep(Worker *worker) { - // Outbound data array - BYTE *out_bound_data_str = NULL; - // Status of operation - SECURITY_STATUS status; - // Unpack data - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; - SecurityContext *context = call->context; - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &context->security_credentials->m_Credentials - , context->hasContext == true ? &context->m_Context : NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length ? &ibd : NULL - , 0 - , &context->m_Context - , &obd - , &context->CtxtAttr - , &context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(context->payload != NULL) free(context->payload); - context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContextStep(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::InitalizeStep(const Arguments &args) { - HandleScope scope; - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - - // We need 3 parameters - if(args.Length() != 3) - return VException("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return VException("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsFunction()) - return VException("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free input string - free(input_str); - } - - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Create call structure - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _initializeContextStep; - worker->mapper = _map_initializeContextStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::InitalizeStepSync(const Arguments &args) { - HandleScope scope; - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - BYTE *out_bound_data_str = NULL; - int decoded_input_str_length = NULL; - // Status of operation - SECURITY_STATUS status; - - // We need 3 parameters - if(args.Length() != 2) - return VException("Initialize must be called with [servicePrincipalName:string, input:string]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return VException("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - } - - // Unpack the long object - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - SecurityCredentials *security_credentials = security_context->security_credentials; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = security_context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(input->Utf8Length() > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = decoded_input_str_length; - ib.pvBuffer = decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &security_credentials->m_Credentials - , security_context->hasContext == true ? &security_context->m_Context : NULL - , const_cast(service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , input->Utf8Length() > 0 ? &ibd : NULL - , 0 - , &security_context->m_Context - , &obd - , &security_context->CtxtAttr - , &security_context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(security_context->payload != NULL) free(security_context->payload); - security_context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async EncryptMessage -// -typedef struct SecurityContextEncryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; - unsigned long flags; -} SecurityContextEncryptMessageCall; - -static void _encryptMessage(Worker *worker) { - SECURITY_STATUS status; - // Unpack call - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; - // Unpack the security context - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_EncryptMessage( - &context->m_Context - , call->flags - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set result - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_encryptMessage(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::EncryptMessage(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 3) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[1]->IsUint32()) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[2]->IsFunction()) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create call structure - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - call->flags = (unsigned long)args[1]->ToInteger()->Value(); - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _encryptMessage; - worker->mapper = _map_encryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::EncryptMessageSync(const Arguments &args) { - HandleScope scope; - SECURITY_STATUS status; - - if(args.Length() != 2) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - if(!args[1]->IsUint32()) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Let's execute encryption - status = _sspi_EncryptMessage( - &security_context->m_Context - , (unsigned long)args[1]->ToInteger()->Value() - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(security_context->payload != NULL) free(security_context->payload); - // Save the payload - security_context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async DecryptMessage -// -typedef struct SecurityContextDecryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; -} SecurityContextDecryptMessageCall; - -static void _decryptMessage(Worker *worker) { - unsigned long quality = 0; - SECURITY_STATUS status; - - // Unpack parameters - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_DecryptMessage( - &context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set return values - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_decryptMessage(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::DecryptMessage(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 2) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!args[1]->IsFunction()) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create call structure - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _decryptMessage; - worker->mapper = _map_decryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::DecryptMessageSync(const Arguments &args) { - HandleScope scope; - unsigned long quality = 0; - SECURITY_STATUS status; - - if(args.Length() != 1) - return VException("DecryptMessageSync takes an instance of SecurityBufferDescriptor"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("DecryptMessageSync takes an instance of SecurityBufferDescriptor"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Let's execute encryption - status = _sspi_DecryptMessage( - &security_context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(security_context->payload != NULL) free(security_context->payload); - // Save the payload - security_context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async QueryContextAttributes -// -typedef struct SecurityContextQueryContextAttributesCall { - SecurityContext *context; - uint32_t attribute; -} SecurityContextQueryContextAttributesCall; - -static void _queryContextAttributes(Worker *worker) { - SECURITY_STATUS status; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - - // Allocate some space - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &call->context->m_Context, - call->attribute, - sizes - ); - - if(status == SEC_E_OK) { - worker->return_code = status; - worker->return_value = sizes; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_queryContextAttributes(Worker *worker) { - HandleScope scope; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - // Unpack the attribute - uint32_t attribute = call->attribute; - - // Convert data - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; - // Create object - Local value = Object::New(); - value->Set(String::New("maxToken"), Integer::New(sizes->cbMaxToken)); - value->Set(String::New("maxSignature"), Integer::New(sizes->cbMaxSignature)); - value->Set(String::New("blockSize"), Integer::New(sizes->cbBlockSize)); - value->Set(String::New("securityTrailer"), Integer::New(sizes->cbSecurityTrailer)); - return scope.Close(value); - } - - // Return the value - return scope.Close(Null()); -} - -Handle SecurityContext::QueryContextAttributes(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 2) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier and a callback function"); - if(!args[0]->IsInt32()) - return VException("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!args[1]->IsFunction()) - return VException("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the int value - uint32_t attribute = args[0]->ToInt32()->Value(); - - // Check that we have a supported attribute - if(attribute != SECPKG_ATTR_SIZES) - return VException("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Create call structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); - call->attribute = attribute; - call->context = security_context; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _queryContextAttributes; - worker->mapper = _map_queryContextAttributes; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::QueryContextAttributesSync(const Arguments &args) { - HandleScope scope; - SECURITY_STATUS status; - - if(args.Length() != 1) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier"); - if(!args[0]->IsInt32()) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - uint32_t attribute = args[0]->ToInt32()->Value(); - - if(attribute != SECPKG_ATTR_SIZES) - return VException("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Check what attribute we are asking for - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes sizes; - - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &security_context->m_Context, - attribute, - &sizes - ); - - if(status == SEC_E_OK) { - Local value = Object::New(); - value->Set(String::New("maxToken"), Integer::New(sizes.cbMaxToken)); - value->Set(String::New("maxSignature"), Integer::New(sizes.cbMaxSignature)); - value->Set(String::New("blockSize"), Integer::New(sizes.cbBlockSize)); - value->Set(String::New("securityTrailer"), Integer::New(sizes.cbSecurityTrailer)); - return scope.Close(value); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - } - - return scope.Close(Null()); -} - -void SecurityContext::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityContext")); - - // Class methods - NODE_SET_METHOD(constructor_template, "initializeSync", InitializeContextSync); - NODE_SET_METHOD(constructor_template, "initialize", InitializeContext); - - // Set up method for the instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "initializeSync", InitalizeStepSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "initialize", InitalizeStep); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "decryptMessageSync", DecryptMessageSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "decryptMessage", DecryptMessage); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "queryContextAttributesSync", QueryContextAttributesSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "queryContextAttributes", QueryContextAttributes); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "encryptMessageSync", EncryptMessageSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "encryptMessage", EncryptMessage); - - // Getters for correct serialization of the object - constructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol("payload"), PayloadGetter); - // Getters for correct serialization of the object - constructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol("hasContext"), HasContextGetter); - - // Set template class name - target->Set(String::NewSymbol("SecurityContext"), constructor_template->GetFunction()); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - } - - return pszName; -} - diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h deleted file mode 100644 index b0059e39e..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef SECURITY_CONTEXT_H -#define SECURITY_CONTEXT_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include "security_credentials.h" -#include "../worker.h" - -extern "C" { - #include "../kerberos_sspi.h" - #include "../base64.h" -} - -using namespace v8; -using namespace node; - -class SecurityContext : public ObjectWrap { - public: - SecurityContext(); - ~SecurityContext(); - - // Security info package - PSecPkgInfo m_PkgInfo; - // Do we have a context - bool hasContext; - // Reference to security credentials - SecurityCredentials *security_credentials; - // Security context - CtxtHandle m_Context; - // Attributes - DWORD CtxtAttr; - // Expiry time for ticket - TimeStamp Expiration; - // Payload - char *payload; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - - static Handle InitializeContext(const Arguments &args); - static Handle InitializeContextSync(const Arguments &args); - - static Handle InitalizeStep(const Arguments &args); - static Handle InitalizeStepSync(const Arguments &args); - - static Handle DecryptMessage(const Arguments &args); - static Handle DecryptMessageSync(const Arguments &args); - - static Handle QueryContextAttributesSync(const Arguments &args); - static Handle QueryContextAttributes(const Arguments &args); - - static Handle EncryptMessageSync(const Arguments &args); - static Handle EncryptMessage(const Arguments &args); - - // Payload getter - static Handle PayloadGetter(Local property, const AccessorInfo& info); - // hasContext getter - static Handle HasContextGetter(Local property, const AccessorInfo& info); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static Handle New(const Arguments &args); - // // Handles the uv calls - // static void Process(uv_work_t* work_req); - // // Called after work is done - // static void After(uv_work_t* work_req); -}; - -#endif diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js deleted file mode 100644 index ef04e9274..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; -// Export the modified class -exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc deleted file mode 100644 index 025238b7c..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc +++ /dev/null @@ -1,468 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_credentials.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -static Handle VExceptionErrNo(const char *msg, const int errorNumber) { - HandleScope scope; - - Local err = Exception::Error(String::New(msg)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(errorNumber)); - return ThrowException(err); -}; - -Persistent SecurityCredentials::constructor_template; - -SecurityCredentials::SecurityCredentials() : ObjectWrap() { -} - -SecurityCredentials::~SecurityCredentials() { -} - -Handle SecurityCredentials::New(const Arguments &args) { - HandleScope scope; - - // Create security credentials instance - SecurityCredentials *security_credentials = new SecurityCredentials(); - // Wrap it - security_credentials->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityCredentials::AquireSync(const Arguments &args) { - HandleScope scope; - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Status of operation - SECURITY_STATUS status; - - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(!args[0]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(!args[1]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(args.Length() == 3 && !args[2]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull())) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if(args.Length() == 4 && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Create Security instance - Local security_credentials_value = constructor_template->GetFunction()->NewInstance(); - - // Unwrap the credentials - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(security_credentials_value); - - // If we have domain string - if(domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(username_str); - - // If we have a password string - if(password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - package_str, - SECPKG_CRED_OUTBOUND, - NULL, - password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - // Make object persistent - Persistent persistent = Persistent::New(security_credentials_value); - // Return the object - return scope.Close(persistent); -} - -// Call structs -typedef struct SecurityCredentialCall { - char *package_str; - char *username_str; - char *password_str; - char *domain_str; - SecurityCredentials *credentials; -} SecurityCredentialCall; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authSSPIAquire(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - - // Unpack data - SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; - - // Unwrap the credentials - SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; - - // If we have domain string - if(call->domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); - - // If we have a password string - if(call->password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - call->package_str, - SECPKG_CRED_OUTBOUND, - NULL, - call->password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } else { - worker->return_code = status; - worker->return_value = security_credentials; - } - - // Free up parameter structure - if(call->package_str != NULL) free(call->package_str); - if(call->domain_str != NULL) free(call->domain_str); - if(call->password_str != NULL) free(call->password_str); - if(call->username_str != NULL) free(call->username_str); - free(call); -} - -static Handle _map_authSSPIAquire(Worker *worker) { - HandleScope scope; - - // Unpack the credentials - SecurityCredentials *security_credentials = (SecurityCredentials *)worker->return_value; - // Make object persistent - Persistent persistent = Persistent::New(security_credentials->handle_); - // Return the object - return scope.Close(persistent); -} - -Handle SecurityCredentials::Aquire(const Arguments &args) { - HandleScope scope; - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4 && args.Length() != 5) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[0]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[1]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 3 && (!args[2]->IsString() && !args[2]->IsFunction())) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull()) && !args[3]->IsFunction()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 5 && !args[4]->IsFunction()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - Local callback; - - // Figure out which parameter is the callback - if(args.Length() == 5) { - callback = Local::Cast(args[4]); - } else if(args.Length() == 4) { - callback = Local::Cast(args[3]); - } else if(args.Length() == 3) { - callback = Local::Cast(args[2]); - } - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4 || args.Length() == 5) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if((args.Length() == 4 || args.Length() == 5) && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Create reference object - Local security_credentials_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap object - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(security_credentials_value); - - // Allocate call structure - SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); - call->domain_str = domain_str; - call->package_str = package_str; - call->password_str = password_str; - call->username_str = username_str; - call->credentials = security_credentials; - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authSSPIAquire; - worker->mapper = _map_authSSPIAquire; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); - - // Return the undefined value - return scope.Close(Undefined()); -} - -void SecurityCredentials::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityCredentials")); - - // Class methods - NODE_SET_METHOD(constructor_template, "aquireSync", AquireSync); - NODE_SET_METHOD(constructor_template, "aquire", Aquire); - - // Set the class on the target module - target->Set(String::NewSymbol("SecurityCredentials"), constructor_template->GetFunction()); - - // Attempt to load the security.dll library - load_library(); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - - } - - return pszName; -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void SecurityCredentials::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void SecurityCredentials::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - delete worker; -} - diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h deleted file mode 100644 index 10b3edaa3..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef SECURITY_CREDENTIALS_H -#define SECURITY_CREDENTIALS_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" -} - -// SEC_WINNT_AUTH_IDENTITY makes it unusually hard -// to compile for both Unicode and ansi, so I use this macro: -#ifdef _UNICODE -#define USTR(str) (str) -#else -#define USTR(str) ((unsigned char*)(str)) -#endif - -using namespace v8; -using namespace node; - -class SecurityCredentials : public ObjectWrap { - public: - SecurityCredentials(); - ~SecurityCredentials(); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static Handle AquireSync(const Arguments &args); - static Handle Aquire(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static Handle New(const Arguments &args); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js deleted file mode 100644 index 4215c9274..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js +++ /dev/null @@ -1,22 +0,0 @@ -var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; - -// Add simple kebros helper -SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { - if(typeof password == 'function') { - callback = password; - password = null; - } else if(typeof domain == 'function') { - callback = domain; - domain = null; - } - - // We are going to use the async version - if(typeof callback == 'function') { - return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); - } else { - return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); - } -} - -// Export the modified class -exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/worker.cc b/node_modules/mongodb/node_modules/kerberos/lib/worker.cc deleted file mode 100644 index e7a472f67..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/lib/worker.h b/node_modules/mongodb/node_modules/kerberos/lib/worker.h deleted file mode 100644 index c5f86f521..000000000 --- a/node_modules/mongodb/node_modules/kerberos/lib/worker.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - v8::Persistent callback; - // // Arguments - // v8::Persistent arguments; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/node_modules/mongodb/node_modules/kerberos/package.json b/node_modules/mongodb/node_modules/kerberos/package.json deleted file mode 100644 index b29cfc2c8..000000000 --- a/node_modules/mongodb/node_modules/kerberos/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "kerberos", - "version": "0.0.3", - "description": "Kerberos library for Node.js", - "main": "index.js", - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test" - }, - "repository": { - "type": "git", - "url": "https://github.com/christkv/kerberos.git" - }, - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "devDependencies": { - "nodeunit": "latest" - }, - "author": { - "name": "Christian Amor Kvalheim" - }, - "license": "Apache 2.0", - "readmeFilename": "README.md", - "gitHead": "bb01d4fe322e022999aca19da564e7d9db59a8ed", - "readme": "kerberos\n========\n\nKerberos library for node.js", - "bugs": { - "url": "https://github.com/christkv/kerberos/issues" - }, - "homepage": "https://github.com/christkv/kerberos", - "_id": "kerberos@0.0.3", - "dist": { - "shasum": "53d6ed947fa0d8306a67680dffb4bd32a51e3839" - }, - "_from": "kerberos@0.0.3", - "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.3.tgz" -} diff --git a/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js b/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js deleted file mode 100644 index a06c5fdfe..000000000 --- a/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js +++ /dev/null @@ -1,34 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos object'] = function(test) { - var Kerberos = require('../lib/kerberos.js').Kerberos; - var kerberos = new Kerberos(); - // console.dir(kerberos) - - // Initiate kerberos client - kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - console.log("===================================== authGSSClientInit") - test.equal(null, err); - test.ok(context != null && typeof context == 'object'); - // console.log("===================================== authGSSClientInit") - console.dir(err) - console.dir(context) - // console.dir(typeof result) - - // Perform the first step - kerberos.authGSSClientStep(context, function(err, result) { - console.log("===================================== authGSSClientStep") - console.dir(err) - console.dir(result) - console.dir(context) - - test.done(); - }); - }); -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js b/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js deleted file mode 100644 index d2f704638..000000000 --- a/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js +++ /dev/null @@ -1,19 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos win32 object'] = function(test) { - var KerberosNative = require('../build/Release/kerberos').Kerberos; - // console.dir(KerberosNative) - var kerberos = new KerberosNative(); - console.log("=========================================== 0") - console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); - console.log("=========================================== 1") - console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); - console.log("=========================================== 2") - test.done(); -} diff --git a/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js deleted file mode 100644 index 3531b6bc2..000000000 --- a/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js +++ /dev/null @@ -1,41 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer Descriptor'] = function(test) { - var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // Create descriptor with single Buffer - var securityDescriptor = new SecurityBufferDescriptor(100); - try { - // Fail to work due to no valid Security Buffer - securityDescriptor = new SecurityBufferDescriptor(["hello"]); - test.ok(false); - } catch(err){} - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - // Should correctly return a buffer - var result = securityDescriptor.toBuffer(); - test.equal(100, result.length); - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - var result = securityDescriptor.toBuffer(); - test.equal("hello world", result.toString()); - - // Test passing in more than one Buffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - var result = securityDescriptor.toBuffer(); - test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js b/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js deleted file mode 100644 index b52b9598b..000000000 --- a/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js +++ /dev/null @@ -1,22 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer'] = function(test) { - var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - // Create empty buffer - var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - var buffer = securityBuffer.toBuffer(); - test.equal(100, buffer.length); - - // Access data passed in - var allocated_buffer = new Buffer(256); - securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); - buffer = securityBuffer.toBuffer(); - test.deepEqual(allocated_buffer, buffer); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js b/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js deleted file mode 100644 index 775818007..000000000 --- a/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js +++ /dev/null @@ -1,55 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a set of security credentials'] = function(test) { - var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; - - // Aquire some credentials - try { - var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); - } catch(err) { - console.dir(err) - test.ok(false); - } - - - - // console.dir(SecurityCredentials); - - // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // // Create descriptor with single Buffer - // var securityDescriptor = new SecurityBufferDescriptor(100); - // try { - // // Fail to work due to no valid Security Buffer - // securityDescriptor = new SecurityBufferDescriptor(["hello"]); - // test.ok(false); - // } catch(err){} - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // // Should correctly return a buffer - // var result = securityDescriptor.toBuffer(); - // test.equal(100, result.length); - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello world", result.toString()); - - // // Test passing in more than one Buffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/package.json b/node_modules/mongodb/package.json deleted file mode 100644 index 4c4244e9f..000000000 --- a/node_modules/mongodb/package.json +++ /dev/null @@ -1,227 +0,0 @@ -{ - "name": "mongodb", - "description": "A node.js driver for MongoDB", - "keywords": [ - "mongodb", - "mongo", - "driver", - "db" - ], - "version": "1.3.23", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [ - { - "name": "Aaron Heckmann" - }, - { - "name": "Christoph Pojer" - }, - { - "name": "Pau Ramon Revilla" - }, - { - "name": "Nathan White" - }, - { - "name": "Emmerman" - }, - { - "name": "Seth LaForge" - }, - { - "name": "Boris Filipov" - }, - { - "name": "Stefan Schärmeli" - }, - { - "name": "Tedde Lundgren" - }, - { - "name": "renctan" - }, - { - "name": "Sergey Ukustov" - }, - { - "name": "Ciaran Jessup" - }, - { - "name": "kuno" - }, - { - "name": "srimonti" - }, - { - "name": "Erik Abele" - }, - { - "name": "Pratik Daga" - }, - { - "name": "Slobodan Utvic" - }, - { - "name": "Kristina Chodorow" - }, - { - "name": "Yonathan Randolph" - }, - { - "name": "Brian Noguchi" - }, - { - "name": "Sam Epstein" - }, - { - "name": "James Harrison Fisher" - }, - { - "name": "Vladimir Dronnikov" - }, - { - "name": "Ben Hockey" - }, - { - "name": "Henrik Johansson" - }, - { - "name": "Simon Weare" - }, - { - "name": "Alex Gorbatchev" - }, - { - "name": "Shimon Doodkin" - }, - { - "name": "Kyle Mueller" - }, - { - "name": "Eran Hammer-Lahav" - }, - { - "name": "Marcin Ciszak" - }, - { - "name": "François de Metz" - }, - { - "name": "Vinay Pulim" - }, - { - "name": "nstielau" - }, - { - "name": "Adam Wiggins" - }, - { - "name": "entrinzikyl" - }, - { - "name": "Jeremy Selier" - }, - { - "name": "Ian Millington" - }, - { - "name": "Public Keating" - }, - { - "name": "andrewjstone" - }, - { - "name": "Christopher Stott" - }, - { - "name": "Corey Jewett" - }, - { - "name": "brettkiefer" - }, - { - "name": "Rob Holland" - }, - { - "name": "Senmiao Liu" - }, - { - "name": "heroic" - }, - { - "name": "gitfy" - }, - { - "name": "Andrew Stone" - }, - { - "name": "John Le Drew" - }, - { - "name": "Lucasfilm Singapore" - }, - { - "name": "Roman Shtylman" - }, - { - "name": "Matt Self" - }, - { - "name": "Gregory Langlais" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/mongodb/node-mongodb-native.git" - }, - "bugs": { - "url": "http://github.com/mongodb/node-mongodb-native/issues" - }, - "dependencies": { - "bson": "0.2.5", - "kerberos": "0.0.3" - }, - "devDependencies": { - "dox": "0.4.4", - "uglify-js": "1.2.5", - "ejs": "0.6.1", - "request": "2.12.0", - "nodeunit": "0.7.4", - "markdown": "0.3.1", - "gleak": "0.2.3", - "step": "0.0.5", - "async": "0.1.22", - "integra": "latest", - "optimist": "latest" - }, - "optionalDependencies": { - "kerberos": "0.0.3" - }, - "config": { - "native": false - }, - "main": "./lib/mongodb/index", - "homepage": "http://mongodb.github.com/node-mongodb-native/", - "directories": { - "lib": "./lib/mongodb" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "test": "make test_functional" - }, - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "readme": "## MongoDB Node.JS Driver\n \n| what | where |\n|---------------|------------------------------------------------|\n| documentation | http://mongodb.github.io/node-mongodb-native/ |\n| apidoc | http://mongodb.github.io/node-mongodb-native/ |\n| source | https://github.com/mongodb/node-mongodb-native |\n| mongodb | http://www.mongodb.org/ |\n\n### Bugs / Feature Requests\n\nThink you’ve found a bug? Want to see a new feature in PyMongo? Please open a\ncase in our issue management tool, JIRA:\n\n- Create an account and login .\n- Navigate to the NODE project .\n- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it.\n\nBug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the\nCore Server (i.e. SERVER) project are **public**.\n\n### Questions and Bug Reports\n\n * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native\n * jira: http://jira.mongodb.org/\n\n### Change Log\n\nhttp://jira.mongodb.org/browse/NODE\n\n## Install\n\nTo install the most recent release from npm, run:\n\n npm install mongodb\n\nThat may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version)\n\nTo install the latest from the repository, run::\n\n npm install path/to/node-mongodb-native\n\n## Live Examples\n\n\n## Introduction\n\nThis is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/.\n\nA simple example of inserting a document.\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format;\n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n var collection = db.collection('test_insert');\n collection.insert({a:2}, function(err, docs) {\n \n collection.count(function(err, count) {\n console.log(format(\"count = %s\", count));\n });\n\n // Locate all the entries using find\n collection.find().toArray(function(err, results) {\n console.dir(results);\n // Let's close the db\n db.close();\n });\n });\n })\n```\n\n## Data types\n\nTo store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code).\n\nIn particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example:\n\n```javascript\n // Get the objectID type\n var ObjectID = require('mongodb').ObjectID;\n\n var idString = '4e4e1638c85e808431000003';\n collection.findOne({_id: new ObjectID(idString)}, console.log) // ok\n collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined\n```\n\nHere are the constructors the non-Javascript BSON primitive types:\n\n```javascript\n // Fetch the library\n var mongo = require('mongodb');\n // Create new instances of BSON types\n new mongo.Long(numberString)\n new mongo.ObjectID(hexString)\n new mongo.Timestamp() // the actual unique number is generated on insert.\n new mongo.DBRef(collectionName, id, dbName)\n new mongo.Binary(buffer) // takes a string or Buffer\n new mongo.Code(code, [context])\n new mongo.Symbol(string)\n new mongo.MinKey()\n new mongo.MaxKey()\n new mongo.Double(number)\t// Force double storage\n```\n\n### The C/C++ bson parser/serializer\n\nIf you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below\n\n```javascript\n // using native_parser:\n MongoClient.connect('mongodb://127.0.0.1:27017/test'\n , {db: {native_parser: true}}, function(err, db) {})\n```\n\nThe C++ parser uses the js objects both for serialization and deserialization.\n\n## GitHub information\n\nThe source code is available at http://github.com/mongodb/node-mongodb-native.\nYou can either clone the repository or download a tarball of the latest release.\n\nOnce you have the source you can test the driver by running\n\n $ make test\n\nin the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.\n\n## Examples\n\nFor examples look in the examples/ directory. You can execute the examples using node.\n\n $ cd examples\n $ node queries.js\n\n## GridStore\n\nThe GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.\n\nFor more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md)\n\n## Replicasets\n\nFor more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/)\n\n### Primary Key Factories\n\nDefining your own primary key factory allows you to generate your own series of id's\n(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long \"string\".\n\nSimple example below\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n // Custom factory (need to provide a 12 byte array);\n CustomPKFactory = function() {}\n CustomPKFactory.prototype = new Object();\n CustomPKFactory.createPk = function() {\n return new ObjectID(\"aaaaaaaaaaaa\");\n }\n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n db.dropDatabase(function(err, done) {\n \n db.createCollection('test_custom_key', function(err, collection) {\n \n collection.insert({'a':1}, function(err, docs) {\n \n collection.find({'_id':new ObjectID(\"aaaaaaaaaaaa\")}).toArray(function(err, items) {\n console.dir(items);\n // Let's close the db\n db.close();\n });\n });\n });\n });\n });\n```\n\n## Documentation\n\nIf this document doesn't answer your questions, see the source of\n[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js)\nor [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js),\nor the documentation at MongoDB for query and update formats.\n\n### Find\n\nThe find method is actually a factory method to create\nCursor objects. A Cursor lazily uses the connection the first time\nyou call `nextObject`, `each`, or `toArray`.\n\nThe basic operation on a cursor is the `nextObject` method\nthat fetches the next matching document from the database. The convenience\nmethods `each` and `toArray` call `nextObject` until the cursor is exhausted.\n\nSignatures:\n\n```javascript\n var cursor = collection.find(query, [fields], options);\n cursor.sort(fields).limit(n).skip(m).\n\n cursor.nextObject(function(err, doc) {});\n cursor.each(function(err, doc) {});\n cursor.toArray(function(err, docs) {});\n\n cursor.rewind() // reset the cursor to its initial state.\n```\n\nUseful chainable methods of cursor. These can optionally be options of `find` instead of method calls:\n\n * `.limit(n).skip(m)` to control paging.\n * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes:\n * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2.\n * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above\n * `.sort([['field1', 'desc'], 'field2'])` same as above\n * `.sort('field1')` ascending by field1\n\nOther options of `find`:\n\n* `fields` the fields to fetch (to avoid transferring the entire document)\n* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors).\n* `batchSize` The number of the subset of results to request the database\nto return for every request. This should initially be greater than 1 otherwise\nthe database will automatically close the cursor. The batch size can be set to 1\nwith `batchSize(n, function(err){})` after performing the initial query to the database.\n* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint).\n* `explain` turns this into an explain query. You can also call\n`explain()` on any cursor to fetch the explanation.\n* `snapshot` prevents documents that are updated while the query is active\nfrom being returned multiple times. See more\n[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database).\n* `timeout` if false, asks MongoDb not to time out this cursor after an\ninactivity period.\n\nFor information on how to create queries, see the\n[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n var collection = db\n .collection('test')\n .find({})\n .limit(10)\n .toArray(function(err, docs) {\n console.dir(docs);\n });\n });\n```\n\n### Insert\n\nSignature:\n\n```javascript\n collection.insert(docs, options, [callback]);\n```\n\nwhere `docs` can be a single document or an array of documents.\n\nUseful options:\n\n* `safe:true` Should always set if you have a callback.\n\nSee also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n \n db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) {\n if (err) console.warn(err.message);\n if (err && err.message.indexOf('E11000 ') !== -1) {\n // this _id was already inserted in the database\n }\n });\n });\n```\n\nNote that there's no reason to pass a callback to the insert or update commands\nunless you use the `safe:true` option. If you don't specify `safe:true`, then\nyour callback will be called immediately.\n\n### Update: update and insert (upsert)\n\nThe update operation will update the first document that matches your query\n(or all documents that match if you use `multi:true`).\nIf `safe:true`, `upsert` is not set, and no documents match, your callback will return 0 documents updated.\n\nSee the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for\nthe modifier (`$inc`, `$set`, `$push`, etc.) formats.\n\nSignature:\n\n```javascript\n collection.update(criteria, objNew, options, [callback]);\n```\n\nUseful options:\n\n* `safe:true` Should always set if you have a callback.\n* `multi:true` If set, all matching documents are updated, not just the first.\n* `upsert:true` Atomically inserts the document if no documents matched.\n\nExample for `update`:\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) {\n if (err) console.warn(err.message);\n else console.log('successfully updated');\n });\n });\n```\n\n### Find and modify\n\n`findAndModify` is like `update`, but it also gives the updated document to\nyour callback. But there are a few key differences between findAndModify and\nupdate:\n\n 1. The signatures differ.\n 2. You can only findAndModify a single item, not multiple items.\n\nSignature:\n\n```javascript\n collection.findAndModify(query, sort, update, options, callback)\n```\n\nThe sort parameter is used to specify which object to operate on, if more than\none document matches. It takes the same format as the cursor sort (see\nConnection.find above).\n\nSee the\n[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)\nfor more details.\n\nUseful options:\n\n* `remove:true` set to a true to remove the object before returning\n* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove.\n* `upsert:true` Atomically inserts the document if no documents matched.\n\nExample for `findAndModify`:\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) {\n if (err) console.warn(err.message);\n else console.dir(object); // undefined if no matching object exists.\n });\n });\n```\n\n### Save\n\nThe `save` method is a shorthand for upsert if the document contains an\n`_id`, or an insert if there is no `_id`.\n\n## Release Notes\n\nSee HISTORY\n\n## Credits\n\n1. [10gen](http://github.com/mongodb/mongo-ruby-driver/)\n2. [Google Closure Library](http://code.google.com/closure/library/)\n3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser)\n\n## Contributors\n\nAaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy\n\n## License\n\n Copyright 2009 - 2013 MongoDb Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n", - "readmeFilename": "Readme.md", - "_id": "mongodb@1.3.23", - "_from": "mongodb@*" -} diff --git a/node_modules/mongodb/t.js b/node_modules/mongodb/t.js deleted file mode 100644 index bbfd5cf7e..000000000 --- a/node_modules/mongodb/t.js +++ /dev/null @@ -1,99 +0,0 @@ -// var MongoClient = require('./lib/mongodb').MongoClient; - -// MongoClient.connect("mongodb://localhost:27017/test", function(err, db) { - -// var t = db.collection('t'); -// var cursor = t.find() -// console.log(cursor.constructor.name) -// db.close(); -// }); - -var mongodb = require('./lib/mongodb'), - async = require('async'), - ObjectId = mongodb.ObjectID, - ReplicaSetManager = require('./test/tools/replica_set_manager').ReplicaSetManager, - dbUrl = 'mongodb://127.0.0.1:30000/mydb?replicaSet=rs0', - dbOptions = { - db: { - w: 1 - }, - server: { - auto_reconnect: true, - poolSize: 5 - } - }, - callbacksCalled = {}; - -function runTest(db, col) { - var i = 0; - - function next(cursor, id) { - cursor.nextObject(function (err, doc) { - if (err) { - console.log('nextObject', id, 'error:', err); - } else { - if (doc) { - console.log('nextObject', id, 'found:', doc); - } else { - console.log('nextObject', id, 'no document'); - } - } - - if (callbacksCalled[id]) { - console.log('callback', id, 'called twice'); - console.log('dumping the cursor nextObject was called on:'); - console.log(cursor); - process.exit(1); - } - - callbacksCalled[id] = true; - - if (cursor.isClosed()) { - console.log('cursor closed'); - // restart - i += 10; - start(); - } else { - i += 1; - next(cursor, i); - } - }); - } - - function start() { - var cursor = col.find({}, {tailable: true, numberOfRetries: -1}). - sort({$natural: 1}); - next(cursor, i); - } - - start(); -} - -RS = new ReplicaSetManager({name:"rs0", retries:120, secondary_count:0, passive_count:0, arbiter_count:1}); -RS.startSet(true, function(err, result) { - if(err != null) throw err; - - mongodb.Db.connect(dbUrl, dbOptions, function (err, db) { - if (err) { - console.log(err); - process.exit(1); - } - - console.log('database connected'); - - db.on('error', function (err) { - console.log('db.on(\'error\'):', err); - }); - - db.createCollection('testCapped', {capped: true, w: 1, size: 100000, max: 20}, function (err, col) { - if (err) { - console.log(err); - process.exit(1); - } - - console.log('collection created'); - - runTest(db, col); - }); - }); -}) \ No newline at end of file diff --git a/node_modules/mongoose/.npmignore b/node_modules/mongoose/.npmignore deleted file mode 100644 index df5ea94c1..000000000 --- a/node_modules/mongoose/.npmignore +++ /dev/null @@ -1,13 +0,0 @@ -lib-cov -**.swp -*.sw* -*.orig -.DS_Store -node_modules/ -benchmarks/ -docs/ -test/ -Makefile -CNAME -index.html -index.jade diff --git a/node_modules/mongoose/.travis.yml b/node_modules/mongoose/.travis.yml deleted file mode 100644 index dcaf0f1f9..000000000 --- a/node_modules/mongoose/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - 0.8 - - 0.10 -services: - - mongodb diff --git a/node_modules/mongoose/CONTRIBUTING.md b/node_modules/mongoose/CONTRIBUTING.md deleted file mode 100644 index 5860cb531..000000000 --- a/node_modules/mongoose/CONTRIBUTING.md +++ /dev/null @@ -1,58 +0,0 @@ -## Contributing to Mongoose - -If you have a question about Mongoose (not a bug report) please post it to either [StackOverflow](http://stackoverflow.com/questions/tagged/mongoose), our [Google Group](http://groups.google.com/group/mongoose-orm), or on the #mongoosejs irc channel on freenode. - -### Reporting bugs - -- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new). - - Please describe the issue you are experiencing, along with any associated stack trace. - - Please post code that reproduces the issue, the version of mongoose, node version, and mongodb version. - - _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_. - - In general, adding a "+1" comment to an existing issue does little to help get it resolved. A better way is to submit a well documented pull request with clean code and passing tests. - -### Requesting new features - -- Before opening a new issue, look for existing [issues](https://github.com/learnboost/mongoose/issues) to avoid duplication. If the issue does not yet exist, [create one](https://github.com/learnboost/mongoose/issues/new). -- Please describe a use case for it -- it would be ideal to include test cases as well -- In general, adding a "+1" comment to an existing issue does little to help get it resolved. A better way is to submit a well documented pull request with clean code and passing tests. - -### Fixing bugs / Adding features - -- Before starting to write code, look for existing [issues](https://github.com/learnboost/mongoose/issues). That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. You can create a new issue [here](https://github.com/learnboost/mongoose/issues/new). - - _The source of this project is written in javascript, not coffeescript, therefore your bug reports should be written in javascript_. -- Fork the [repo](https://github.com/learnboost/mongoose) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. -- Follow the general coding style of the rest of the project: - - 2 space tabs - - no trailing whitespace - - comma first - - inline documentation for new methods, class members, etc - - 1 space between conditionals/functions, and their parenthesis and curly braces - - `if (..) {` - - `for (..) {` - - `while (..) {` - - `function (err) {` -- Write tests and make sure they pass (tests are in the [test](https://github.com/LearnBoost/mongoose/tree/master/test) directory). - -### Running the tests -- Open a terminal and navigate to the root of the project -- execute `npm install` to install the necessary dependencies -- execute `make test` to run the tests (we're using [mocha](http://visionmedia.github.com/mocha/)) - - or to execute a single test `T="-g 'some regexp that matches the test description'" make test` - - any mocha flags can be specified with `T="..."` - -### Documentation - -To contribute to the [API documentation](http://mongoosejs.com/docs/api.html) just make your changes to the inline documentation of the appropriate [source code](https://github.com/LearnBoost/mongoose/tree/master/lib) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. - -To contribute to the [guide](http://mongoosejs.com/docs/guide.html) or [quick start](http://mongoosejs.com/docs/index.html) docs, make your changes to the appropriate `.jade` files in the [docs](https://github.com/LearnBoost/mongoose/tree/master/docs) directory of the master branch and submit a pull request. Again, the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button might work for you here. - -If you'd like to preview your documentation changes, first commit your changes to your local 3.6.x branch, then execute `make docs` from the project root, which switches to the gh-pages branch, merges from the 3.6.x branch and builds all the static pages for you. Now execute `node static.js` from the project root which will launch a local webserver where you can browse the documentation site locally. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the 3.6.x branch with your changes. - -### Plugins website - -The [plugins](http://plugins.mongoosejs.com/) site is also an [open source project](https://github.com/aheckmann/mongooseplugins) that you can get involved with. Feel free to fork and improve it as well! - -### Sharing your projects - -All are welcome to share their creations which use mongoose on our [tumbler](http://mongoosejs.tumblr.com/). Just fill out the [simple submission form](http://mongoosejs.tumblr.com/submit). diff --git a/node_modules/mongoose/History.md b/node_modules/mongoose/History.md deleted file mode 100644 index 0a2c31514..000000000 --- a/node_modules/mongoose/History.md +++ /dev/null @@ -1,2013 +0,0 @@ - -3.8.4 / 2014-01-07 -================== - - * updated; mongodb driver to 1.3.23 - * updated; mquery to 0.4.1 - * updated; mpromise to 0.4.3 - * fixed; discriminators now work when selecting fields #1820 [daemon1981](https://github.com/daemon1981) - * fixed; geoSearch with no results timeout #1846 [ghartnett](https://github.com/ghartnett) - * fixed; infitite recursion in ValidationError #1834 [chetverikov](https://github.com/chetverikov) - -3.8.3 / 2013-12-17 -================== - - * fixed; setting empty array with model.update #1838 - * docs; fix url - -3.8.2 / 2013-12-14 -================== - - * fixed; enum validation of multiple values #1778 [heroicyang](https://github.com/heroicyang) - * fixed; global var leak #1803 - * fixed; post remove now fires on subdocs #1810 - * fixed; no longer set default empty array for geospatial-indexed fields #1668 [shirish87](https://github.com/shirish87) - * fixed; model.stream() not hydrating discriminators correctly #1792 [j](https://github.com/j) - * docs: Stablility -> Stability [nikmartin](https://github.com/nikmartin) - * tests; improve shard error handling - -3.8.1 / 2013-11-19 -================== - - * fixed; mishandling of Dates with minimize/getters #1764 - * fixed; Normalize bugs.email, so `npm` will shut up #1769 [refack](https://github.com/refack) - * docs; Improve the grammar where "lets us" was used #1777 [alexyoung](https://github.com/alexyoung) - * docs; Fix some grammatical issues in the documentation #1777 [alexyoung](https://github.com/alexyoung) - * docs; fix Query api exposure - * docs; fix return description - * docs; Added Notes on findAndUpdate() #1750 [sstadelman](https://github.com/sstadelman) - * docs; Update version number in README #1762 [Fodi69](https://github.com/Fodi69) - -3.8.0 / 2013-10-31 -================== - - * updated; warn when using an unstable version - * updated; error message returned in doc.save() #1595 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * updated; mquery to 0.3.2 - * updated; mocha to 1.12.0 - * updated; mpromise 0.3.0 - * updated; sliced 0.0.5 - * removed; mongoose.Error.DocumentError (never used) - * removed; namedscope (undocumented and broken) #679 #642 #455 #379 - * changed; no longer offically supporting node 0.6.x - * changed; query.within getter is now a method -> query.within() - * changed; query.intersects getter is now a method -> query.intersects() - * added; custom error msgs for built-in validators #747 - * added; discriminator support #1647 #1003 [j](https://github.com/j) - * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) - * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) - * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) - * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) - * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) - * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) - * added; promise support to model.mapReduce() - * added; promise support to model.ensureIndexes() - * added; promise support to model.populate() - * added; benchmarks [ebensing](https://github.com/ebensing) - * added; publicly exposed connection states #1585 - * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) - * added; query method chain validation - * added; model.update `overwrite` option - * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) - * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) - * added; MongooseBuffer#subtype() - * added; model.create() now returns a promise #1340 - * added; support for `awaitdata` query option - * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) - * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) - * fixed; document.toObject when using `minimize` and `getters` options #1607 [JedWatson](https://github.com/JedWatson) - * fixed; Mixed types can now be required #1722 [Reggino](https://github.com/Reggino) - * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals() when _id option is set to false #1687 - * fixed; strict mode warnings #1686 - * fixed; $near GeoJSON casting #1683 - * fixed; nearSphere GeoJSON query builder - * fixed; population field selection w/ strings #1669 - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; handle another versioning edge case #1520 - * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) - * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) - * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) - * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) - * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) - * fixed; model.remove() removes only what is necessary #1649 - * fixed; update() now only runs with cb or explicit true #1644 - * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) - * fixed; model.update "overwrite" option works as documented - * fixed; query#remove() works as documented - * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) - * fixed; benchmarks to actually output valid json - * deprecated; promise#addBack (use promise#onResolve) - * deprecated; promise#complete (use promise#fulfill) - * deprecated; promise#addCallback (use promise#onFulFill) - * deprecated; promise#addErrback (use promise#onReject) - * deprecated; query.nearSphere() (use query.near) - * deprecated; query.center() (use query.circle) - * deprecated; query.centerSphere() (use query.circle) - * deprecated; query#slaveOk (use query#read) - * docs; custom validator messages - * docs; 10gen -> MongoDB - * docs; add Date method caveats #1598 - * docs; more validation details - * docs; state which branch is stable/unstable - * docs; mention that middleware does not run on Models - * docs; promise.fulfill() - * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) - * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) - * website; add "show code" for properties - * website; move "show code" links down - * website; update guide - * website; add unstable docs - * website; many improvements - * website; fix copyright #1439 - * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) - * tests; refactor 1703 - * tests; add test generator - * tests; validate formatMessage() throws - * tests; add script for continuously running tests - * tests; fixed versioning tests - * tests; race conditions in tests - * tests; added for nested and/or queries - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; replace deprecated method names - * tests; convert id to string - * tests; fix sharding tests for MongoDB 2.4.5 - * tests; now 4-5 seconds faster - * tests; fix race condition - * make; suppress warning msg in test - * benchmarks; updated for pull requests - * examples; improved and expanded [ebensing](https://github.com/ebensing) - -3.7.4 (unstable) / 2013-10-01 -============================= - - * updated; mquery to 0.3.2 - * removed; mongoose.Error.DocumentError (never used) - * added; custom error msgs for built-in validators #747 - * added; discriminator support #1647 #1003 [j](https://github.com/j) - * added; support disabled collection name pluralization #1350 #1707 [refack](https://github.com/refack) - * fixed; do not pluralize model names not ending with letters #1703 [refack](https://github.com/refack) - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals() when _id option is set to false #1687 - * fixed; strict mode warnings #1686 - * fixed; $near GeoJSON casting #1683 - * fixed; nearSphere GeoJSON query builder - * fixed; population field selection w/ strings #1669 - * docs; custom validator messages - * docs; 10gen -> MongoDB - * docs; add Date method caveats #1598 - * docs; more validation details - * website; add "show code" for properties - * website; move "show code" links down - * tests; refactor 1703 - * tests; add test generator - * tests; validate formatMessage() throws - -3.7.3 (unstable) / 2013-08-22 -============================= - - * updated; warn when using an unstable version - * updated; mquery to 0.3.1 - * updated; mocha to 1.12.0 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * changed; no longer offically supporting node 0.6.x - * added; support for GeoJSON to Query#near [ebensing](https://github.com/ebensing) - * added; stand-alone base query support - query.toConstructor() [ebensing](https://github.com/ebensing) - * added; promise support to geoSearch #1614 [ebensing](https://github.com/ebensing) - * added; promise support for geoNear #1614 [ebensing](https://github.com/ebensing) - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; handle another versioning edge case #1520 - * fixed; excluding subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; allow array properties to be set to null with findOneAndUpdate [aheuermann](https://github.com/aheuermann) - * fixed; subdocuments now use own toJSON opts #1376 [ebensing](https://github.com/ebensing) - * fixed; model#geoNear fulfills promise when results empty #1658 [ebensing](https://github.com/ebensing) - * fixed; utils.merge no longer overrides props and methods #1655 [j](https://github.com/j) - * fixed; subdocuments now use their own transform #1412 [ebensing](https://github.com/ebensing) - * make; suppress warning msg in test - * docs; state which branch is stable/unstable - * docs; mention that middleware does not run on Models - * tests; add script for continuously running tests - * tests; fixed versioning tests - * benchmarks; updated for pull requests - -3.7.2 (unstable) / 2013-08-15 -================== - - * fixed; model.remove() removes only what is necessary #1649 - * fixed; update() now only runs with cb or explicit true #1644 - * tests; race conditions in tests - * website; update guide - -3.7.1 (unstable) / 2013-08-13 -============================= - - * updated; driver to 1.3.18 (fixes memory leak) - * added; connection.useDb() #1124 [ebensing](https://github.com/ebensing) - * added; promise support to model.mapReduce() - * added; promise support to model.ensureIndexes() - * added; promise support to model.populate() - * fixed; casting ref docs on creation #1606 [ebensing](https://github.com/ebensing) - * fixed; model.update "overwrite" option works as documented - * fixed; query#remove() works as documented - * fixed; "limit" correctly applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; issue with positional operator on ref docs #1572 [ebensing](https://github.com/ebensing) - * fixed; benchmarks to actually output valid json - * tests; added for nested and/or queries - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; close some test connections - * tests; validate db contents - * tests; remove .only - * tests; replace deprecated method names - * tests; convert id to string - * docs; promise.fulfill() - -3.7.0 (unstable) / 2013-08-05 -=================== - - * changed; query.within getter is now a method -> query.within() - * changed; query.intersects getter is now a method -> query.intersects() - * deprecated; promise#addBack (use promise#onResolve) - * deprecated; promise#complete (use promise#fulfill) - * deprecated; promise#addCallback (use promise#onFulFill) - * deprecated; promise#addErrback (use promise#onReject) - * deprecated; query.nearSphere() (use query.near) - * deprecated; query.center() (use query.circle) - * deprecated; query.centerSphere() (use query.circle) - * deprecated; query#slaveOk (use query#read) - * removed; namedscope (undocumented and broken) #679 #642 #455 #379 - * added; benchmarks [ebensing](https://github.com/ebensing) - * added; publicly exposed connection states #1585 - * added; $geoWithin support #1529 $1455 [ebensing](https://github.com/ebensing) - * added; query method chain validation - * added; model.update `overwrite` option - * added; model.geoNear() support #1563 [ebensing](https://github.com/ebensing) - * added; model.geoSearch() support #1560 [ebensing](https://github.com/ebensing) - * added; MongooseBuffer#subtype() - * added; model.create() now returns a promise #1340 - * added; support for `awaitdata` query option - * added; pass the doc to doc.remove() callback #1419 [JoeWagner](https://github.com/JoeWagner) - * added; aggregation query builder #1404 [njoyard](https://github.com/njoyard) - * updated; integrate mquery #1562 [ebensing](https://github.com/ebensing) - * updated; error msg in doc.save() #1595 - * updated; bump driver to 1.3.15 - * updated; mpromise 0.3.0 - * updated; sliced 0.0.5 - * tests; fix sharding tests for MongoDB 2.4.5 - * tests; now 4-5 seconds faster - * tests; fix race condition - * docs; fix readme spelling #1483 [yorchopolis](https://github.com/yorchopolis) - * docs; fixed up the README and examples [ebensing](https://github.com/ebensing) - * website; add unstable docs - * website; many improvements - * website; fix copyright #1439 - * website; server.js -> static.js #1546 [nikmartin](https://github.com/nikmartin) - * examples; improved and expanded [ebensing](https://github.com/ebensing) - -3.6.20 (stable) / 2013-09-23 -=================== - - * fixed; repopulating modified populated paths #1697 - * fixed; doc.equals w/ _id false #1687 - * fixed; strict mode warning #1686 - * docs; near/nearSphere - -3.6.19 (stable) / 2013-09-04 -================== - - * fixed; population field selection w/ strings #1669 - * docs; Date method caveats #1598 - -3.6.18 (stable) / 2013-08-22 -=================== - - * updated; warn when using an unstable version of mongoose - * updated; mocha to 1.12.0 - * updated; mongodb driver to 1.3.19 (fix error swallowing behavior) - * fixed; setters not firing on null values #1445 [ebensing](https://github.com/ebensing) - * fixed; properly exclude subdocument fields #1280 [ebensing](https://github.com/ebensing) - * fixed; cast error in findAndModify #1643 [aheuermann](https://github.com/aheuermann) - * website; update guide - * website; added documentation for safe:false and versioning interaction - * docs; mention that middleware dont run on Models - * docs; fix indexes link - * make; suppress warning msg in test - * tests; moar - -3.6.17 / 2013-08-13 -=================== - - * updated; driver to 1.3.18 (fixes memory leak) - * fixed; casting ref docs on creation #1606 - * docs; query options - -3.6.16 / 2013-08-08 -=================== - - * added; publicly expose connection states #1585 - * fixed; limit applies to individual items on population #1490 [ebensing](https://github.com/ebensing) - * fixed; positional operator casting in updates #1572 [ebensing](https://github.com/ebensing) - * updated; MongoDB driver to 1.3.17 - * updated; sliced to 0.0.5 - * website; tweak homepage - * tests; fixed + added - * docs; fix some examples - * docs; multi-mongos support details - * docs; auto open browser after starting static server - -3.6.15 / 2013-07-16 -================== - - * added; mongos failover support #1037 - * updated; make schematype return vals return self #1580 - * docs; add note to model.update #571 - * docs; document third param to document.save callback #1536 - * tests; tweek mongos test timeout - -3.6.14 / 2013-07-05 -=================== - - * updated; driver to 1.3.11 - * fixed; issue with findOneAndUpdate not returning null on upserts #1533 [ebensing](https://github.com/ebensing) - * fixed; missing return statement in SchemaArray#$geoIntersects() #1498 [bsrykt](https://github.com/bsrykt) - * fixed; wrong isSelected() behavior #1521 [kyano](https://github.com/kyano) - * docs; note about toObject behavior during save() - * docs; add callbacks details #1547 [nikmartin](https://github.com/nikmartin) - -3.6.13 / 2013-06-27 -=================== - - * fixed; calling model.distinct without conditions #1541 - * fixed; regression in Query#count() #1542 - * now working on 3.6.13 - -3.6.12 / 2013-06-25 -=================== - - * updated; driver to 1.3.10 - * updated; clearer capped collection error message #1509 [bitmage](https://github.com/bitmage) - * fixed; MongooseBuffer subtype loss during casting #1517 [zedgu](https://github.com/zedgu) - * fixed; docArray#id when doc.id is disabled #1492 - * fixed; docArray#id now supports matches on populated arrays #1492 [pgherveou](https://github.com/pgherveou) - * website; fix example - * website; improve _id disabling example - * website; fix typo #1494 [dejj](https://github.com/dejj) - * docs; added a 'Requesting new features' section #1504 [shovon](https://github.com/shovon) - * docs; improve subtypes description - * docs; clarify _id disabling - * docs: display by alphabetical order the methods list #1508 [nicolasleger](https://github.com/nicolasleger) - * tests; refactor isSelected checks - * tests; remove pointless test - * tests; fixed timeouts - -3.6.11 / 2013-05-15 -=================== - - * updated; driver to 1.3.5 - * fixed; compat w/ Object.create(null) #1484 #1485 - * fixed; cloning objects w/ missing constructors - * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) - * docs; add doc.increment() example - * docs; add $size example - * docs; add "distinct" example - -3.6.10 / 2013-05-09 -================== - - * update driver to 1.3.3 - * fixed; increment() works without other changes #1475 - * website; fix links to posterous - * docs; fix link #1472 - -3.6.9 / 2013-05-02 -================== - - * fixed; depopulation of mixed documents #1471 - * fixed; use of $options in array #1462 - * tests; fix race condition - * docs; fix default example - -3.6.8 / 2013-04-25 -================== - - * updated; driver to 1.3.0 - * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) - * tests; 4-5 seconds faster - -3.6.7 / 2013-04-19 -================== - - * fixed; population regression in 3.6.6 #1444 - -3.6.6 / 2013-04-18 -================== - - * fixed; saving populated new documents #1442 - * fixed; population regession in 3.6.5 #1441 - * website; fix copyright #1439 - -3.6.5 / 2013-04-15 -================== - - * fixed; strict:throw edge case using .set(path, val) - * fixed; schema.pathType() on some numbericAlpha paths - * fixed; numbericAlpha path versioning - * fixed; setting nested mixed paths #1418 - * fixed; setting nested objects with null prop #1326 - * fixed; regression in v3.6 population performance #1426 [vedmalex](https://github.com/vedmalex) - * fixed; read pref typos #1422 [kyano](https://github.com/kyano) - * docs; fix method example - * website; update faq - * website; add more deep links - * website; update poolSize docs - * website; add 3.6 release notes - * website; note about keepAlive - -3.6.4 / 2013-04-03 -================== - - * fixed; +field conflict with $slice #1370 - * fixed; nested deselection conflict #1333 - * fixed; RangeError in ValidationError.toString() #1296 - * fixed; do not save user defined transforms #1415 - * tests; fix race condition - -3.6.3 / 2013-04-02 -================== - - * fixed; setting subdocuments deeply nested fields #1394 - * fixed; regression: populated streams #1411 - * docs; mention hooks/validation with findAndModify - * docs; mention auth - * docs; add more links - * examples; add document methods example - * website; display "see" links for properties - * website; clean up homepage - -3.6.2 / 2013-03-29 -================== - - * fixed; corrupted sub-doc array #1408 - * fixed; document#update returns a Query #1397 - * docs; readpref strategy - -3.6.1 / 2013-03-27 -================== - - * added; populate support to findAndModify varients #1395 - * added; text index type to schematypes - * expose allowed index types as Schema.indexTypes - * fixed; use of `setMaxListeners` as path - * fixed; regression in node 0.6 on docs with > 10 arrays - * fixed; do not alter schema arguments #1364 - * fixed; subdoc#ownerDocument() #1385 - * website; change search id - * website; add search from google [jackdbernier](https://github.com/jackdbernier) - * website; fix link - * website; add 3.5.x docs release - * website; fix link - * docs; fix geometry - * docs; hide internal constructor - * docs; aggregation does not cast arguments #1399 - * docs; querystream options - * examples; added for population - -3.6.0 / 2013-03-18 -================== - - * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) - * changed; Buffer arrays can now contain nulls - * added; QueryStream transform option - * added; support for authSource driver option - * added; {mongoose,db}.modelNames() - * added; $push w/ $slice,$sort support (MongoDB 2.4) - * added; hashed index type (MongoDB 2.4) - * added; support for mongodb 2.4 geojson (MongoDB 2.4) - * added; value at time of validation error - * added; support for object literal schemas - * added; bufferCommands schema option - * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) - * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) - * added; allow adding uncasted docs to populated arrays and properties #570 - * added; doc#populated(path) stores original populated _ids - * added; lean population #1260 - * added; query.populate() now accepts an options object - * added; document#populate(opts, callback) - * added; Model.populate(docs, opts, callback) - * added; support for rich nested path population - * added; doc.array.remove(value) subdoc with _id value support #1278 - * added; optionally allow non-strict sets and updates - * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) - * added; promise#then - * added; promise#end - * fixed; use of `model` as doc property - * fixed; lean population #1382 - * fixed; empty object mixed defaults #1380 - * fixed; populate w/ deselected _id using string syntax - * fixed; attempted save of divergent populated arrays #1334 related - * fixed; better error msg when attempting toObject as property name - * fixed; non population buffer casting from doc - * fixed; setting populated paths #570 - * fixed; casting when added docs to populated arrays #570 - * fixed; prohibit updating arrays selected with $elemMatch #1334 - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * fixed; manual reconnection to single mongod - * fixed; Constructor / version exposure #1124 - * fixed; CastError race condition - * fixed; no longer swallowing misuse of subdoc#invalidate() - * fixed; utils.clone retains RegExp opts - * fixed; population of non-schema property - * fixed; allow updating versionKey #1265 - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; can now deselect populated doc _ids #1331 - * fixed; properly pass subtype to Binary in MongooseBuffer - * fixed; casting _id from document with non-ObjectId _id - * fixed; specifying schema type edge case { path: [{type: "String" }] } - * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) - * updated; driver to 1.2.14 - * updated; muri to 0.3.1 - * updated; mpromise to 0.2.1 - * updated; mocha 1.8.1 - * updated; mpath to 0.1.1 - * deprecated; pluralization will die in 4.x - * refactor; rename private methods to something unusable as doc properties - * refactor MongooseArray#remove - * refactor; move expires index to SchemaDate #1328 - * refactor; internal document properties #1171 #1184 - * tests; added - * docs; indexes - * docs; validation - * docs; populate - * docs; populate - * docs; add note about stream compatibility with node 0.8 - * docs; fix for private names - * docs; Buffer -> mongodb.Binary #1363 - * docs; auth options - * docs; improved - * website; update FAQ - * website; add more api links - * website; add 3.5.x docs to prior releases - * website; Change mongoose-types to an active repo [jackdbernier](https://github.com/jackdbernier) - * website; compat with node 0.10 - * website; add news section - * website; use T for generic type - * benchmark; make adjustable - -3.6.0rc1 / 2013-03-12 -====================== - - * refactor; rename private methods to something unusable as doc properties - * added; {mongoose,db}.modelNames() - * added; $push w/ $slice,$sort support (MongoDB 2.4) - * added; hashed index type (MongoDB 2.4) - * added; support for mongodb 2.4 geojson (MongoDB 2.4) - * added; value at time of validation error - * added; support for object literal schemas - * added; bufferCommands schema option - * added; allow auth option in connections #1360 [geoah](https://github.com/geoah) - * fixed; lean population #1382 - * fixed; empty object mixed defaults #1380 - * fixed; populate w/ deselected _id using string syntax - * fixed; attempted save of divergent populated arrays #1334 related - * fixed; better error msg when attempting toObject as property name - * fixed; non population buffer casting from doc - * fixed; setting populated paths #570 - * fixed; casting when added docs to populated arrays #570 - * fixed; prohibit updating arrays selected with $elemMatch #1334 - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * fixed; manual reconnection to single mongod - * fixed; Constructor / version exposure #1124 - * fixed; CastError race condition - * fixed; no longer swallowing misuse of subdoc#invalidate() - * fixed; utils.clone retains RegExp opts - * fixed; population of non-schema property - * fixed; allow updating versionKey #1265 - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; can now deselect populated doc _ids #1331 - * updated; muri to 0.3.1 - * updated; driver to 1.2.12 - * updated; mpromise to 0.2.1 - * deprecated; pluralization will die in 4.x - * docs; Buffer -> mongodb.Binary #1363 - * docs; auth options - * docs; improved - * website; add news section - * benchmark; make adjustable - -3.6.0rc0 / 2013-02-03 -====================== - - * changed; cast 'true'/'false' to boolean #1282 [mgrach](https://github.com/mgrach) - * changed; Buffer arrays can now contain nulls - * fixed; properly pass subtype to Binary in MongooseBuffer - * fixed; casting _id from document with non-ObjectId _id - * fixed; specifying schema type edge case { path: [{type: "String" }] } - * fixed; typo in schemdate #1329 [jplock](https://github.com/jplock) - * refactor; move expires index to SchemaDate #1328 - * refactor; internal document properties #1171 #1184 - * added; performance improvements to populate() [263ece9](https://github.com/LearnBoost/mongoose/commit/263ece9) - * added; allow adding uncasted docs to populated arrays and properties #570 - * added; doc#populated(path) stores original populated _ids - * added; lean population #1260 - * added; query.populate() now accepts an options object - * added; document#populate(opts, callback) - * added; Model.populate(docs, opts, callback) - * added; support for rich nested path population - * added; doc.array.remove(value) subdoc with _id value support #1278 - * added; optionally allow non-strict sets and updates - * added; promises/A+ comformancy with [mpromise](https://github.com/aheckmann/mpromise) - * added; promise#then - * added; promise#end - * updated; mocha 1.8.1 - * updated; muri to 0.3.0 - * updated; mpath to 0.1.1 - * updated; docs - -3.5.16 / 2013-08-13 -=================== - - * updated; driver to 1.3.18 - -3.5.15 / 2013-07-26 -================== - - * updated; sliced to 0.0.5 - * updated; driver to 1.3.12 - * fixed; regression in Query#count() due to driver change - * tests; fixed timeouts - * tests; handle differing test uris - -3.5.14 / 2013-05-15 -=================== - - * updated; driver to 1.3.5 - * fixed; compat w/ Object.create(null) #1484 #1485 - * fixed; cloning objects missing constructors - * fixed; prevent multiple min number validators #1481 [nrako](https://github.com/nrako) - -3.5.13 / 2013-05-09 -================== - - * update driver to 1.3.3 - * fixed; use of $options in array #1462 - -3.5.12 / 2013-04-25 -=================== - - * updated; driver to 1.3.0 - * fixed; connection.model should retain options #1458 [vedmalex](https://github.com/vedmalex) - * fixed; read pref typos #1422 [kyano](https://github.com/kyano) - -3.5.11 / 2013-04-03 -================== - - * fixed; +field conflict with $slice #1370 - * fixed; RangeError in ValidationError.toString() #1296 - * fixed; nested deselection conflict #1333 - * remove time from Makefile - -3.5.10 / 2013-04-02 -================== - - * fixed; setting subdocuments deeply nested fields #1394 - * fixed; do not alter schema arguments #1364 - -3.5.9 / 2013-03-15 -================== - - * updated; driver to 1.2.14 - * added; support for authSource driver option (mongodb 2.4) - * added; QueryStream transform option (node 0.10 helper) - * fixed; backport for saving required populated buffers - * fixed; pull / set subdoc combination #1303 - * fixed; multiple bg index creation #1365 - * test; added for saveable required populated buffers - * test; added for #1365 - * test; add authSource test - -3.5.8 / 2013-03-12 -================== - - * added; auth option in connection [geoah](https://github.com/geoah) - * fixed; CastError race condition - * docs; add note about stream compatibility with node 0.8 - -3.5.7 / 2013-02-22 -================== - - * updated; driver to 1.2.13 - * updated; muri to 0.3.1 #1347 - * fixed; utils.clone retains RegExp opts #1355 - * fixed; deepEquals RegExp support - * tests; fix a connection test - * website; clean up docs [afshinm](https://github.com/afshinm) - * website; update homepage - * website; migragtion: emphasize impact of strict docs #1264 - -3.5.6 / 2013-02-14 -================== - - * updated; driver to 1.2.12 - * fixed; properly pass Binary subtype - * fixed; add EventEmitter props to reserved paths #1338 - * fixed; use correct node engine version - * fixed; display empty docs as {} in log output #953 follow up - * improved; "bad $within $box argument" error message - * populate; add unscientific benchmark - * website; add stack overflow to help section - * website; use better code font #1336 [risseraka](https://github.com/risseraka) - * website; clarify where help is available - * website; fix source code links #1272 [floatingLomas](https://github.com/floatingLomas) - * docs; be specific about _id schema option #1103 - * docs; add ensureIndex error handling example - * docs; README - * docs; CONTRIBUTING.md - -3.5.5 / 2013-01-29 -================== - - * updated; driver to 1.2.11 - * removed; old node < 0.6x shims - * fixed; documents with Buffer _ids equality - * fixed; MongooseBuffer properly casts numbers - * fixed; reopening closed connection on alt host/port #1287 - * docs; fixed typo in Readme #1298 [rened](https://github.com/rened) - * docs; fixed typo in migration docs [Prinzhorn](https://github.com/Prinzhorn) - * docs; fixed incorrect annotation in SchemaNumber#min [bilalq](https://github.com/bilalq) - * docs; updated - -3.5.4 / 2013-01-07 -================== - - * changed; "_pres" & "_posts" are now reserved pathnames #1261 - * updated; driver to 1.2.8 - * fixed; exception when reopening a replica set. #1263 [ethankan](https://github.com/ethankan) - * website; updated - -3.5.3 / 2012-12-26 -================== - - * added; support for geo object notation #1257 - * fixed; $within query casting with arrays - * fixed; unix domain socket support #1254 - * updated; driver to 1.2.7 - * updated; muri to 0.0.5 - -3.5.2 / 2012-12-17 -================== - - * fixed; using auth with replica sets #1253 - -3.5.1 / 2012-12-12 -================== - - * fixed; regression when using subdoc with `path` as pathname #1245 [daeq](https://github.com/daeq) - * fixed; safer db option checks - * updated; driver to 1.2.5 - * website; add more examples - * website; clean up old docs - * website; fix prev release urls - * docs; clarify streaming with HTTP responses - -3.5.0 / 2012-12-10 -================== - - * added; paths to CastErrors #1239 - * added; support for mongodb connection string spec #1187 - * added; post validate event - * added; Schema#get (to retrieve schema options) - * added; VersionError #1071 - * added; npmignore [hidekiy](https://github.com/hidekiy) - * update; driver to 1.2.3 - * fixed; stackoverflow in setter #1234 - * fixed; utils.isObject() - * fixed; do not clobber user specified driver writeConcern #1227 - * fixed; always pass current document to post hooks - * fixed; throw error when user attempts to overwrite a model - * fixed; connection.model only caches on connection #1209 - * fixed; respect conn.model() creation when matching global model exists #1209 - * fixed; passing model name + collection name now always honors collection name - * fixed; setting virtual field to an empty object #1154 - * fixed; subclassed MongooseErrors exposure, now available in mongoose.Error.xxxx - * fixed; model.remove() ignoring callback when executed twice [daeq](https://github.com/daeq) #1210 - * docs; add collection option to schema api docs #1222 - * docs; NOTE about db safe options - * docs; add post hooks docs - * docs; connection string options - * docs; middleware is not executed with Model.remove #1241 - * docs; {g,s}etter introspection #777 - * docs; update validation docs - * docs; add link to plugins page - * docs; clarify error returned by unique indexes #1225 - * docs; more detail about disabling autoIndex behavior - * docs; add homepage section to package (npm docs mongoose) - * docs; more detail around collection name pluralization #1193 - * website; add .important css - * website; update models page - * website; update getting started - * website; update quick start - -3.4.0 / 2012-11-10 -================== - - * added; support for generic toJSON/toObject transforms #1160 #1020 #1197 - * added; doc.set() merge support #1148 [NuORDER](https://github.com/NuORDER) - * added; query#add support #1188 [aleclofabbro](https://github.com/aleclofabbro) - * changed; adding invalid nested paths to non-objects throws 4216f14 - * changed; fixed; stop invalid function cloning (internal fix) - * fixed; add query $and casting support #1180 [anotheri](https://github.com/anotheri) - * fixed; overwriting of query arguments #1176 - * docs; fix expires examples - * docs; transforms - * docs; schema `collection` option docs [hermanjunge](https://github.com/hermanjunge) - * website; updated - * tests; added - -3.3.1 / 2012-10-11 -================== - - * fixed; allow goose.connect(uris, dbname, opts) #1144 - * docs; persist API private checked state across page loads - -3.3.0 / 2012-10-10 -================== - - * fixed; passing options as 2nd arg to connect() #1144 - * fixed; race condition after no-op save #1139 - * fixed; schema field selection application in findAndModify #1150 - * fixed; directly setting arrays #1126 - * updated; driver to 1.1.11 - * updated; collection pluralization rules [mrickard](https://github.com/mrickard) - * tests; added - * docs; updated - -3.2.2 / 2012-10-08 -================== - - * updated; driver to 1.1.10 #1143 - * updated; use sliced 0.0.3 - * fixed; do not recast embedded docs unnecessarily - * fixed; expires schema option helper #1132 - * fixed; built in string setters #1131 - * fixed; debug output for Dates/ObjectId properties #1129 - * docs; fixed Javascript syntax error in example [olalonde](https://github.com/olalonde) - * docs; fix toJSON example #1137 - * docs; add ensureIndex production notes - * docs; fix spelling - * docs; add blogposts about v3 - * website; updated - * removed; undocumented inGroupsOf util - * tests; added - -3.2.1 / 2012-09-28 -================== - - * fixed; remove query batchSize option default of 1000 https://github.com/learnboost/mongoose/commit/3edaa8651 - * docs; updated - * website; updated - -3.2.0 / 2012-09-27 -================== - - * added; direct array index assignment with casting support `doc.array.set(index, value)` - * fixed; QueryStream#resume within same tick as pause() #1116 - * fixed; default value validatation #1109 - * fixed; array splice() not casting #1123 - * fixed; default array construction edge case #1108 - * fixed; query casting for inequalities in arrays #1101 [dpatti](https://github.com/dpatti) - * tests; added - * website; more documentation - * website; fixed layout issue #1111 [SlashmanX](https://github.com/SlashmanX) - * website; refactored [guille](https://github.com/guille) - -3.1.2 / 2012-09-10 -================== - - * added; ReadPreferrence schema option #1097 - * updated; driver to 1.1.7 - * updated; default query batchSize to 1000 - * fixed; we now cast the mapReduce query option #1095 - * fixed; $elemMatch+$in with field selection #1091 - * fixed; properly cast $elemMatch+$in conditions #1100 - * fixed; default field application of subdocs #1027 - * fixed; querystream prematurely dying #1092 - * fixed; querystream never resumes when paused at getMore boundries #1092 - * fixed; querystream occasionally emits data events after destroy #1092 - * fixed; remove unnecessary ObjectId creation in querystream - * fixed; allow ne(boolean) again #1093 - * docs; add populate/field selection syntax notes - * docs; add toObject/toJSON options detail - * docs; `read` schema option - -3.1.1 / 2012-08-31 -================== - - * updated; driver to 1.1.6 - -3.1.0 / 2012-08-29 -================== - - * changed; fixed; directly setting nested objects now overwrites entire object (previously incorrectly merged them) - * added; read pref support (mongodb 2.2) 205a709c - * added; aggregate support (mongodb 2.2) f3a5bd3d - * added; virtual {g,s}etter introspection (#1070) - * updated; docs [brettz9](https://github.com/brettz9) - * updated; driver to 1.1.5 - * fixed; retain virtual setter return values (#1069) - -3.0.3 / 2012-08-23 -================== - - * fixed; use of nested paths beginning w/ numbers #1062 - * fixed; query population edge case #1053 #1055 [jfremy](https://github.com/jfremy) - * fixed; simultaneous top and sub level array modifications #1073 - * added; id and _id schema option aliases + tests - * improve debug formatting to allow copy/paste logged queries into mongo shell [eknkc](https://github.com/eknkc) - * docs - -3.0.2 / 2012-08-17 -================== - - * added; missing support for v3 sort/select syntax to findAndModify helpers (#1058) - * fixed; replset fullsetup event emission - * fixed; reconnected event for replsets - * fixed; server reconnection setting discovery - * fixed; compat with non-schema path props using positional notation (#1048) - * fixed; setter/casting order (#665) - * docs; updated - -3.0.1 / 2012-08-11 -================== - - * fixed; throw Error on bad validators (1044) - * fixed; typo in EmbeddedDocument#parentArray [lackac] - * fixed; repair mongoose.SchemaTypes alias - * updated; docs - -3.0.0 / 2012-08-07 -================== - - * removed; old subdocument#commit method - * fixed; setting arrays of matching docs [6924cbc2] - * fixed; doc!remove event now emits in save order as save for consistency - * fixed; pre-save hooks no longer fire on subdocuments when validation fails - * added; subdoc#parent() and subdoc#parentArray() to access subdocument parent objects - * added; query#lean() helper - -3.0.0rc0 / 2012-08-01 -===================== - - * fixed; allow subdoc literal declarations containing "type" pathname (#993) - * fixed; unsetting a default array (#758) - * fixed; boolean $in queries (#998) - * fixed; allow use of `options` as a pathname (#529) - * fixed; `model` is again a permitted schema path name - * fixed; field selection option on subdocs (#1022) - * fixed; handle another edge case with subdoc saving (#975) - * added; emit save err on model if listening - * added; MongoDB TTL collection support (#1006) - * added; $center options support - * added; $nearSphere and $polygon support - * updated; driver version to 1.1.2 - -3.0.0alpha2 / 2012-07-18 -========================= - - * changed; index errors are now emitted on their model and passed to an optional callback (#984) - * fixed; specifying index along with sparse/unique option no longer overwrites (#1004) - * fixed; never swallow connection errors (#618) - * fixed; creating object from model with emded object no longer overwrites defaults [achurkin] (#859) - * fixed; stop needless validation of unchanged/unselected fields (#891) - * fixed; document#equals behavior of objectids (#974) - * fixed; honor the minimize schema option (#978) - * fixed; provide helpful error msgs when reserved schema path is used (#928) - * fixed; callback to conn#disconnect is optional (#875) - * fixed; handle missing protocols in connection urls (#987) - * fixed; validate args to query#where (#969) - * fixed; saving modified/removed subdocs (#975) - * fixed; update with $pull from Mixed array (#735) - * fixed; error with null shard key value - * fixed; allow unsetting enums (#967) - * added; support for manual index creation (#984) - * added; support for disabled auto-indexing (#984) - * added; support for preserving MongooseArray#sort changes (#752) - * added; emit state change events on connection - * added; support for specifying BSON subtype in MongooseBuffer#toObject [jcrugzz] - * added; support for disabled versioning (#977) - * added; implicit "new" support for models and Schemas - -3.0.0alpha1 / 2012-06-15 -========================= - - * removed; doc#commit (use doc#markModified) - * removed; doc.modified getter (#950) - * removed; mongoose{connectSet,createSetConnection}. use connect,createConnection instead - * removed; query alias methods 1149804c - * removed; MongooseNumber - * changed; now creating indexes in background by default - * changed; strict mode now enabled by default (#952) - * changed; doc#modifiedPaths is now a method (#950) - * changed; getters no longer cast (#820); casting happens during set - * fixed; no need to pass updateArg to findOneAndUpdate (#931) - * fixed: utils.merge bug when merging nested non-objects. [treygriffith] - * fixed; strict:throw should produce errors in findAndModify (#963) - * fixed; findAndUpdate no longer overwrites document (#962) - * fixed; setting default DocumentArrays (#953) - * fixed; selection of _id with schema deselection (#954) - * fixed; ensure promise#error emits instanceof Error - * fixed; CursorStream: No stack overflow on any size result (#929) - * fixed; doc#remove now passes safe options - * fixed; invalid use of $set during $pop - * fixed; array#{$pop,$shift} mirror MongoDB behavior - * fixed; no longer test non-required vals in string match (#934) - * fixed; edge case with doc#inspect - * fixed; setter order (#665) - * fixed; setting invalid paths in strict mode (#916) - * fixed; handle docs without id in DocumentArray#id method (#897) - * fixed; do not save virtuals during model.update (#894) - * fixed; sub doc toObject virtuals application (#889) - * fixed; MongooseArray#pull of ObjectId (#881) - * fixed; handle passing db name with any repl set string - * fixed; default application of selected fields (#870) - * fixed; subdoc paths reported in validation errors (#725) - * fixed; incorrect reported num of affected docs in update ops (#862) - * fixed; connection assignment in Model#model (#853) - * fixed; stringifying arrays of docs (#852) - * fixed; modifying subdoc and parent array works (#842) - * fixed; passing undefined to next hook (#785) - * fixed; Query#{update,remove}() works without callbacks (#788) - * fixed; set/updating nested objects by parent pathname (#843) - * fixed; allow null in number arrays (#840) - * fixed; isNew on sub doc after insertion error (#837) - * fixed; if an insert fails, set isNew back to false [boutell] - * fixed; isSelected when only _id is selected (#730) - * fixed; setting an unset default value (#742) - * fixed; query#sort error messaging (#671) - * fixed; support for passing $options with $regex - * added; array of object literal notation in schema creates DocumentArrays - * added; gt,gte,lt,lte query support for arrays (#902) - * added; capped collection support (#938) - * added; document versioning support - * added; inclusion of deselected schema path (#786) - * added; non-atomic array#pop - * added; EmbeddedDocument constructor is now exposed in DocArray#create 7cf8beec - * added; mapReduce support (#678) - * added; support for a configurable minimize option #to{Object,JSON}(option) (#848) - * added; support for strict: `throws` [regality] - * added; support for named schema types (#795) - * added; to{Object,JSON} schema options (#805) - * added; findByIdAnd{Update,Remove}() - * added; findOneAnd{Update,Remove}() - * added; query.setOptions() - * added; instance.update() (#794) - * added; support specifying model in populate() [DanielBaulig] - * added; `lean` query option [gitfy] - * added; multi-atomic support to MongooseArray#nonAtomicPush - * added; support for $set + other $atomic ops on single array - * added; tests - * updated; driver to 1.0.2 - * updated; query.sort() syntax to mirror query.select() - * updated; clearer cast error msg for array numbers - * updated; docs - * updated; doc.clone 3x faster (#950) - * updated; only create _id if necessary (#950) - -2.7.3 / 2012-08-01 -================== - - * fixed; boolean $in queries (#998) - * fixed field selection option on subdocs (#1022) - -2.7.2 / 2012-07-18 -================== - - * fixed; callback to conn#disconnect is optional (#875) - * fixed; handle missing protocols in connection urls (#987) - * fixed; saving modified/removed subdocs (#975) - * updated; tests - -2.7.1 / 2012-06-26 -=================== - - * fixed; sharding: when a document holds a null as a value of the shard key - * fixed; update() using $pull on an array of Mixed (gh-735) - * deprecated; MongooseNumber#{inc, increment, decrement} methods - * tests; now using mocha - -2.7.0 / 2012-06-14 -=================== - - * added; deprecation warnings to methods being removed in 3.x - -2.6.8 / 2012-06-14 -=================== - - * fixed; edge case when using 'options' as a path name (#961) - -2.6.7 / 2012-06-08 -=================== - - * fixed; ensure promise#error always emits instanceof Error - * fixed; selection of _id w/ another excluded path (#954) - * fixed; setting default DocumentArrays (#953) - -2.6.6 / 2012-06-06 -=================== - - * fixed; stack overflow in query stream with large result sets (#929) - * added; $gt, $gte, $lt, $lte support to arrays (#902) - * fixed; pass option `safe` along to doc#remove() calls - -2.6.5 / 2012-05-24 -=================== - - * fixed; do not save virtuals in Model.update (#894) - * added; missing $ prefixed query aliases (going away in 3.x) (#884) [timoxley] - * fixed; setting invalid paths in strict mode (#916) - * fixed; resetting isNew after insert failure (#837) [boutell] - -2.6.4 / 2012-05-15 -=================== - - * updated; backport string regex $options to 2.x - * updated; use driver 1.0.2 (performance improvements) (#914) - * fixed; calling MongooseDocumentArray#id when the doc has no _id (#897) - -2.6.3 / 2012-05-03 -=================== - - * fixed; repl-set connectivity issues during failover on MongoDB 2.0.1 - * updated; driver to 1.0.0 - * fixed; virtuals application of subdocs when using toObject({ virtuals: true }) (#889) - * fixed; MongooseArray#pull of ObjectId correctly updates the array itself (#881) - -2.6.2 / 2012-04-30 -=================== - - * fixed; default field application of selected fields (#870) - -2.6.1 / 2012-04-30 -=================== - - * fixed; connection assignment in mongoose#model (#853, #877) - * fixed; incorrect reported num of affected docs in update ops (#862) - -2.6.0 / 2012-04-19 -=================== - - * updated; hooks.js to 0.2.1 - * fixed; issue with passing undefined to a hook callback. thanks to [chrisleishman] for reporting. - * fixed; updating/setting nested objects in strict schemas (#843) as reported by [kof] - * fixed; Query#{update,remove}() work without callbacks again (#788) - * fixed; modifying subdoc along with parent array $atomic op (#842) - -2.5.14 / 2012-04-13 -=================== - - * fixed; setting an unset default value (#742) - * fixed; doc.isSelected(otherpath) when only _id is selected (#730) - * updated; docs - -2.5.13 / 2012-03-22 -=================== - - * fixed; failing validation of unselected required paths (#730,#713) - * fixed; emitting connection error when only one listener (#759) - * fixed; MongooseArray#splice was not returning values (#784) [chrisleishman] - -2.5.12 / 2012-03-21 -=================== - - * fixed; honor the `safe` option in all ensureIndex calls - * updated; node-mongodb-native driver to 0.9.9-7 - -2.5.11 / 2012-03-15 -=================== - - * added; introspection for getters/setters (#745) - * updated; node-mongodb-driver to 0.9.9-5 - * added; tailable method to Query (#769) [holic] - * fixed; Number min/max validation of null (#764) [btamas] - * added; more flexible user/password connection options (#738) [KarneAsada] - -2.5.10 / 2012-03-06 -=================== - - * updated; node-mongodb-native driver to 0.9.9-4 - * added; Query#comment() - * fixed; allow unsetting arrays - * fixed; hooking the set method of subdocuments (#746) - * fixed; edge case in hooks - * fixed; allow $id and $ref in queries (fixes compatibility with mongoose-dbref) (#749) [richtera] - * added; default path selection to SchemaTypes - -2.5.9 / 2012-02-22 -=================== - - * fixed; properly cast nested atomic update operators for sub-documents - -2.5.8 / 2012-02-21 -=================== - - * added; post 'remove' middleware includes model that was removed (#729) [timoxley] - -2.5.7 / 2012-02-09 -=================== - - * fixed; RegExp validators on node >= v0.6.x - -2.5.6 / 2012-02-09 -=================== - - * fixed; emit errors returned from db.collection() on the connection (were being swallowed) - * added; can add multiple validators in your schema at once (#718) [diogogmt] - * fixed; strict embedded documents (#717) - * updated; docs [niemyjski] - * added; pass number of affected docs back in model.update/save - -2.5.5 / 2012-02-03 -=================== - - * fixed; RangeError: maximum call stack exceed error when removing docs with Number _id (#714) - -2.5.4 / 2012-02-03 -=================== - - * fixed; RangeError: maximum call stack exceed error (#714) - -2.5.3 / 2012-02-02 -=================== - - * added; doc#isSelected(path) - * added; query#equals() - * added; beta sharding support - * added; more descript error msgs (#700) [obeleh] - * added; document.modifiedPaths (#709) [ljharb] - * fixed; only functions can be added as getters/setters (#707,704) [ljharb] - -2.5.2 / 2012-01-30 -=================== - - * fixed; rollback -native driver to 0.9.7-3-5 (was causing timeouts and other replica set weirdness) - * deprecated; MongooseNumber (will be moved to a separate repo for 3.x) - * added; init event is emitted on schemas - -2.5.1 / 2012-01-27 -=================== - - * fixed; honor strict schemas in Model.update (#699) - -2.5.0 / 2012-01-26 -=================== - - * added; doc.toJSON calls toJSON on embedded docs when exists [jerem] - * added; populate support for refs of type Buffer (#686) [jerem] - * added; $all support for ObjectIds and Dates (#690) - * fixed; virtual setter calling on instantiation when strict: true (#682) [hunterloftis] - * fixed; doc construction triggering getters (#685) - * fixed; MongooseBuffer check in deepEquals (#688) - * fixed; range error when using Number _ids with `instance.save()` (#691) - * fixed; isNew on embedded docs edge case (#680) - * updated; driver to 0.9.8-3 - * updated; expose `model()` method within static methods - -2.4.10 / 2012-01-10 -=================== - - * added; optional getter application in .toObject()/.toJSON() (#412) - * fixed; nested $operators in $all queries (#670) - * added; $nor support (#674) - * fixed; bug when adding nested schema (#662) [paulwe] - -2.4.9 / 2012-01-04 -=================== - - * updated; driver to 0.9.7-3-5 to fix Linux performance degradation on some boxes - -2.4.8 / 2011-12-22 -=================== - - * updated; bump -native to 0.9.7.2-5 - * fixed; compatibility with date.js (#646) [chrisleishman] - * changed; undocumented schema "lax" option to "strict" - * fixed; default value population for strict schemas - * updated; the nextTick helper for small performance gain. 1bee2a2 - -2.4.7 / 2011-12-16 -=================== - - * fixed; bug in 2.4.6 with path setting - * updated; bump -native to 0.9.7.2-1 - * added; strict schema option [nw] - -2.4.6 / 2011-12-16 -=================== - - * fixed; conflicting mods on update bug [sirlantis] - * improved; doc.id getter performance - -2.4.5 / 2011-12-14 -=================== - - * fixed; bad MongooseArray behavior in 2.4.2 - 2.4.4 - -2.4.4 / 2011-12-14 -=================== - - * fixed; MongooseArray#doAtomics throwing after sliced - -2.4.3 / 2011-12-14 -=================== - - * updated; system.profile schema for MongoDB 2x - -2.4.2 / 2011-12-12 -=================== - - * fixed; partially populating multiple children of subdocs (#639) [kenpratt] - * fixed; allow Update of numbers to null (#640) [jerem] - -2.4.1 / 2011-12-02 -=================== - - * added; options support for populate() queries - * updated; -native driver to 0.9.7-1.4 - -2.4.0 / 2011-11-29 -=================== - - * added; QueryStreams (#614) - * added; debug print mode for development - * added; $within support to Array queries (#586) [ggoodale] - * added; $centerSphere query support - * fixed; $within support - * added; $unset is now used when setting a path to undefined (#519) - * added; query#batchSize support - * updated; docs - * updated; -native driver to 0.9.7-1.3 (provides Windows support) - -2.3.13 / 2011-11-15 -=================== - - * fixed; required validation for Refs (#612) [ded] - * added; $nearSphere support for Arrays (#610) - -2.3.12 / 2011-11-09 -=================== - - * fixed; regression, objects passed to Model.update should not be changed (#605) - * fixed; regression, empty Model.update should not be executed - -2.3.11 / 2011-11-08 -=================== - - * fixed; using $elemMatch on arrays of Mixed types (#591) - * fixed; allow using $regex when querying Arrays (#599) - * fixed; calling Model.update with no atomic keys (#602) - -2.3.10 / 2011-11-05 -=================== - - * fixed; model.update casting for nested paths works (#542) - -2.3.9 / 2011-11-04 -================== - - * fixed; deepEquals check for MongooseArray returned false - * fixed; reset modified flags of embedded docs after save [gitfy] - * fixed; setting embedded doc with identical values no longer marks modified [gitfy] - * updated; -native driver to 0.9.6.23 [mlazarov] - * fixed; Model.update casting (#542, #545, #479) - * fixed; populated refs no longer fail required validators (#577) - * fixed; populating refs of objects with custom ids works - * fixed; $pop & $unset work with Model.update (#574) - * added; more helpful debugging message for Schema#add (#578) - * fixed; accessing .id when no _id exists now returns null (#590) - -2.3.8 / 2011-10-26 -================== - - * added; callback to query#findOne is now optional (#581) - -2.3.7 / 2011-10-24 -================== - - * fixed; wrapped save/remove callbacks in nextTick to mitigate -native swallowing thrown errors - -2.3.6 / 2011-10-21 -================== - - * fixed; exclusion of embedded doc _id from query results (#541) - -2.3.5 / 2011-10-19 -================== - - * fixed; calling queries without passing a callback works (#569) - * fixed; populate() works with String and Number _ids too (#568) - -2.3.4 / 2011-10-18 -================== - - * added; Model.create now accepts an array as a first arg - * fixed; calling toObject on a DocumentArray with nulls no longer throws - * fixed; calling inspect on a DocumentArray with nulls no longer throws - * added; MongooseArray#unshift support - * fixed; save hooks now fire on embedded documents [gitfy] (#456) - * updated; -native driver to 0.9.6-22 - * fixed; correctly pass $addToSet op instead of $push - * fixed; $addToSet properly detects dates - * fixed; $addToSet with multiple items works - * updated; better node 0.6 Buffer support - -2.3.3 / 2011-10-12 -================== - - * fixed; population conditions in multi-query settings [vedmalex] (#563) - * fixed; now compatible with Node v0.5.x - -2.3.2 / 2011-10-11 -================== - - * fixed; population of null subdoc properties no longer hangs (#561) - -2.3.1 / 2011-10-10 -================== - - * added; support for Query filters to populate() [eneko] - * fixed; querying with number no longer crashes mongodb (#555) [jlbyrey] - * updated; version of -native driver to 0.9.6-21 - * fixed; prevent query callbacks that throw errors from corrupting -native connection state - -2.3.0 / 2011-10-04 -================== - - * fixed; nulls as default values for Boolean now works as expected - * updated; version of -native driver to 0.9.6-20 - -2.2.4 / 2011-10-03 -================== - - * fixed; populate() works when returned array contains undefined/nulls - -2.2.3 / 2011-09-29 -================== - - * updated; version of -native driver to 0.9.6-19 - -2.2.2 / 2011-09-28 -================== - - * added; $regex support to String [davidandrewcope] - * added; support for other contexts like repl etc (#535) - * fixed; clear modified state properly after saving - * added; $addToSet support to Array - -2.2.1 / 2011-09-22 -================== - - * more descript error when casting undefined to string - * updated; version of -native driver to 0.9.6-18 - -2.2.0 / 2011-09-22 -================== - - * fixed; maxListeners warning on schemas with many arrays (#530) - * changed; return / apply defaults based on fields selected in query (#423) - * fixed; correctly detect Mixed types within schema arrays (#532) - -2.1.4 / 2011-09-20 -================== - - * fixed; new private methods that stomped on users code - * changed; finished removing old "compat" support which did nothing - -2.1.3 / 2011-09-16 -================== - - * updated; version of -native driver to 0.9.6-15 - * added; emit `error` on connection when open fails [edwardhotchkiss] - * added; index support to Buffers (thanks justmoon for helping track this down) - * fixed; passing collection name via schema in conn.model() now works (thanks vedmalex for reporting) - -2.1.2 / 2011-09-07 -================== - - * fixed; Query#find with no args no longer throws - -2.1.1 / 2011-09-07 -================== - - * added; support Model.count(fn) - * fixed; compatibility with node >=0.4.0 < 0.4.3 - * added; pass model.options.safe through with .save() so w:2, wtimeout:5000 options work [andrewjstone] - * added; support for $type queries - * added; support for Query#or - * added; more tests - * optimized populate queries - -2.1.0 / 2011-09-01 -================== - - * changed; document#validate is a public method - * fixed; setting number to same value no longer marks modified (#476) [gitfy] - * fixed; Buffers shouldn't have default vals - * added; allow specifying collection name in schema (#470) [ixti] - * fixed; reset modified paths and atomics after saved (#459) - * fixed; set isNew on embedded docs to false after save - * fixed; use self to ensure proper scope of options in doOpenSet (#483) [andrewjstone] - -2.0.4 / 2011-08-29 -================== - - * Fixed; Only send the depopulated ObjectId instead of the entire doc on save (DBRefs) - * Fixed; Properly cast nested array values in Model.update (the data was stored in Mongo incorrectly but recast on document fetch was "fixing" it) - -2.0.3 / 2011-08-28 -================== - - * Fixed; manipulating a populated array no longer causes infinite loop in BSON serializer during save (#477) - * Fixed; populating an empty array no longer hangs foreeeeeeeever (#481) - -2.0.2 / 2011-08-25 -================== - - * Fixed; Maintain query option key order (fixes 'bad hint' error from compound query hints) - -2.0.1 / 2011-08-25 -================== - - * Fixed; do not over-write the doc when no valide props exist in Model.update (#473) - -2.0.0 / 2011-08-24 -=================== - - * Added; support for Buffers [justmoon] - * Changed; improved error handling [maelstrom] - * Removed: unused utils.erase - * Fixed; support for passing other context object into Schemas (#234) [Sija] - * Fixed; getters are no longer circular refs to themselves (#366) - * Removed; unused compat.js - * Fixed; getter/setter scopes are set properly - * Changed; made several private properties more obvious by prefixing _ - * Added; DBRef support [guille] - * Changed; removed support for multiple collection names per model - * Fixed; no longer applying setters when document returned from db - * Changed; default auto_reconnect to true - * Changed; Query#bind no longer clones the query - * Fixed; Model.update now accepts $pull, $inc and friends (#404) - * Added; virtual type option support [nw] - -1.8.4 / 2011-08-21 -=================== - - * Fixed; validation bug when instantiated with non-schema properties (#464) [jmreidy] - -1.8.3 / 2011-08-19 -=================== - - * Fixed; regression in connection#open [jshaw86] - -1.8.2 / 2011-08-17 -=================== - - * fixed; reset connection.readyState after failure [tomseago] - * fixed; can now query positionally for non-embedded docs (arrays of numbers/strings etc) - * fixed; embedded document query casting - * added; support for passing options to node-mongo-native db, server, and replsetserver [tomseago] - -1.8.1 / 2011-08-10 -=================== - - * fixed; ObjectIds were always marked modified - * fixed; can now query using document instances - * fixed; can now query/update using documents with subdocs - -1.8.0 / 2011-08-04 -=================== - - * fixed; can now use $all with String and Number - * fixed; can query subdoc array with $ne: null - * fixed; instance.subdocs#id now works with custom _ids - * fixed; do not apply setters when doc returned from db (change in bad behavior) - -1.7.4 / 2011-07-25 -=================== - - * fixed; sparse now a valid seperate schema option - * fixed; now catching cast errors in queries - * fixed; calling new Schema with object created in vm.runInNewContext now works (#384) [Sija] - * fixed; String enum was disallowing null - * fixed; Find by nested document _id now works (#389) - -1.7.3 / 2011-07-16 -=================== - - * fixed; MongooseArray#indexOf now works with ObjectIds - * fixed; validation scope now set properly (#418) - * fixed; added missing colors dependency (#398) - -1.7.2 / 2011-07-13 -=================== - - * changed; node-mongodb-native driver to v0.9.6.7 - -1.7.1 / 2011-07-12 -=================== - - * changed; roll back node-mongodb-native driver to v0.9.6.4 - -1.7.0 / 2011-07-12 -=================== - - * fixed; collection name misspelling [mathrawka] - * fixed; 2nd param is required for ReplSetServers [kevinmarvin] - * fixed; MongooseArray behaves properly with Object.keys - * changed; node-mongodb-native driver to v0.9.6.6 - * fixed/changed; Mongodb segfault when passed invalid ObjectId (#407) - - This means invalid data passed to the ObjectId constructor will now error - -1.6.0 / 2011-07-07 -=================== - - * changed; .save() errors are now emitted on the instances db instead of the instance 9782463fc - * fixed; errors occurring when creating indexes now properly emit on db - * added; $maxDistance support to MongooseArrays - * fixed; RegExps now work with $all - * changed; node-mongodb-native driver to v0.9.6.4 - * fixed; model names are now accessible via .modelName - * added; Query#slaveOk support - -1.5.0 / 2011-06-27 -=================== - - * changed; saving without a callback no longer ignores the error (@bnoguchi) - * changed; hook-js version bump to 0.1.9 - * changed; node-mongodb-native version bumped to 0.9.6.1 - When .remove() doesn't - return an error, null is no longer passed. - * fixed; two memory leaks (@justmoon) - * added; sparse index support - * added; more ObjectId conditionals (gt, lt, gte, lte) (@phillyqueso) - * added; options are now passed in model#remote (@JerryLuke) - -1.4.0 / 2011-06-10 -=================== - - * bumped hooks-js dependency (fixes issue passing null as first arg to next()) - * fixed; document#inspect now works properly with nested docs - * fixed; 'set' now works as a schema attribute (GH-365) - * fixed; _id is now set properly within pre-init hooks (GH-289) - * added; Query#distinct / Model#distinct support (GH-155) - * fixed; embedded docs now can use instance methods (GH-249) - * fixed; can now overwrite strings conflicting with schema type - -1.3.7 / 2011-06-03 -=================== - - * added MongooseArray#splice support - * fixed; 'path' is now a valid Schema pathname - * improved hooks (utilizing https://github.com/bnoguchi/hooks-js) - * fixed; MongooseArray#$shift now works (never did) - * fixed; Document.modified no longer throws - * fixed; modifying subdoc property sets modified paths for subdoc and parent doc - * fixed; marking subdoc path as modified properly persists the value to the db - * fixed; RexExps can again be saved ( #357 ) - -1.3.6 / 2011-05-18 -=================== - - * fixed; corrected casting for queries against array types - * added; Document#set now accepts Document instances - -1.3.5 / 2011-05-17 -=================== - - * fixed; $ne queries work properly with single vals - * added; #inspect() methods to improve console.log output - -1.3.4 / 2011-05-17 -=================== - - * fixed; find by Date works as expected (#336) - * added; geospatial 2d index support - * added; support for $near (#309) - * updated; node-mongodb-native driver - * fixed; updating numbers work (#342) - * added; better error msg when try to remove an embedded doc without an _id (#307) - * added; support for 'on-the-fly' schemas (#227) - * changed; virtual id getters can now be skipped - * fixed; .index() called on subdoc schema now works as expected - * fixed; db.setProfile() now buffers until the db is open (#340) - -1.3.3 / 2011-04-27 -=================== - - * fixed; corrected query casting on nested mixed types - -1.3.2 / 2011-04-27 -=================== - - * fixed; query hints now retain key order - -1.3.1 / 2011-04-27 -=================== - - * fixed; setting a property on an embedded array no longer overwrites entire array (GH-310) - * fixed; setting nested properties works when sibling prop is named "type" - * fixed; isModified is now much finer grained when .set() is used (GH-323) - * fixed; mongoose.model() and connection.model() now return the Model (GH-308, GH-305) - * fixed; can now use $gt, $lt, $gte, $lte with String schema types (GH-317) - * fixed; .lowercase() -> .toLowerCase() in pluralize() - * fixed; updating an embedded document by index works (GH-334) - * changed; .save() now passes the instance to the callback (GH-294, GH-264) - * added; can now query system.profile and system.indexes collections - * added; db.model('system.profile') is now included as a default Schema - * added; db.setProfiling(level, ms, callback) - * added; Query#hint() support - * added; more tests - * updated node-mongodb-native to 0.9.3 - -1.3.0 / 2011-04-19 -=================== - - * changed; save() callbacks now fire only once on failed validation - * changed; Errors returned from save() callbacks now instances of ValidationError - * fixed; MongooseArray#indexOf now works properly - -1.2.0 / 2011-04-11 -=================== - - * changed; MongooseNumber now casts empty string to null - -1.1.25 / 2011-04-08 -=================== - - * fixed; post init now fires at proper time - -1.1.24 / 2011-04-03 -=================== - - * fixed; pushing an array onto an Array works on existing docs - -1.1.23 / 2011-04-01 -=================== - - * Added Model#model - -1.1.22 / 2011-03-31 -=================== - - * Fixed; $in queries on mixed types now work - -1.1.21 / 2011-03-31 -=================== - - * Fixed; setting object root to null/undefined works - -1.1.20 / 2011-03-31 -=================== - - * Fixed; setting multiple props on null field works - -1.1.19 / 2011-03-31 -=================== - - * Fixed; no longer using $set on paths to an unexisting fields - -1.1.18 / 2011-03-30 -=================== - - * Fixed; non-mixed type object setters work after initd from null - -1.1.17 / 2011-03-30 -=================== - - * Fixed; nested object property access works when root initd with null value - -1.1.16 / 2011-03-28 -=================== - - * Fixed; empty arrays are now saved - -1.1.15 / 2011-03-28 -=================== - - * Fixed; `null` and `undefined` are set atomically. - -1.1.14 / 2011-03-28 -=================== - - * Changed; more forgiving date casting, accepting '' as null. - -1.1.13 / 2011-03-26 -=================== - - * Fixed setting values as `undefined`. - -1.1.12 / 2011-03-26 -=================== - - * Fixed; nested objects now convert to JSON properly - * Fixed; setting nested objects directly now works - * Update node-mongodb-native - -1.1.11 / 2011-03-25 -=================== - - * Fixed for use of `type` as a key. - -1.1.10 / 2011-03-23 -=================== - - * Changed; Make sure to only ensure indexes while connected - -1.1.9 / 2011-03-2 -================== - - * Fixed; Mixed can now default to empty arrays - * Fixed; keys by the name 'type' are now valid - * Fixed; null values retrieved from the database are hydrated as null values. - * Fixed repeated atomic operations when saving a same document twice. - -1.1.8 / 2011-03-23 -================== - - * Fixed 'id' overriding. [bnoguchi] - -1.1.7 / 2011-03-22 -================== - - * Fixed RegExp query casting when querying against an Array of Strings [bnoguchi] - * Fixed getters/setters for nested virtualsl. [bnoguchi] - -1.1.6 / 2011-03-22 -================== - - * Only doValidate when path exists in Schema [aheckmann] - * Allow function defaults for Array types [aheckmann] - * Fix validation hang [aheckmann] - * Fix setting of isRequired of SchemaType [aheckmann] - * Fix SchemaType#required(false) filter [aheckmann] - * More backwards compatibility [aheckmann] - * More tests [aheckmann] - -1.1.5 / 2011-03-14 -================== - - * Added support for `uri, db, fn` and `uri, fn` signatures for replica sets. - * Improved/extended replica set tests. - -1.1.4 / 2011-03-09 -================== - - * Fixed; running an empty Query doesn't throw. [aheckmann] - * Changed; Promise#addBack returns promise. [aheckmann] - * Added streaming cursor support. [aheckmann] - * Changed; Query#update defaults to use$SetOnSave now. [brian] - * Added more docs. - -1.1.3 / 2011-03-04 -================== - - * Added Promise#resolve [aheckmann] - * Fixed backward compatibility with nulls [aheckmann] - * Changed; Query#{run,exec} return promises [aheckmann] - -1.1.2 / 2011-03-03 -================== - - * Restored Query#exec and added notion of default operation [brian] - * Fixed ValidatorError messages [brian] - -1.1.1 / 2011-03-01 -================== - - * Added SchemaType String `lowercase`, `uppercase`, `trim`. - * Public exports (`Model`, `Document`) and tests. - * Added ObjectId casting support for `Document`s. - -1.1.0 / 2011-02-25 -================== - - * Added support for replica sets. - -1.0.16 / 2011-02-18 -=================== - - * Added $nin as another whitelisted $conditional for SchemaArray [brian] - * Changed #with to #where [brian] - * Added ability to use $in conditional with Array types [brian] - -1.0.15 / 2011-02-18 -=================== - - * Added `id` virtual getter for documents to easily access the hexString of - the `_id`. - -1.0.14 / 2011-02-17 -=================== - - * Fix for arrays within subdocuments [brian] - -1.0.13 / 2011-02-16 -=================== - - * Fixed embedded documents saving. - -1.0.12 / 2011-02-14 -=================== - - * Minor refactorings [brian] - -1.0.11 / 2011-02-14 -=================== - - * Query refactor and $ne, $slice, $or, $size, $elemMatch, $nin, $exists support [brian] - * Named scopes sugar [brian] - -1.0.10 / 2011-02-11 -=================== - - * Updated node-mongodb-native driver [thanks John Allen] - -1.0.9 / 2011-02-09 -================== - - * Fixed single member arrays as defaults [brian] - -1.0.8 / 2011-02-09 -================== - - * Fixed for collection-level buffering of commands [gitfy] - * Fixed `Document#toJSON` [dalejefferson] - * Fixed `Connection` authentication [robrighter] - * Fixed clash of accessors in getters/setters [eirikurn] - * Improved `Model#save` promise handling - -1.0.7 / 2011-02-05 -================== - - * Fixed memory leak warnings for test suite on 0.3 - * Fixed querying documents that have an array that contain at least one - specified member. [brian] - * Fixed default value for Array types (fixes GH-210). [brian] - * Fixed example code. - -1.0.6 / 2011-02-03 -================== - - * Fixed `post` middleware - * Fixed; it's now possible to instantiate a model even when one of the paths maps - to an undefined value [brian] - -1.0.5 / 2011-02-02 -================== - - * Fixed; combo $push and $pushAll auto-converts into a $pushAll [brian] - * Fixed; combo $pull and $pullAll auto-converts to a single $pullAll [brian] - * Fixed; $pullAll now removes said members from array before save (so it acts just - like pushAll) [brian] - * Fixed; multiple $pulls and $pushes become a single $pullAll and $pushAll. - Moreover, $pull now modifies the array before save to reflect the immediate - change [brian] - * Added tests for nested shortcut getters [brian] - * Added tests that show that Schemas with nested Arrays don't apply defaults - [brian] - -1.0.4 / 2011-02-02 -================== - - * Added MongooseNumber#toString - * Added MongooseNumber unit tests - -1.0.3 / 2011-02-02 -================== - - * Make sure safe mode works with Model#save - * Changed Schema options: safe mode is now the default - * Updated node-mongodb-native to HEAD - -1.0.2 / 2011-02-02 -================== - - * Added a Model.create shortcut for creating documents. [brian] - * Fixed; we can now instantiate models with hashes that map to at least one - null value. [brian] - * Fixed Schema with more than 2 nested levels. [brian] - -1.0.1 / 2011-02-02 -================== - - * Improved `MongooseNumber`, works almost like the native except for `typeof` - not being `'number'`. diff --git a/node_modules/mongoose/README.md b/node_modules/mongoose/README.md deleted file mode 100644 index 24ae49d40..000000000 --- a/node_modules/mongoose/README.md +++ /dev/null @@ -1,271 +0,0 @@ -# Mongoose - -Mongoose is a [MongoDB](http://www.mongodb.org/) object modeling tool designed to work in an asynchronous environment. - -[![Build Status](https://travis-ci.org/LearnBoost/mongoose.png?branch=3.8.x)](https://travis-ci.org/LearnBoost/mongoose) - -## Documentation - -[mongoosejs.com](http://mongoosejs.com/) - -## Support - - - [Stack Overflow](http://stackoverflow.com/questions/tagged/mongoose) - - [bug reports](https://github.com/learnboost/mongoose/issues/) - - [help forum](http://groups.google.com/group/mongoose-orm) - - [MongoDB support](http://www.mongodb.org/display/DOCS/Technical+Support) - - (irc) #mongoosejs on freenode - -## Plugins - -Check out the [plugins search site](http://plugins.mongoosejs.com/) to see hundreds of related modules from the community. - -## Contributors - -View all 100+ [contributors](https://github.com/learnboost/mongoose/graphs/contributors). Stand up and be counted as a [contributor](https://github.com/LearnBoost/mongoose/blob/master/CONTRIBUTING.md) too! - -## Live Examples - - -## Installation - -First install [node.js](http://nodejs.org/) and [mongodb](http://www.mongodb.org/downloads). Then: - - $ npm install mongoose - -## Stability - -The current stable branch is [3.8.x](https://github.com/LearnBoost/mongoose/tree/3.8.x). New (unstable) development always occurs on the [master](https://github.com/LearnBoost/mongoose/tree/master) branch. - -## Overview - -### Connecting to MongoDB - -First, we need to define a connection. If your app uses only one database, you should use `mongoose.connect`. If you need to create additional connections, use `mongoose.createConnection`. - -Both `connect` and `createConnection` take a `mongodb://` URI, or the parameters `host, database, port, options`. - - var mongoose = require('mongoose'); - - mongoose.connect('mongodb://localhost/my_database'); - -Once connected, the `open` event is fired on the `Connection` instance. If you're using `mongoose.connect`, the `Connection` is `mongoose.connection`. Otherwise, `mongoose.createConnection` return value is a `Connection`. - -**Important!** Mongoose buffers all the commands until it's connected to the database. This means that you don't have to wait until it connects to MongoDB in order to define models, run queries, etc. - -### Defining a Model - -Models are defined through the `Schema` interface. - - var Schema = mongoose.Schema - , ObjectId = Schema.ObjectId; - - var BlogPost = new Schema({ - author : ObjectId - , title : String - , body : String - , date : Date - }); - -Aside from defining the structure of your documents and the types of data you're storing, a Schema handles the definition of: - -* [Validators](http://mongoosejs.com/docs/validation.html) (async and sync) -* [Defaults](http://mongoosejs.com/docs/api.html#schematype_SchemaType-default) -* [Getters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-get) -* [Setters](http://mongoosejs.com/docs/api.html#schematype_SchemaType-set) -* [Indexes](http://mongoosejs.com/docs/guide.html#indexes) -* [Middleware](http://mongoosejs.com/docs/middleware.html) -* [Methods](http://mongoosejs.com/docs/guide.html#methods) definition -* [Statics](http://mongoosejs.com/docs/guide.html#statics) definition -* [Plugins](http://mongoosejs.com/docs/plugins.html) -* [pseudo-JOINs](http://mongoosejs.com/docs/populate.html) - -The following example shows some of these features: - - var Comment = new Schema({ - name : { type: String, default: 'hahaha' } - , age : { type: Number, min: 18, index: true } - , bio : { type: String, match: /[a-z]/ } - , date : { type: Date, default: Date.now } - , buff : Buffer - }); - - // a setter - Comment.path('name').set(function (v) { - return capitalize(v); - }); - - // middleware - Comment.pre('save', function (next) { - notify(this.get('email')); - next(); - }); - -Take a look at the example in `examples/schema.js` for an end-to-end example of a typical setup. - -### Accessing a Model - -Once we define a model through `mongoose.model('ModelName', mySchema)`, we can access it through the same function - - var myModel = mongoose.model('ModelName'); - -Or just do it all at once - - var MyModel = mongoose.model('ModelName', mySchema); - -We can then instantiate it, and save it: - - var instance = new MyModel(); - instance.my.key = 'hello'; - instance.save(function (err) { - // - }); - -Or we can find documents from the same collection - - MyModel.find({}, function (err, docs) { - // docs.forEach - }); - -You can also `findOne`, `findById`, `update`, etc. For more details check out [the docs](http://mongoosejs.com/docs/queries.html). - -**Important!** If you opened a separate connection using `mongoose.createConnection()` but attempt to access the model through `mongoose.model('ModelName')` it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created: - - var conn = mongoose.createConnection('your connection string'); - var MyModel = conn.model('ModelName', schema); - var m = new MyModel; - m.save() // works - - vs - - var conn = mongoose.createConnection('your connection string'); - var MyModel = mongoose.model('ModelName', schema); - var m = new MyModel; - m.save() // does not work b/c the default connection object was never connected - -### Embedded Documents - -In the first example snippet, we defined a key in the Schema that looks like: - - comments: [Comments] - -Where `Comments` is a `Schema` we created. This means that creating embedded documents is as simple as: - - // retrieve my model - var BlogPost = mongoose.model('BlogPost'); - - // create a blog post - var post = new BlogPost(); - - // create a comment - post.comments.push({ title: 'My comment' }); - - post.save(function (err) { - if (!err) console.log('Success!'); - }); - -The same goes for removing them: - - BlogPost.findById(myId, function (err, post) { - if (!err) { - post.comments[0].remove(); - post.save(function (err) { - // do something - }); - } - }); - -Embedded documents enjoy all the same features as your models. Defaults, validators, middleware. Whenever an error occurs, it's bubbled to the `save()` error callback, so error handling is a snap! - -Mongoose interacts with your embedded documents in arrays _atomically_, out of the box. - -### Middleware - -See the [docs](http://mongoosejs.com/docs/middleware.html) page. - -#### Intercepting and mutating method arguments - -You can intercept method arguments via middleware. - -For example, this would allow you to broadcast changes about your Documents every time someone `set`s a path in your Document to a new value: - - schema.pre('set', function (next, path, val, typel) { - // `this` is the current Document - this.emit('set', path, val); - - // Pass control to the next pre - next(); - }); - -Moreover, you can mutate the incoming `method` arguments so that subsequent middleware see different values for those arguments. To do so, just pass the new values to `next`: - - .pre(method, function firstPre (next, methodArg1, methodArg2) { - // Mutate methodArg1 - next("altered-" + methodArg1.toString(), methodArg2); - }) - - // pre declaration is chainable - .pre(method, function secondPre (next, methodArg1, methodArg2) { - console.log(methodArg1); - // => 'altered-originalValOfMethodArg1' - - console.log(methodArg2); - // => 'originalValOfMethodArg2' - - // Passing no arguments to `next` automatically passes along the current argument values - // i.e., the following `next()` is equivalent to `next(methodArg1, methodArg2)` - // and also equivalent to, with the example method arg - // values, `next('altered-originalValOfMethodArg1', 'originalValOfMethodArg2')` - next(); - }) - -#### Schema gotcha - -`type`, when used in a schema has special meaning within Mongoose. If your schema requires using `type` as a nested property you must use object notation: - - new Schema({ - broken: { type: Boolean } - , asset : { - name: String - , type: String // uh oh, it broke. asset will be interpreted as String - } - }); - - new Schema({ - works: { type: Boolean } - , asset : { - name: String - , type: { type: String } // works. asset is an object with a type property - } - }); - -### Driver access - -The driver being used defaults to [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) and is directly accessible through `YourModel.collection`. **Note**: using the driver directly bypasses all Mongoose power-tools like validation, getters, setters, hooks, etc. - -## API Docs - -Find the API docs [here](http://mongoosejs.com/docs/api.html), generated using [dox](http://github.com/visionmedia/dox). - -## License - -Copyright (c) 2010 LearnBoost <dev@learnboost.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/contRun.sh b/node_modules/mongoose/contRun.sh deleted file mode 100644 index cd5610d9b..000000000 --- a/node_modules/mongoose/contRun.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/bash - -make test - -ret=$? - -while [ $ret == 0 ]; do - make test - ret=$? -done diff --git a/node_modules/mongoose/examples/README.md b/node_modules/mongoose/examples/README.md deleted file mode 100644 index cb32898e8..000000000 --- a/node_modules/mongoose/examples/README.md +++ /dev/null @@ -1,41 +0,0 @@ -This directory contains runnable sample mongoose programs. - -To run: - - - first install [Node.js](http://nodejs.org/) - - from the root of the project, execute `npm install -d` - - in the example directory, run `npm install -d` - - from the command line, execute: `node example.js`, replacing "example.js" with the name of a program. - - -Goal is to show: - -- ~~global schemas~~ -- ~~GeoJSON schemas / use (with crs)~~ -- text search (once MongoDB removes the "Experimental/beta" label) -- ~~lean queries~~ -- ~~statics~~ -- methods and statics on subdocs -- custom types -- ~~querybuilder~~ -- ~~promises~~ -- accessing driver collection, db -- ~~connecting to replica sets~~ -- connecting to sharded clusters -- enabling a fail fast mode -- on the fly schemas -- storing files -- ~~map reduce~~ -- ~~aggregation~~ -- advanced hooks -- using $elemMatch to return a subset of an array -- query casting -- upserts -- pagination -- express + mongoose session handling -- ~~group by (use aggregation)~~ -- authentication -- schema migration techniques -- converting documents to plain objects (show transforms) -- how to $unset - diff --git a/node_modules/mongoose/examples/aggregate/aggregate.js b/node_modules/mongoose/examples/aggregate/aggregate.js deleted file mode 100644 index e58d25dd9..000000000 --- a/node_modules/mongoose/examples/aggregate/aggregate.js +++ /dev/null @@ -1,78 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)), gender : "Male", - likes : ['movies', 'games', 'dogs']}, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)), gender : "Female", - likes : ['movies', 'birds', 'cats']}, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)), gender : "Male", - likes : ['tv', 'games', 'rabbits']}, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)), gender : "Female", - likes : ['books', 'cats', 'dogs']}, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)), gender : "Male", - likes : ['glasses', 'wine', 'the night']}, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // run an aggregate query that will get all of the people who like a given - // item. To see the full documentation on ways to use the aggregate - // framework, see http://docs.mongodb.org/manual/core/aggregation/ - Person.aggregate( - // select the fields we want to deal with - { $project : { name : 1, likes : 1 } }, - // unwind 'likes', which will create a document for each like - { $unwind : "$likes" }, - // group everything by the like and then add each name with that like to - // the set for the like - { $group : { - _id : { likes : "$likes" }, - likers : { $addToSet : "$name" } - } }, - function (err, result) { - if (err) throw err; - console.log(result); - //[ { _id: { likes: 'the night' }, likers: [ 'alucard' ] }, - //{ _id: { likes: 'wine' }, likers: [ 'alucard' ] }, - //{ _id: { likes: 'books' }, likers: [ 'lilly' ] }, - //{ _id: { likes: 'glasses' }, likers: [ 'alucard' ] }, - //{ _id: { likes: 'birds' }, likers: [ 'mary' ] }, - //{ _id: { likes: 'rabbits' }, likers: [ 'bob' ] }, - //{ _id: { likes: 'cats' }, likers: [ 'lilly', 'mary' ] }, - //{ _id: { likes: 'dogs' }, likers: [ 'lilly', 'bill' ] }, - //{ _id: { likes: 'tv' }, likers: [ 'bob' ] }, - //{ _id: { likes: 'games' }, likers: [ 'bob', 'bill' ] }, - //{ _id: { likes: 'movies' }, likers: [ 'mary', 'bill' ] } ] - - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/aggregate/package.json b/node_modules/mongoose/examples/aggregate/package.json deleted file mode 100644 index 53ed2e14b..000000000 --- a/node_modules/mongoose/examples/aggregate/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "aggregate-example", - "private": "true", - "version": "0.0.0", - "description": "deps for aggregate example", - "main": "aggregate.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/aggregate/person.js b/node_modules/mongoose/examples/aggregate/person.js deleted file mode 100644 index 5046b1fe1..000000000 --- a/node_modules/mongoose/examples/aggregate/person.js +++ /dev/null @@ -1,17 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date, - gender: String, - likes: [String] - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/doc-methods.js b/node_modules/mongoose/examples/doc-methods.js deleted file mode 100644 index 373a46be2..000000000 --- a/node_modules/mongoose/examples/doc-methods.js +++ /dev/null @@ -1,70 +0,0 @@ - -var mongoose = require('mongoose') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Schema - */ - -var CharacterSchema = Schema({ - name: { type: String, required: true } - , health: { type: Number, min: 0, max: 100 } -}) - -/** - * Methods - */ - -CharacterSchema.methods.attack = function () { - console.log('%s is attacking', this.name); -} - -/** - * Character model - */ - -var Character = mongoose.model('Character', CharacterSchema); - -/** - * Connect to the database on localhost with - * the default port (27017) - */ - -var dbname = 'mongoose-example-doc-methods-' + ((Math.random()*10000)|0); -var uri = 'mongodb://localhost/' + dbname; - -console.log('connecting to %s', uri); - -mongoose.connect(uri, function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - example(); -}) - -/** - * Use case - */ - -function example () { - Character.create({ name: 'Link', health: 100 }, function (err, link) { - if (err) return done(err); - console.log('found', link); - link.attack(); // 'Link is attacking' - done(); - }) -} - -/** - * Clean up - */ - -function done (err) { - if (err) console.error(err); - mongoose.connection.db.dropDatabase(function () { - mongoose.disconnect(); - }) -} diff --git a/node_modules/mongoose/examples/express/README.md b/node_modules/mongoose/examples/express/README.md deleted file mode 100644 index 7ba07b8ab..000000000 --- a/node_modules/mongoose/examples/express/README.md +++ /dev/null @@ -1 +0,0 @@ -Mongoose + Express examples diff --git a/node_modules/mongoose/examples/express/connection-sharing/README.md b/node_modules/mongoose/examples/express/connection-sharing/README.md deleted file mode 100644 index fc709a3ab..000000000 --- a/node_modules/mongoose/examples/express/connection-sharing/README.md +++ /dev/null @@ -1,6 +0,0 @@ - -To run: - -- Execute `npm install` from this directory -- Execute `node app.js` -- Navigate to `localhost:8000` diff --git a/node_modules/mongoose/examples/express/connection-sharing/app.js b/node_modules/mongoose/examples/express/connection-sharing/app.js deleted file mode 100644 index fe3332c26..000000000 --- a/node_modules/mongoose/examples/express/connection-sharing/app.js +++ /dev/null @@ -1,18 +0,0 @@ - -var express = require('express') -var mongoose = require('../../../lib') - -var uri = 'mongodb://localhost/mongoose-shared-connection'; -global.db = mongoose.createConnection(uri); - -var routes = require('./routes') - -var app = express(); -app.get('/', routes.home); -app.get('/insert', routes.insert); -app.get('/name', routes.modelName); - -app.listen(8000, function () { - console.log('listening on http://localhost:8000'); -}) - diff --git a/node_modules/mongoose/examples/express/connection-sharing/modelA.js b/node_modules/mongoose/examples/express/connection-sharing/modelA.js deleted file mode 100644 index a38716108..000000000 --- a/node_modules/mongoose/examples/express/connection-sharing/modelA.js +++ /dev/null @@ -1,6 +0,0 @@ - -var Schema = require('../../../lib').Schema; -var mySchema = Schema({ name: String }); - -// db is global -module.exports = db.model('MyModel', mySchema); diff --git a/node_modules/mongoose/examples/express/connection-sharing/package.json b/node_modules/mongoose/examples/express/connection-sharing/package.json deleted file mode 100644 index e32616553..000000000 --- a/node_modules/mongoose/examples/express/connection-sharing/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "connection-sharing", - "private": "true", - "version": "0.0.0", - "description": "ERROR: No README.md file found!", - "main": "app.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "express": "3.1.1" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/express/connection-sharing/routes.js b/node_modules/mongoose/examples/express/connection-sharing/routes.js deleted file mode 100644 index d8fe8bf2f..000000000 --- a/node_modules/mongoose/examples/express/connection-sharing/routes.js +++ /dev/null @@ -1,20 +0,0 @@ - -var model = require('./modelA') - -exports.home = function (req, res, next) { - model.find(function (err, docs) { - if (err) return next(err); - res.send(docs); - }) -} - -exports.modelName = function (req, res) { - res.send('my model name is ' + model.modelName); -} - -exports.insert = function (req, res, next) { - model.create({ name: 'inserting ' + Date.now() }, function (err, doc) { - if (err) return next(err); - res.send(doc); - }) -} diff --git a/node_modules/mongoose/examples/geospatial/geoJSONSchema.js b/node_modules/mongoose/examples/geospatial/geoJSONSchema.js deleted file mode 100644 index e9ad28d98..000000000 --- a/node_modules/mongoose/examples/geospatial/geoJSONSchema.js +++ /dev/null @@ -1,22 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - // NOTE : This object must conform *precisely* to the geoJSON specification - // you cannot embed a geoJSON doc inside a model or anything like that- IT - // MUST BE VANILLA - var LocationObject = new Schema({ - loc: { - type: { type: String }, - coordinates: [] - } - }); - // define the index - LocationObject.index({ loc : '2dsphere' }); - - mongoose.model('Location', LocationObject); -}; diff --git a/node_modules/mongoose/examples/geospatial/geoJSONexample.js b/node_modules/mongoose/examples/geospatial/geoJSONexample.js deleted file mode 100644 index b1c919981..000000000 --- a/node_modules/mongoose/examples/geospatial/geoJSONexample.js +++ /dev/null @@ -1,49 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./geoJSONSchema.js')(); - -var Location = mongoose.model('Location'); - -// define some dummy data -// note: the type can be Point, LineString, or Polygon -var data = [ - { loc: { type: 'Point', coordinates: [-20.0, 5.0] }}, - { loc: { type: 'Point', coordinates: [6.0, 10.0] }}, - { loc: { type: 'Point', coordinates: [34.0, -50.0] }}, - { loc: { type: 'Point', coordinates: [-100.0, 70.0] }}, - { loc: { type: 'Point', coordinates: [38.0, 38.0] }} -]; - - -mongoose.connect('mongodb://localhost/locations', function (err) { - if (err) throw err; - - Location.on('index', function(err) { - if (err) throw err; - // create all of the dummy locations - async.each(data, function (item, cb) { - Location.create(item, cb); - }, function (err) { - if (err) throw err; - // create the location we want to search for - var coords = { type : 'Point', coordinates : [-5, 5] }; - // search for it - Location.find({ loc : { $near : coords }}).limit(1).exec(function(err, res) { - if (err) throw err; - console.log("Closest to %s is %s", JSON.stringify(coords), res); - cleanup(); - }); - }); - }); -}); - -function cleanup() { - Location.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/geospatial/geospatial.js b/node_modules/mongoose/examples/geospatial/geospatial.js deleted file mode 100644 index bec89e374..000000000 --- a/node_modules/mongoose/examples/geospatial/geospatial.js +++ /dev/null @@ -1,67 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)), gender : "Male", - likes : ['movies', 'games', 'dogs'], loc : [0, 0]}, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)), gender : "Female", - likes : ['movies', 'birds', 'cats'], loc : [1, 1]}, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)), gender : "Male", - likes : ['tv', 'games', 'rabbits'], loc : [3, 3]}, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)), gender : "Female", - likes : ['books', 'cats', 'dogs'], loc : [6, 6]}, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)), gender : "Male", - likes : ['glasses', 'wine', 'the night'], loc : [10, 10]}, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // let's find the closest person to bob - Person.find({ name : 'bob' }, function (err, res) { - if (err) throw err; - - res[0].findClosest(function (err, closest) { - if (err) throw err; - - console.log("%s is closest to %s", res[0].name, closest); - - - // we can also just query straight off of the model. For more - // information about geospatial queries and indexes, see - // http://docs.mongodb.org/manual/applications/geospatial-indexes/ - var coords = [7,7]; - Person.find({ loc : { $nearSphere : coords }}).limit(1).exec(function(err, res) { - console.log("Closest to %s is %s", coords, res); - cleanup(); - }); - }); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/geospatial/package.json b/node_modules/mongoose/examples/geospatial/package.json deleted file mode 100644 index 75c2a0eef..000000000 --- a/node_modules/mongoose/examples/geospatial/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "geospatial-example", - "private": "true", - "version": "0.0.0", - "description": "deps for geospatial example", - "main": "geospatial.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/geospatial/person.js b/node_modules/mongoose/examples/geospatial/person.js deleted file mode 100644 index c84273e59..000000000 --- a/node_modules/mongoose/examples/geospatial/person.js +++ /dev/null @@ -1,28 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date, - gender: String, - likes: [String], - // define the geospatial field - loc: { type : [Number], index: '2d' } - }); - - // define a method to find the closest person - PersonSchema.methods.findClosest = function(cb) { - return this.model('Person').find({ - loc : { $nearSphere : this.loc }, - name : { $ne : this.name } - }).limit(1).exec(cb); - }; - - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/globalschemas/gs_example.js b/node_modules/mongoose/examples/globalschemas/gs_example.js deleted file mode 100644 index 547c6e7d8..000000000 --- a/node_modules/mongoose/examples/globalschemas/gs_example.js +++ /dev/null @@ -1,40 +0,0 @@ - -var mongoose = require('../../lib'); - - -// import the global schema, this can be done in any file that needs the model -require('./person.js')(); - -// grab the person model object -var Person = mongoose.model("Person"); - -// connect to a server to do a quick write / read example - -mongoose.connect('mongodb://localhost/persons', function(err) { - if (err) throw err; - - Person.create({ - name : 'bill', - age : 25, - birthday : new Date().setFullYear((new Date().getFullYear() - 25)) - }, function (err, bill) { - if (err) throw err; - console.log("People added to db: %s", bill.toString()); - Person.find({}, function(err, people) { - if (err) throw err; - - people.forEach(function(person) { - console.log("People in the db: %s", person.toString()); - }); - - // make sure to clean things up after we're done - setTimeout(function () { cleanup(); }, 2000); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/globalschemas/person.js b/node_modules/mongoose/examples/globalschemas/person.js deleted file mode 100644 index f9c9a27ab..000000000 --- a/node_modules/mongoose/examples/globalschemas/person.js +++ /dev/null @@ -1,15 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/lean/lean.js b/node_modules/mongoose/examples/lean/lean.js deleted file mode 100644 index 6780f1630..000000000 --- a/node_modules/mongoose/examples/lean/lean.js +++ /dev/null @@ -1,61 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)), gender : "Male", - likes : ['movies', 'games', 'dogs']}, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)), gender : "Female", - likes : ['movies', 'birds', 'cats']}, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)), gender : "Male", - likes : ['tv', 'games', 'rabbits']}, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)), gender : "Female", - likes : ['books', 'cats', 'dogs']}, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)), gender : "Male", - likes : ['glasses', 'wine', 'the night']}, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // lean queries return just plain javascript objects, not - // MongooseDocuments. This makes them good for high performance read - // situations - - // when using .lean() the default is true, but you can explicitly set the - // value by passing in a boolean value. IE. .lean(false) - var q = Person.find({ age : { $lt : 1000 }}).sort('age').limit(2).lean(); - q.exec(function (err, results) { - if (err) throw err; - console.log("Are the results MongooseDocuments?: %s", results[0] instanceof mongoose.Document); - - console.log(results); - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/lean/package.json b/node_modules/mongoose/examples/lean/package.json deleted file mode 100644 index 6ee511de7..000000000 --- a/node_modules/mongoose/examples/lean/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "lean-example", - "private": "true", - "version": "0.0.0", - "description": "deps for lean example", - "main": "lean.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/lean/person.js b/node_modules/mongoose/examples/lean/person.js deleted file mode 100644 index 5046b1fe1..000000000 --- a/node_modules/mongoose/examples/lean/person.js +++ /dev/null @@ -1,17 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date, - gender: String, - likes: [String] - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/mapreduce/mapreduce.js b/node_modules/mongoose/examples/mapreduce/mapreduce.js deleted file mode 100644 index 52d16f2b9..000000000 --- a/node_modules/mongoose/examples/mapreduce/mapreduce.js +++ /dev/null @@ -1,77 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)), gender : "Male" }, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)), gender : "Female" }, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)), gender : "Male" }, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)), gender : "Female" }, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)), gender : "Male" }, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // alright, simple map reduce example. We will find the total ages of each - // gender - - // create the options object - var o = {}; - - o.map = function () { - // in this function, 'this' refers to the current document being - // processed. Return the (gender, age) tuple using emit() - emit(this.gender, this.age); - }; - - // the reduce function receives the array of ages that are grouped by the - // id, which in this case is the gender - o.reduce = function (id, ages) { - return Array.sum(ages); - }; - - // other options that can be specified - - // o.query = { age : { $lt : 1000 }}; // the query object - // o.limit = 3; // max number of documents - // o.keeptemp = true; // default is false, specifies whether to keep temp data - // o.finalize = someFunc; // function called after reduce - // o.scope = {}; // the scope variable exposed to map/reduce/finalize - // o.jsMode = true; // default is false, force execution to stay in JS - o.verbose = true; // default is false, provide stats on the job - // o.out = {}; // objects to specify where output goes, by default is - // returned, but can also be stored in a new collection - // see: http://mongoosejs.com/docs/api.html#model_Model.mapReduce - Person.mapReduce(o, function (err, results, stats) { - console.log("map reduce took %d ms", stats.processtime); - console.log(results); - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/mapreduce/package.json b/node_modules/mongoose/examples/mapreduce/package.json deleted file mode 100644 index 424006845..000000000 --- a/node_modules/mongoose/examples/mapreduce/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "map-reduce-example", - "private": "true", - "version": "0.0.0", - "description": "deps for map reduce example", - "main": "mapreduce.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/mapreduce/person.js b/node_modules/mongoose/examples/mapreduce/person.js deleted file mode 100644 index 6d476ec1a..000000000 --- a/node_modules/mongoose/examples/mapreduce/person.js +++ /dev/null @@ -1,16 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date, - gender: String - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/population/population-across-three-collections.js b/node_modules/mongoose/examples/population/population-across-three-collections.js deleted file mode 100644 index 407396527..000000000 --- a/node_modules/mongoose/examples/population/population-across-three-collections.js +++ /dev/null @@ -1,135 +0,0 @@ - -var assert = require('assert') -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; -var ObjectId = mongoose.Types.ObjectId; - -/** - * Connect to the db - */ - -var dbname = 'testing_populateAdInfinitum_' + require('../lib/utils').random() -mongoose.connect('localhost', dbname); -mongoose.connection.on('error', function() { - console.error('connection error', arguments); -}); - -/** - * Schemas - */ - -var user = new Schema({ - name: String, - friends: [{ - type: Schema.ObjectId, - ref: 'User' - }] -}); -var User = mongoose.model('User', user); - -var blogpost = Schema({ - title: String, - tags: [String], - author: { - type: Schema.ObjectId, - ref: 'User' - } -}) -var BlogPost = mongoose.model('BlogPost', blogpost); - -/** - * example - */ - -mongoose.connection.on('open', function() { - - /** - * Generate data - */ - - var userIds = [new ObjectId, new ObjectId, new ObjectId, new ObjectId]; - var users = []; - - users.push({ - _id: userIds[0], - name: 'mary', - friends: [userIds[1], userIds[2], userIds[3]] - }); - users.push({ - _id: userIds[1], - name: 'bob', - friends: [userIds[0], userIds[2], userIds[3]] - }); - users.push({ - _id: userIds[2], - name: 'joe', - friends: [userIds[0], userIds[1], userIds[3]] - }); - users.push({ - _id: userIds[3], - name: 'sally', - friends: [userIds[0], userIds[1], userIds[2]] - }); - - User.create(users, function(err, docs) { - assert.ifError(err); - - var blogposts = []; - blogposts.push({ - title: 'blog 1', - tags: ['fun', 'cool'], - author: userIds[3] - }) - blogposts.push({ - title: 'blog 2', - tags: ['cool'], - author: userIds[1] - }) - blogposts.push({ - title: 'blog 3', - tags: ['fun', 'odd'], - author: userIds[2] - }) - - BlogPost.create(blogposts, function(err, docs) { - assert.ifError(err); - - /** - * Population - */ - - BlogPost - .find({ tags: 'fun' }) - .lean() - .populate('author') - .exec(function(err, docs) { - assert.ifError(err); - - /** - * Populate the populated documents - */ - - var opts = { - path: 'author.friends', - select: 'name', - options: { limit: 2 } - } - - BlogPost.populate(docs, opts, function(err, docs) { - assert.ifError(err); - console.log('populated'); - var s = require('util').inspect(docs, { depth: null }) - console.log(s); - done(); - }) - }) - }) - }) -}); - -function done(err) { - if (err) console.error(err.stack); - mongoose.connection.db.dropDatabase(function() { - mongoose.connection.close(); - }); -} diff --git a/node_modules/mongoose/examples/population/population-basic.js b/node_modules/mongoose/examples/population/population-basic.js deleted file mode 100644 index 7b16fb5ed..000000000 --- a/node_modules/mongoose/examples/population/population-basic.js +++ /dev/null @@ -1,95 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, function (err, nintendo64) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .findOne({ name: /^Legend of Zelda/ }) - .populate('consoles') - .exec(function (err, ocinara) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s' - , ocinara.name - , ocinara.consoles[0].name - , ocinara.released.toLocaleDateString()); - - done(); - }) -} - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/population/population-of-existing-doc.js b/node_modules/mongoose/examples/population/population-of-existing-doc.js deleted file mode 100644 index 980cc7f65..000000000 --- a/node_modules/mongoose/examples/population/population-of-existing-doc.js +++ /dev/null @@ -1,101 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, function (err, nintendo64) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .findOne({ name: /^Legend of Zelda/ }) - .exec(function (err, ocinara) { - if (err) return done(err); - - console.log('"%s" console _id: %s', ocinara.name, ocinara.consoles[0]); - - // population of existing document - ocinara.populate('consoles', function (err) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s' - , ocinara.name - , ocinara.consoles[0].name - , ocinara.released.toLocaleDateString()); - - done(); - }) - }) -} - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js b/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js deleted file mode 100644 index e4d154d4f..000000000 --- a/node_modules/mongoose/examples/population/population-of-multiple-existing-docs.js +++ /dev/null @@ -1,112 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, { - name: 'Super Nintendo' - , manufacturer: 'Nintendo' - , released: 'August 23, 1991' - }, function (err, nintendo64, superNintendo) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, { - name: 'Mario Kart' - , developer: 'Nintendo' - , released: 'September 1, 1992' - , consoles: [superNintendo] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .find({}) - .exec(function (err, games) { - if (err) return done(err); - - console.log('found %d games', games.length); - - var options = { path: 'consoles', select: 'name released -_id' }; - Game.populate(games, options, function (err, games) { - if (err) return done(err); - - games.forEach(function (game) { - console.log( - '"%s" was released for the %s on %s' - , game.name - , game.consoles[0].name - , game.released.toLocaleDateString()); - }) - - done() - }) - }) -} - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/population/population-options.js b/node_modules/mongoose/examples/population/population-options.js deleted file mode 100644 index b65e3ec5b..000000000 --- a/node_modules/mongoose/examples/population/population-options.js +++ /dev/null @@ -1,124 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, { - name: 'Super Nintendo' - , manufacturer: 'Nintendo' - , released: 'August 23, 1991' - }, { - name: 'XBOX 360' - , manufacturer: 'Microsoft' - , released: 'November 22, 2005' - }, function (err, nintendo64, superNintendo, xbox360) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, { - name: 'Mario Kart' - , developer: 'Nintendo' - , released: 'September 1, 1992' - , consoles: [superNintendo] - }, { - name: 'Perfect Dark Zero' - , developer: 'Rare' - , released: 'November 17, 2005' - , consoles: [xbox360] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .find({}) - .populate({ - path: 'consoles' - , match: { manufacturer: 'Nintendo' } - , select: 'name' - , options: { comment: 'population' } - }) - .exec(function (err, games) { - if (err) return done(err); - - games.forEach(function (game) { - console.log( - '"%s" was released for the %s on %s' - , game.name - , game.consoles.length ? game.consoles[0].name : '??' - , game.released.toLocaleDateString()); - }) - - return done(); - }) -} - -/** - * Clean up - */ - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/population/population-plain-objects.js b/node_modules/mongoose/examples/population/population-plain-objects.js deleted file mode 100644 index 026259a3d..000000000 --- a/node_modules/mongoose/examples/population/population-plain-objects.js +++ /dev/null @@ -1,96 +0,0 @@ - -var mongoose = require('../../lib') -var Schema = mongoose.Schema; - -console.log('Running mongoose version %s', mongoose.version); - -/** - * Console schema - */ - -var consoleSchema = Schema({ - name: String - , manufacturer: String - , released: Date -}) -var Console = mongoose.model('Console', consoleSchema); - -/** - * Game schema - */ - -var gameSchema = Schema({ - name: String - , developer: String - , released: Date - , consoles: [{ type: Schema.Types.ObjectId, ref: 'Console' }] -}) -var Game = mongoose.model('Game', gameSchema); - -/** - * Connect to the console database on localhost with - * the default port (27017) - */ - -mongoose.connect('mongodb://localhost/console', function (err) { - // if we failed to connect, abort - if (err) throw err; - - // we connected ok - createData(); -}) - -/** - * Data generation - */ - -function createData () { - Console.create({ - name: 'Nintendo 64' - , manufacturer: 'Nintendo' - , released: 'September 29, 1996' - }, function (err, nintendo64) { - if (err) return done(err); - - Game.create({ - name: 'Legend of Zelda: Ocarina of Time' - , developer: 'Nintendo' - , released: new Date('November 21, 1998') - , consoles: [nintendo64] - }, function (err) { - if (err) return done(err); - example(); - }) - }) -} - -/** - * Population - */ - -function example () { - Game - .findOne({ name: /^Legend of Zelda/ }) - .populate('consoles') - .lean() // just return plain objects, not documents wrapped by mongoose - .exec(function (err, ocinara) { - if (err) return done(err); - - console.log( - '"%s" was released for the %s on %s' - , ocinara.name - , ocinara.consoles[0].name - , ocinara.released.toLocaleDateString()); - - done(); - }) -} - -function done (err) { - if (err) console.error(err); - Console.remove(function () { - Game.remove(function () { - mongoose.disconnect(); - }) - }) -} diff --git a/node_modules/mongoose/examples/promises/package.json b/node_modules/mongoose/examples/promises/package.json deleted file mode 100644 index 198325080..000000000 --- a/node_modules/mongoose/examples/promises/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "promise-example", - "private": "true", - "version": "0.0.0", - "description": "deps for promise example", - "main": "promise.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/promises/person.js b/node_modules/mongoose/examples/promises/person.js deleted file mode 100644 index f9c9a27ab..000000000 --- a/node_modules/mongoose/examples/promises/person.js +++ /dev/null @@ -1,15 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/promises/promise.js b/node_modules/mongoose/examples/promises/promise.js deleted file mode 100644 index 7b02b1f09..000000000 --- a/node_modules/mongoose/examples/promises/promise.js +++ /dev/null @@ -1,70 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)) }, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)) }, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)) }, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)) }, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)) }, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // create a promise (get one from the query builder) - var prom = Person.find({age : { $lt : 1000 }}).exec(); - - // add a callback on the promise. This will be called on both error and - // complete - prom.addBack(function () { console.log("completed"); }); - - // add a callback that is only called on complete (success) events - prom.addCallback(function () { console.log("Successful Completion!"); }); - - // add a callback that is only called on err (rejected) events - prom.addErrback(function () { console.log("Fail Boat"); }); - - // you can chain things just like in the promise/A+ spec - // note: each then() is returning a new promise, so the above methods - // that we defined will all fire after the initial promise is fulfilled - prom.then(function (people) { - - // just getting the stuff for the next query - var ids = people.map(function (p) { - return p._id; - }); - - // return the next promise - return Person.find({ _id : { $nin : ids }}).exec(); - }).then(function (oldest) { - console.log("Oldest person is: %s", oldest); - }).then(cleanup); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/querybuilder/package.json b/node_modules/mongoose/examples/querybuilder/package.json deleted file mode 100644 index 1a3450aa1..000000000 --- a/node_modules/mongoose/examples/querybuilder/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "query-builder-example", - "private": "true", - "version": "0.0.0", - "description": "deps for query builder example", - "main": "querybuilder.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/querybuilder/person.js b/node_modules/mongoose/examples/querybuilder/person.js deleted file mode 100644 index f9c9a27ab..000000000 --- a/node_modules/mongoose/examples/querybuilder/person.js +++ /dev/null @@ -1,15 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/querybuilder/querybuilder.js b/node_modules/mongoose/examples/querybuilder/querybuilder.js deleted file mode 100644 index ecc0fe846..000000000 --- a/node_modules/mongoose/examples/querybuilder/querybuilder.js +++ /dev/null @@ -1,65 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)) }, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)) }, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)) }, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)) }, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)) }, -]; - - -mongoose.connect('mongodb://localhost/persons', function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - if (err) throw err; - - // when querying data, instead of providing a callback, you can instead - // leave that off and get a query object returned - var query = Person.find({ age : { $lt : 1000 }}); - - // this allows you to continue applying modifiers to it - query.sort('birthday'); - query.select('name'); - - // you can chain them together as well - // a full list of methods can be found: - // http://mongoosejs.com/docs/api.html#query-js - query.where('age').gt(21); - - // finally, when ready to execute the query, call the exec() function - query.exec(function (err, results) { - if (err) throw err; - - console.log(results); - - cleanup(); - }); - - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/replicasets/package.json b/node_modules/mongoose/examples/replicasets/package.json deleted file mode 100644 index 927dfd24b..000000000 --- a/node_modules/mongoose/examples/replicasets/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "replica-set-example", - "private": "true", - "version": "0.0.0", - "description": "deps for replica set example", - "main": "querybuilder.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "dependencies": { "async": "*" }, - "repository": "", - "author": "", - "license": "BSD" -} diff --git a/node_modules/mongoose/examples/replicasets/person.js b/node_modules/mongoose/examples/replicasets/person.js deleted file mode 100644 index f9c9a27ab..000000000 --- a/node_modules/mongoose/examples/replicasets/person.js +++ /dev/null @@ -1,15 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/replicasets/replica-sets.js b/node_modules/mongoose/examples/replicasets/replica-sets.js deleted file mode 100644 index 5b69f49d6..000000000 --- a/node_modules/mongoose/examples/replicasets/replica-sets.js +++ /dev/null @@ -1,53 +0,0 @@ - -// import async to make control flow simplier -var async = require('async'); - -// import the rest of the normal stuff -var mongoose = require('../../lib'); - -require('./person.js')(); - -var Person = mongoose.model('Person'); - -// define some dummy data -var data = [ - { name : 'bill', age : 25, birthday : new Date().setFullYear((new - Date().getFullYear() - 25)) }, - { name : 'mary', age : 30, birthday : new Date().setFullYear((new - Date().getFullYear() - 30)) }, - { name : 'bob', age : 21, birthday : new Date().setFullYear((new - Date().getFullYear() - 21)) }, - { name : 'lilly', age : 26, birthday : new Date().setFullYear((new - Date().getFullYear() - 26)) }, - { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new - Date().getFullYear() - 1000)) }, -]; - - -// to connect to a replica set, pass in the comma delimited uri and optionally -// any connection options such as the rs_name. -var opts = { - replSet : { rs_name : "rs0" } -}; -mongoose.connect('mongodb://localhost:27018/persons,localhost:27019,localhost:27020', opts, function (err) { - if (err) throw err; - - // create all of the dummy people - async.each(data, function (item, cb) { - Person.create(item, cb); - }, function (err) { - - // create and delete some data - var prom = Person.find({age : { $lt : 1000 }}).exec(); - - prom.then(function (people) { - console.log("young people: %s", people); - }).then(cleanup); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/examples/schema/schema.js b/node_modules/mongoose/examples/schema/schema.js deleted file mode 100644 index 7fb171c88..000000000 --- a/node_modules/mongoose/examples/schema/schema.js +++ /dev/null @@ -1,102 +0,0 @@ - -/** - * Module dependencies. - */ - -var mongoose = require('../../lib') - , Schema = mongoose.Schema; - -/** - * Schema definition - */ - -// recursive embedded-document schema - -var Comment = new Schema(); - -Comment.add({ - title : { type: String, index: true } - , date : Date - , body : String - , comments : [Comment] -}); - -var BlogPost = new Schema({ - title : { type: String, index: true } - , slug : { type: String, lowercase: true, trim: true } - , date : Date - , buf : Buffer - , comments : [Comment] - , creator : Schema.ObjectId -}); - -var Person = new Schema({ - name: { - first: String - , last : String - } - , email: { type: String, required: true, index: { unique: true, sparse: true } } - , alive: Boolean -}); - -/** - * Accessing a specific schema type by key - */ - -BlogPost.path('date') -.default(function(){ - return new Date() - }) -.set(function(v){ - return v == 'now' ? new Date() : v; - }); - -/** - * Pre hook. - */ - -BlogPost.pre('save', function(next, done){ - emailAuthor(done); // some async function - next(); -}); - -/** - * Methods - */ - -BlogPost.methods.findCreator = function (callback) { - return this.db.model('Person').findById(this.creator, callback); -} - -BlogPost.statics.findByTitle = function (title, callback) { - return this.find({ title: title }, callback); -} - -BlogPost.methods.expressiveQuery = function (creator, date, callback) { - return this.find('creator', creator).where('date').gte(date).run(callback); -} - -/** - * Plugins - */ - -function slugGenerator (options){ - options = options || {}; - var key = options.key || 'title'; - - return function slugGenerator(schema){ - schema.path(key).set(function(v){ - this.slug = v.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/-+/g, ''); - return v; - }); - }; -}; - -BlogPost.plugin(slugGenerator()); - -/** - * Define model. - */ - -mongoose.model('BlogPost', BlogPost); -mongoose.model('Person', Person); diff --git a/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js b/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js deleted file mode 100644 index 1e05b41c5..000000000 --- a/node_modules/mongoose/examples/schema/storing-schemas-as-json/index.js +++ /dev/null @@ -1,27 +0,0 @@ - -// modules -var mongoose = require('../../../lib') -var Schema = mongoose.Schema; - -// parse json -var raw = require('./schema.json'); - -// create a schema -var timeSignatureSchema = Schema(raw); - -// compile the model -var TimeSignature = mongoose.model('TimeSignatures', timeSignatureSchema); - -// create a TimeSignature document -var threeFour = new TimeSignature({ - count: 3 - , unit: 4 - , description: "3/4" - , additive: false - , created: new Date - , links: ["http://en.wikipedia.org/wiki/Time_signature"] - , user_id: "518d31a0ef32bbfa853a9814" -}); - -// print its description -console.log(threeFour) diff --git a/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json b/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json deleted file mode 100644 index 5afc626cc..000000000 --- a/node_modules/mongoose/examples/schema/storing-schemas-as-json/schema.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "count": "number", - "unit": "number", - "description": "string", - "links": ["string"], - "created": "date", - "additive": "boolean", - "user_id": "ObjectId" -} diff --git a/node_modules/mongoose/examples/statics/person.js b/node_modules/mongoose/examples/statics/person.js deleted file mode 100644 index 45dbfdee7..000000000 --- a/node_modules/mongoose/examples/statics/person.js +++ /dev/null @@ -1,21 +0,0 @@ - -// import the necessary modules -var mongoose = require('../../lib'); -var Schema = mongoose.Schema; - -// create an export function to encapsulate the model creation -module.exports = function() { - // define schema - var PersonSchema = new Schema({ - name : String, - age : Number, - birthday : Date - }); - - // define a static - PersonSchema.statics.findPersonByName = function (name, cb) { - this.find({ name : new RegExp(name, 'i') }, cb); - }; - - mongoose.model('Person', PersonSchema); -}; diff --git a/node_modules/mongoose/examples/statics/statics.js b/node_modules/mongoose/examples/statics/statics.js deleted file mode 100644 index 7af642f30..000000000 --- a/node_modules/mongoose/examples/statics/statics.js +++ /dev/null @@ -1,38 +0,0 @@ - -var mongoose = require('../../lib'); - - -// import the schema -require('./person.js')(); - -// grab the person model object -var Person = mongoose.model("Person"); - -// connect to a server to do a quick write / read example - -mongoose.connect('mongodb://localhost/persons', function(err) { - if (err) throw err; - - Person.create({ - name : 'bill', - age : 25, - birthday : new Date().setFullYear((new Date().getFullYear() - 25)) - }, function (err, bill) { - if (err) throw err; - console.log("People added to db: %s", bill.toString()); - - // using the static - Person.findPersonByName('bill', function(err, result) { - if (err) throw err; - - console.log(result); - cleanup(); - }); - }); -}); - -function cleanup() { - Person.remove(function() { - mongoose.disconnect(); - }); -} diff --git a/node_modules/mongoose/index.js b/node_modules/mongoose/index.js deleted file mode 100644 index e7e627859..000000000 --- a/node_modules/mongoose/index.js +++ /dev/null @@ -1,7 +0,0 @@ - -/** - * Export lib/mongoose - * - */ - -module.exports = require('./lib/'); diff --git a/node_modules/mongoose/lib/aggregate.js b/node_modules/mongoose/lib/aggregate.js deleted file mode 100644 index e75044def..000000000 --- a/node_modules/mongoose/lib/aggregate.js +++ /dev/null @@ -1,408 +0,0 @@ -/*! - * Module dependencies - */ - -var Promise = require('./promise') - , util = require('util') - , utils = require('./utils') - , Query = require('./query') - , read = Query.prototype.read - -/** - * Aggregate constructor used for building aggregation pipelines. - * - * ####Example: - * - * new Aggregate(); - * new Aggregate({ $project: { a: 1, b: 1 } }); - * new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); - * new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); - * - * Returned when calling Model.aggregate(). - * - * ####Example: - * - * Model - * .aggregate({ $match: { age: { $gte: 21 }}}) - * .unwind('tags') - * .exec(callback) - * - * ####Note: - * - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - Requires MongoDB >= 2.1 - * - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @see driver http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate - * @param {Object|Array} [ops] aggregation operator(s) or operator array - * @api public - */ - -function Aggregate () { - this._pipeline = []; - this._model = undefined; - this.options = undefined; - - if (1 === arguments.length && util.isArray(arguments[0])) { - this.append.apply(this, arguments[0]); - } else { - this.append.apply(this, arguments); - } -} - -/** - * Binds this aggregate to a model. - * - * @param {Model} model the model to which the aggregate is to be bound - * @return {Aggregate} - * @api private - */ - -Aggregate.prototype.bind = function (model) { - this._model = model; - return this; -} - -/** - * Appends new operators to this aggregate pipeline - * - * ####Examples: - * - * aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); - * - * // or pass an array - * var pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; - * aggregate.append(pipeline); - * - * @param {Object} ops operator(s) to append - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.append = function () { - var args = utils.args(arguments) - , arg; - - if (!args.every(isOperator)) { - throw new Error("Arguments must be aggregate pipeline operators"); - } - - this._pipeline = this._pipeline.concat(args); - - return this; -} - -/** - * Appends a new $project operator to this aggregate pipeline. - * - * Mongoose query [selection syntax](#query_Query-select) is also supported. - * - * ####Examples: - * - * // include a, include b, exclude _id - * aggregate.project("a b -_id"); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * aggregate.project({a: 1, b: 1, _id: 0}); - * - * // reshaping documents - * aggregate.project({ - * newField: '$b.nested' - * , plusTen: { $add: ['$val', 10]} - * , sub: { - * name: '$a' - * } - * }) - * - * // etc - * aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); - * - * @param {Object|String} arg field specification - * @see projection http://docs.mongodb.org/manual/reference/aggregation/project/ - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.project = function (arg) { - var fields = {}; - - if ('object' === typeof arg && !util.isArray(arg)) { - Object.keys(arg).forEach(function (field) { - fields[field] = arg[field]; - }); - } else if (1 === arguments.length && 'string' === typeof arg) { - arg.split(/\s+/).forEach(function (field) { - if (!field) return; - var include = '-' == field[0] ? 0 : 1; - if (include === 0) field = field.substring(1); - fields[field] = include; - }); - } else { - throw new Error("Invalid project() argument. Must be string or object"); - } - - return this.append({ $project: fields }); -} - -/** - * Appends a new custom $group operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.group({ _id: "$department" }); - * - * @see $group http://docs.mongodb.org/manual/reference/aggregation/group/ - * @method group - * @memberOf Aggregate - * @param {Object} arg $group operator contents - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new custom $match operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.match({ department: { $in: [ "sales", "engineering" } } }); - * - * @see $match http://docs.mongodb.org/manual/reference/aggregation/match/ - * @method match - * @memberOf Aggregate - * @param {Object} arg $match operator contents - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $skip operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.skip(10); - * - * @see $skip http://docs.mongodb.org/manual/reference/aggregation/skip/ - * @method skip - * @memberOf Aggregate - * @param {Number} num number of records to skip before next stage - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $limit operator to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.limit(10); - * - * @see $limit http://docs.mongodb.org/manual/reference/aggregation/limit/ - * @method limit - * @memberOf Aggregate - * @param {Number} num maximum number of records to pass to the next stage - * @return {Aggregate} - * @api public - */ - -/** - * Appends a new $geoNear operator to this aggregate pipeline. - * - * ####NOTE: - * - * **MUST** be used as the first operator in the pipeline. - * - * ####Examples: - * - * aggregate.near({ - * near: [40.724, -73.997], - * distanceField: "dist.calculated", // required - * maxDistance: 0.008, - * query: { type: "public" }, - * includeLocs: "dist.location", - * uniqueDocs: true, - * num: 5 - * }); - * - * @see $geoNear http://docs.mongodb.org/manual/reference/aggregation/geoNear/ - * @method near - * @memberOf Aggregate - * @param {Object} parameters - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.near = function (arg) { - var op = {}; - op.$geoNear = arg; - return this.append(op); -}; - -/*! - * define methods - */ - -'group match skip limit'.split(' ').forEach(function ($operator) { - Aggregate.prototype[$operator] = function (arg) { - var op = {}; - op['$' + $operator] = arg; - return this.append(op); - }; -}); - -/** - * Appends new custom $unwind operator(s) to this aggregate pipeline. - * - * ####Examples: - * - * aggregate.unwind("tags"); - * aggregate.unwind("a", "b", "c"); - * - * @see $unwind http://docs.mongodb.org/manual/reference/aggregation/unwind/ - * @param {String} fields the field(s) to unwind - * @return {Aggregate} - * @api public - */ - -Aggregate.prototype.unwind = function () { - var args = utils.args(arguments); - - return this.append.apply(this, args.map(function (arg) { - return { $unwind: '$' + arg }; - })); -} - -/** - * Appends a new $sort operator to this aggregate pipeline. - * - * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - * - * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - * - * ####Examples: - * - * // these are equivalent - * aggregate.sort({ field: 'asc', test: -1 }); - * aggregate.sort('field -test'); - * - * @see $sort http://docs.mongodb.org/manual/reference/aggregation/sort/ - * @param {Object|String} arg - * @return {Query} this - * @api public - */ - -Aggregate.prototype.sort = function (arg) { - // TODO refactor to reuse the query builder logic - - var sort = {}; - - if ('Object' === arg.constructor.name) { - var desc = ['desc', 'descending', -1]; - Object.keys(arg).forEach(function (field) { - sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1; - }); - } else if (1 === arguments.length && 'string' == typeof arg) { - arg.split(/\s+/).forEach(function (field) { - if (!field) return; - var ascend = '-' == field[0] ? -1 : 1; - if (ascend === -1) field = field.substring(1); - sort[field] = ascend; - }); - } else { - throw new TypeError('Invalid sort() argument. Must be a string or object.'); - } - - return this.append({ $sort: sort }); -} - -/** - * Sets the readPreference option for the aggregation query. - * - * ####Example: - * - * Model.aggregate(..).read('primaryPreferred').exec(callback) - * - * @param {String} pref one of the listed preference options or their aliases - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - */ - -Aggregate.prototype.read = function (pref) { - if (!this.options) this.options = {}; - read.apply(this, arguments); - return this; -} - -/** - * Executes the aggregate pipeline on the currently bound Model. - * - * ####Example: - * - * aggregate.exec(callback); - * - * // Because a promise is returned, the `callback` is optional. - * var promise = aggregate.exec(); - * promise.then(..); - * - * @see Promise #promise_Promise - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Aggregate.prototype.exec = function (callback) { - var promise = new Promise(); - - if (callback) { - promise.addBack(callback); - } - - if (!this._pipeline.length) { - promise.error(new Error("Aggregate has empty pipeline")); - return promise; - } - - if (!this._model) { - promise.error(new Error("Aggregate not bound to any Model")); - return promise; - } - - this._model - .collection - .aggregate(this._pipeline, this.options || {}, promise.resolve.bind(promise)); - - return promise; -} - -/*! - * Helpers - */ - -/** - * Checks whether an object is likely a pipeline operator - * - * @param {Object} obj object to check - * @return {Boolean} - * @api private - */ - -function isOperator (obj) { - var k; - - if ('object' !== typeof obj) { - return false; - } - - k = Object.keys(obj); - - return 1 === k.length && k.some(function (key) { - return '$' === key[0]; - }); -} - -/*! - * Exports - */ - -module.exports = Aggregate; diff --git a/node_modules/mongoose/lib/collection.js b/node_modules/mongoose/lib/collection.js deleted file mode 100644 index 1c38286a8..000000000 --- a/node_modules/mongoose/lib/collection.js +++ /dev/null @@ -1,188 +0,0 @@ - -/*! - * Module dependencies. - */ - -var STATES = require('./connectionstate') - -/** - * Abstract Collection constructor - * - * This is the base class that drivers inherit from and implement. - * - * @param {String} name name of the collection - * @param {Connection} conn A MongooseConnection instance - * @param {Object} opts optional collection options - * @api public - */ - -function Collection (name, conn, opts) { - if (undefined === opts) opts = {}; - if (undefined === opts.capped) opts.capped = {}; - - opts.bufferCommands = undefined === opts.bufferCommands - ? true - : opts.bufferCommands; - - if ('number' == typeof opts.capped) { - opts.capped = { size: opts.capped }; - } - - this.opts = opts; - this.name = name; - this.conn = conn; - this.queue = []; - this.buffer = this.opts.bufferCommands; - - if (STATES.connected == this.conn.readyState) { - this.onOpen(); - } -}; - -/** - * The collection name - * - * @api public - * @property name - */ - -Collection.prototype.name; - -/** - * The Connection instance - * - * @api public - * @property conn - */ - -Collection.prototype.conn; - -/** - * Called when the database connects - * - * @api private - */ - -Collection.prototype.onOpen = function () { - var self = this; - this.buffer = false; - self.doQueue(); -}; - -/** - * Called when the database disconnects - * - * @api private - */ - -Collection.prototype.onClose = function () { - if (this.opts.bufferCommands) { - this.buffer = true; - } -}; - -/** - * Queues a method for later execution when its - * database connection opens. - * - * @param {String} name name of the method to queue - * @param {Array} args arguments to pass to the method when executed - * @api private - */ - -Collection.prototype.addQueue = function (name, args) { - this.queue.push([name, args]); - return this; -}; - -/** - * Executes all queued methods and clears the queue. - * - * @api private - */ - -Collection.prototype.doQueue = function () { - for (var i = 0, l = this.queue.length; i < l; i++){ - this[this.queue[i][0]].apply(this, this.queue[i][1]); - } - this.queue = []; - return this; -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.ensureIndex = function(){ - throw new Error('Collection#ensureIndex unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findAndModify = function(){ - throw new Error('Collection#findAndModify unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.findOne = function(){ - throw new Error('Collection#findOne unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.find = function(){ - throw new Error('Collection#find unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.insert = function(){ - throw new Error('Collection#insert unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.save = function(){ - throw new Error('Collection#save unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.update = function(){ - throw new Error('Collection#update unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.getIndexes = function(){ - throw new Error('Collection#getIndexes unimplemented by driver'); -}; - -/** - * Abstract method that drivers must implement. - */ - -Collection.prototype.mapReduce = function(){ - throw new Error('Collection#mapReduce unimplemented by driver'); -}; - -/*! - * Module exports. - */ - -module.exports = Collection; diff --git a/node_modules/mongoose/lib/connection.js b/node_modules/mongoose/lib/connection.js deleted file mode 100644 index 276652906..000000000 --- a/node_modules/mongoose/lib/connection.js +++ /dev/null @@ -1,718 +0,0 @@ -/*! - * Module dependencies. - */ - -var url = require('url') - , utils = require('./utils') - , EventEmitter = require('events').EventEmitter - , driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native' - , Model = require('./model') - , Schema = require('./schema') - , Collection = require(driver + '/collection') - , STATES = require('./connectionstate') - , MongooseError = require('./error') - , assert =require('assert') - , muri = require('muri') - -/*! - * Protocol prefix regexp. - * - * @api private - */ - -var rgxProtocol = /^(?:.)+:\/\//; - -/** - * Connection constructor - * - * For practical reasons, a Connection equals a Db. - * - * @param {Mongoose} base a mongoose instance - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `connecting`: Emitted when `connection.{open,openSet}()` is executed on this connection. - * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios. - * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connections models. - * @event `disconnecting`: Emitted when `connection.close()` was executed. - * @event `disconnected`: Emitted after getting disconnected from the db. - * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connections models. - * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successfull connection. - * @event `error`: Emitted when an error occurs on this connection. - * @event `fullsetup`: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. - * @api public - */ - -function Connection (base) { - this.base = base; - this.collections = {}; - this.models = {}; - this.replica = false; - this.hosts = null; - this.host = null; - this.port = null; - this.user = null; - this.pass = null; - this.name = null; - this.options = null; - this.otherDbs = []; - this._readyState = STATES.disconnected; - this._closeCalled = false; - this._hasOpened = false; -}; - -/*! - * Inherit from EventEmitter - */ - -Connection.prototype.__proto__ = EventEmitter.prototype; - -/** - * Connection ready state - * - * - 0 = disconnected - * - 1 = connected - * - 2 = connecting - * - 3 = disconnecting - * - * Each state change emits its associated event name. - * - * ####Example - * - * conn.on('connected', callback); - * conn.on('disconnected', callback); - * - * @property readyState - * @api public - */ - -Object.defineProperty(Connection.prototype, 'readyState', { - get: function(){ return this._readyState; } - , set: function (val) { - if (!(val in STATES)) { - throw new Error('Invalid connection state: ' + val); - } - - if (this._readyState !== val) { - this._readyState = val; - // loop over the otherDbs on this connection and change their state - for (var i=0; i < this.otherDbs.length; i++) { - this.otherDbs[i].readyState = val; - } - - if (STATES.connected === val) - this._hasOpened = true; - - this.emit(STATES[val]); - } - } -}); - -/** - * A hash of the collections associated with this connection - * - * @property collections - */ - -Connection.prototype.collections; - -/** - * The mongodb.Db instance, set when the connection is opened - * - * @property db - */ - -Connection.prototype.db; - -/** - * Opens the connection to MongoDB. - * - * `options` is a hash with the following possible properties: - * - * db - passed to the connection db instance - * server - passed to the connection server instance(s) - * replset - passed to the connection ReplSet instance - * user - username for authentication - * pass - password for authentication - * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) - * - * ####Notes: - * - * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. - * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. - * See the node-mongodb-native driver instance for options that it understands. - * - * _Options passed take precedence over options included in connection strings._ - * - * @param {String} connection_string mongodb://uri or the host to which you are connecting - * @param {String} [database] database name - * @param {Number} [port] database port - * @param {Object} [options] options - * @param {Function} [callback] - * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native - * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate - * @api public - */ - -Connection.prototype.open = function (host, database, port, options, callback) { - var self = this - , parsed - , uri; - - if ('string' === typeof database) { - switch (arguments.length) { - case 2: - port = 27017; - case 3: - switch (typeof port) { - case 'function': - callback = port, port = 27017; - break; - case 'object': - options = port, port = 27017; - break; - } - break; - case 4: - if ('function' === typeof options) - callback = options, options = {}; - } - } else { - switch (typeof database) { - case 'function': - callback = database, database = undefined; - break; - case 'object': - options = database; - database = undefined; - callback = port; - break; - } - - if (!rgxProtocol.test(host)) { - host = 'mongodb://' + host; - } - - try { - parsed = muri(host); - } catch (err) { - this.error(err, callback); - return this; - } - - database = parsed.db; - host = parsed.hosts[0].host || parsed.hosts[0].ipc; - port = parsed.hosts[0].port || 27017; - } - - this.options = this.parseOptions(options, parsed && parsed.options); - - // make sure we can open - if (STATES.disconnected !== this.readyState) { - var err = new Error('Trying to open unclosed connection.'); - err.state = this.readyState; - this.error(err, callback); - return this; - } - - if (!host) { - this.error(new Error('Missing hostname.'), callback); - return this; - } - - if (!database) { - this.error(new Error('Missing database name.'), callback); - return this; - } - - // authentication - if (options && options.user && options.pass) { - this.user = options.user; - this.pass = options.pass; - - } else if (parsed && parsed.auth) { - this.user = parsed.auth.user; - this.pass = parsed.auth.pass; - - // Check hostname for user/pass - } else if (/@/.test(host) && /:/.test(host.split('@')[0])) { - host = host.split('@'); - var auth = host.shift().split(':'); - host = host.pop(); - this.user = auth[0]; - this.pass = auth[1]; - - } else { - this.user = this.pass = undefined; - } - - this.name = database; - this.host = host; - this.port = port; - - this._open(callback); - return this; -}; - -/** - * Opens the connection to a replica set. - * - * ####Example: - * - * var db = mongoose.createConnection(); - * db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); - * - * The database name and/or auth need only be included in one URI. - * The `options` is a hash which is passed to the internal driver connection object. - * - * Valid `options` - * - * db - passed to the connection db instance - * server - passed to the connection server instance(s) - * replset - passed to the connection ReplSetServer instance - * user - username for authentication - * pass - password for authentication - * auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) - * mongos - Boolean - if true, enables High Availability support for mongos - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Notes: - * - * _If connecting to multiple mongos servers, set the `mongos` option to true._ - * - * conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb); - * - * Mongoose forces the db option `forceServerObjectId` false and cannot be overridden. - * Mongoose defaults the server `auto_reconnect` options to true which can be overridden. - * See the node-mongodb-native driver instance for options that it understands. - * - * _Options passed take precedence over options included in connection strings._ - * - * @param {String} uris comma-separated mongodb:// `URI`s - * @param {String} [database] database name if not included in `uris` - * @param {Object} [options] passed to the internal driver - * @param {Function} [callback] - * @see node-mongodb-native https://github.com/mongodb/node-mongodb-native - * @see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate - * @api public - */ - -Connection.prototype.openSet = function (uris, database, options, callback) { - if (!rgxProtocol.test(uris)) { - uris = 'mongodb://' + uris; - } - - var self = this; - - switch (arguments.length) { - case 3: - switch (typeof database) { - case 'string': - this.name = database; - break; - case 'object': - callback = options; - options = database; - database = null; - break; - } - - if ('function' === typeof options) { - callback = options; - options = {}; - } - break; - case 2: - switch (typeof database) { - case 'string': - this.name = database; - break; - case 'function': - callback = database, database = null; - break; - case 'object': - options = database, database = null; - break; - } - } - - var parsed; - try { - parsed = muri(uris); - } catch (err) { - this.error(err, callback); - return this; - } - - if (!this.name) { - this.name = parsed.db; - } - - this.hosts = parsed.hosts; - this.options = this.parseOptions(options, parsed && parsed.options); - this.replica = true; - - if (!this.name) { - this.error(new Error('No database name provided for replica set'), callback); - return this; - } - - // authentication - if (options && options.user && options.pass) { - this.user = options.user; - this.pass = options.pass; - - } else if (parsed && parsed.auth) { - this.user = parsed.auth.user; - this.pass = parsed.auth.pass; - - } else { - this.user = this.pass = undefined; - } - - this._open(callback); - return this; -}; - -/** - * error - * - * Graceful error handling, passes error to callback - * if available, else emits error on the connection. - * - * @param {Error} err - * @param {Function} callback optional - * @api private - */ - -Connection.prototype.error = function (err, callback) { - if (callback) return callback(err); - this.emit('error', err); -} - -/** - * Handles opening the connection with the appropriate method based on connection type. - * - * @param {Function} callback - * @api private - */ - -Connection.prototype._open = function (callback) { - this.readyState = STATES.connecting; - this._closeCalled = false; - - var self = this; - - var method = this.replica - ? 'doOpenSet' - : 'doOpen'; - - // open connection - this[method](function (err) { - if (err) { - self.readyState = STATES.disconnected; - if (self._hasOpened) { - if (callback) callback(err); - } else { - self.error(err, callback); - } - return; - } - - self.onOpen(callback); - }); -} - -/** - * Called when the connection is opened - * - * @api private - */ - -Connection.prototype.onOpen = function (callback) { - var self = this; - - function open (err) { - if (err) { - self.readyState = STATES.disconnected; - if (self._hasOpened) { - if (callback) callback(err); - } else { - self.error(err, callback); - } - return; - } - - self.readyState = STATES.connected; - - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (var i in self.collections) - self.collections[i].onOpen(); - - callback && callback(); - self.emit('open'); - }; - - // re-authenticate - if (self.user && self.pass) { - self.db.authenticate(self.user, self.pass, self.options.auth, open); - } - else - open(); -}; - -/** - * Closes the connection - * - * @param {Function} [callback] optional - * @return {Connection} self - * @api public - */ - -Connection.prototype.close = function (callback) { - var self = this; - this._closeCalled = true; - - switch (this.readyState){ - case 0: // disconnected - callback && callback(); - break; - - case 1: // connected - this.readyState = STATES.disconnecting; - this.doClose(function(err){ - if (err){ - self.error(err, callback); - } else { - self.onClose(); - callback && callback(); - } - }); - break; - - case 2: // connecting - this.once('open', function(){ - self.close(callback); - }); - break; - - case 3: // disconnecting - if (!callback) break; - this.once('close', function () { - callback(); - }); - break; - } - - return this; -}; - -/** - * Called when the connection closes - * - * @api private - */ - -Connection.prototype.onClose = function () { - this.readyState = STATES.disconnected; - - // avoid having the collection subscribe to our event emitter - // to prevent 0.3 warning - for (var i in this.collections) - this.collections[i].onClose(); - - this.emit('close'); -}; - -/** - * Retrieves a collection, creating it if not cached. - * - * Not typically needed by applications. Just talk to your collection through your model. - * - * @param {String} name of the collection - * @param {Object} [options] optional collection options - * @return {Collection} collection instance - * @api public - */ - -Connection.prototype.collection = function (name, options) { - if (!(name in this.collections)) - this.collections[name] = new Collection(name, this, options); - return this.collections[name]; -}; - -/** - * Defines or retrieves a model. - * - * var mongoose = require('mongoose'); - * var db = mongoose.createConnection(..); - * db.model('Venue', new Schema(..)); - * var Ticket = db.model('Ticket', new Schema(..)); - * var Venue = db.model('Venue'); - * - * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ - * - * ####Example: - * - * var schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * var collectionName = 'actor' - * var M = conn.model('Actor', schema, collectionName) - * - * @param {String} name the model name - * @param {Schema} [schema] a schema. necessary when defining a model - * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name - * @see Mongoose#model #index_Mongoose-model - * @return {Model} The compiled model - * @api public - */ - -Connection.prototype.model = function (name, schema, collection) { - // collection name discovery - if ('string' == typeof schema) { - collection = schema; - schema = false; - } - - if (utils.isObject(schema) && !(schema instanceof Schema)) { - schema = new Schema(schema); - } - - if (this.models[name] && !collection) { - // model exists but we are not subclassing with custom collection - if (schema instanceof Schema && schema != this.models[name].schema) { - throw new MongooseError.OverwriteModelError(name); - } - return this.models[name]; - } - - var opts = { cache: false, connection: this } - var model; - - if (schema instanceof Schema) { - // compile a model - model = this.base.model(name, schema, collection, opts) - - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } - - model.init(); - return model; - } - - if (this.models[name] && collection) { - // subclassing current model with alternate collection - model = this.models[name]; - schema = model.prototype.schema; - var sub = model.__subclass(this, schema, collection); - // do not cache the sub model - return sub; - } - - // lookup model in mongoose module - model = this.base.models[name]; - - if (!model) { - throw new MongooseError.MissingSchemaError(name); - } - - if (this == model.prototype.db - && (!collection || collection == model.collection.name)) { - // model already uses this connection. - - // only the first model with this name is cached to allow - // for one-offs with custom collection names etc. - if (!this.models[name]) { - this.models[name] = model; - } - - return model; - } - - return this.models[name] = model.__subclass(this, schema, collection); -} - -/** - * Returns an array of model names created on this connection. - * @api public - * @return {Array} - */ - -Connection.prototype.modelNames = function () { - return Object.keys(this.models); -} - -/** - * Set profiling level. - * - * @param {Number|String} level either off (0), slow (1), or all (2) - * @param {Number} [ms] the threshold in milliseconds above which queries will be logged when in `slow` mode. defaults to 100. - * @param {Function} callback - * @api public - */ - -Connection.prototype.setProfiling = function (level, ms, callback) { - if (STATES.connected !== this.readyState) { - return this.on('open', this.setProfiling.bind(this, level, ms, callback)); - } - - if (!callback) callback = ms, ms = 100; - - var cmd = {}; - - switch (level) { - case 0: - case 'off': - cmd.profile = 0; - break; - case 1: - case 'slow': - cmd.profile = 1; - if ('number' !== typeof ms) { - ms = parseInt(ms, 10); - if (isNaN(ms)) ms = 100; - } - cmd.slowms = ms; - break; - case 2: - case 'all': - cmd.profile = 2; - break; - default: - return callback(new Error('Invalid profiling level: '+ level)); - } - - this.db.executeDbCommand(cmd, function (err, resp) { - if (err) return callback(err); - - var doc = resp.documents[0]; - - err = 1 === doc.ok - ? null - : new Error('Could not set profiling level to: '+ level) - - callback(err, doc); - }); -}; - -/*! - * Noop. - */ - -function noop () {} - -/*! - * Module exports. - */ - -Connection.STATES = STATES; -module.exports = Connection; diff --git a/node_modules/mongoose/lib/connectionstate.js b/node_modules/mongoose/lib/connectionstate.js deleted file mode 100644 index 2d05ab087..000000000 --- a/node_modules/mongoose/lib/connectionstate.js +++ /dev/null @@ -1,24 +0,0 @@ - -/*! - * Connection states - */ - -var STATES = module.exports = exports = Object.create(null); - -var disconnected = 'disconnected'; -var connected = 'connected'; -var connecting = 'connecting'; -var disconnecting = 'disconnecting'; -var uninitialized = 'uninitialized'; - -STATES[0] = disconnected; -STATES[1] = connected; -STATES[2] = connecting; -STATES[3] = disconnecting; -STATES[99] = uninitialized; - -STATES[disconnected] = 0; -STATES[connected] = 1; -STATES[connecting] = 2; -STATES[disconnecting] = 3; -STATES[uninitialized] = 99; diff --git a/node_modules/mongoose/lib/document.js b/node_modules/mongoose/lib/document.js deleted file mode 100644 index 16affc7d6..000000000 --- a/node_modules/mongoose/lib/document.js +++ /dev/null @@ -1,1791 +0,0 @@ -/*! - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , setMaxListeners = EventEmitter.prototype.setMaxListeners - , MongooseError = require('./error') - , MixedSchema = require('./schema/mixed') - , Schema = require('./schema') - , ValidatorError = require('./schematype').ValidatorError - , utils = require('./utils') - , clone = utils.clone - , isMongooseObject = utils.isMongooseObject - , inspect = require('util').inspect - , ElemMatchError = MongooseError.ElemMatchError - , ValidationError = MongooseError.ValidationError - , InternalCache = require('./internal') - , deepEqual = utils.deepEqual - , hooks = require('hooks') - , DocumentArray - , MongooseArray - , Embedded - -/** - * Document constructor. - * - * @param {Object} obj the values to set - * @param {Object} [opts] optional object containing the fields which were selected in the query returning this document and any populated paths data - * @param {Boolean} [skipId] bool, should we auto create an ObjectId _id - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose. - * @event `save`: Emitted when the document is successfully saved - * @api private - */ - -function Document (obj, fields, skipId) { - this.$__ = new InternalCache; - this.isNew = true; - this.errors = undefined; - - var schema = this.schema; - - if ('boolean' === typeof fields) { - this.$__.strictMode = fields; - fields = undefined; - } else { - this.$__.strictMode = schema.options && schema.options.strict; - this.$__.selected = fields; - } - - var required = schema.requiredPaths(); - for (var i = 0; i < required.length; ++i) { - this.$__.activePaths.require(required[i]); - } - - setMaxListeners.call(this, 0); - this._doc = this.$__buildDoc(obj, fields, skipId); - - if (obj) { - this.set(obj, undefined, true); - } - - this.$__registerHooks(); -} - -/*! - * Inherit from EventEmitter. - */ - -Document.prototype.__proto__ = EventEmitter.prototype; - -/** - * The documents schema. - * - * @api public - * @property schema - */ - -Document.prototype.schema; - -/** - * Boolean flag specifying if the document is new. - * - * @api public - * @property isNew - */ - -Document.prototype.isNew; - -/** - * The string version of this documents _id. - * - * ####Note: - * - * This getter exists on all documents by default. The getter can be disabled by setting the `id` [option](/docs/guide.html#id) of its `Schema` to false at construction time. - * - * new Schema({ name: String }, { id: false }); - * - * @api public - * @see Schema options /docs/guide.html#options - * @property id - */ - -Document.prototype.id; - -/** - * Hash containing current validation errors. - * - * @api public - * @property errors - */ - -Document.prototype.errors; - -/** - * Builds the default doc structure - * - * @param {Object} obj - * @param {Object} [fields] - * @param {Boolean} [skipId] - * @return {Object} - * @api private - * @method $__buildDoc - * @memberOf Document - */ - -Document.prototype.$__buildDoc = function (obj, fields, skipId) { - var doc = {} - , self = this - , exclude - , keys - , key - , ki - - // determine if this doc is a result of a query with - // excluded fields - if (fields && 'Object' === fields.constructor.name) { - keys = Object.keys(fields); - ki = keys.length; - - while (ki--) { - if ('_id' !== keys[ki]) { - exclude = 0 === fields[keys[ki]]; - break; - } - } - } - - var paths = Object.keys(this.schema.paths) - , plen = paths.length - , ii = 0 - - for (; ii < plen; ++ii) { - var p = paths[ii]; - - if ('_id' == p) { - if (skipId) continue; - if (obj && '_id' in obj) continue; - } - - var type = this.schema.paths[p] - , path = p.split('.') - , len = path.length - , last = len-1 - , curPath = '' - , doc_ = doc - , i = 0 - - for (; i < len; ++i) { - var piece = path[i] - , def - - // support excluding intermediary levels - if (exclude) { - curPath += piece; - if (curPath in fields) break; - curPath += '.'; - } - - if (i === last) { - if (fields) { - if (exclude) { - // apply defaults to all non-excluded fields - if (p in fields) continue; - - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { - doc_[piece] = def; - self.$__.activePaths.default(p); - } - - } else if (p in fields) { - // selected field - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { - doc_[piece] = def; - self.$__.activePaths.default(p); - } - } - } else { - def = type.getDefault(self, true); - if ('undefined' !== typeof def) { - doc_[piece] = def; - self.$__.activePaths.default(p); - } - } - } else { - doc_ = doc_[piece] || (doc_[piece] = {}); - } - } - }; - - return doc; -}; - -/** - * Initializes the document without setters or marking anything modified. - * - * Called internally after a document is returned from mongodb. - * - * @param {Object} doc document returned by mongo - * @param {Function} fn callback - * @api private - */ - -Document.prototype.init = function (doc, opts, fn) { - // do not prefix this method with $__ since its - // used by public hooks - - if ('function' == typeof opts) { - fn = opts; - opts = null; - } - - this.isNew = false; - - // handle docs with populated paths - if (doc._id && opts && opts.populated && opts.populated.length) { - var id = String(doc._id); - for (var i = 0; i < opts.populated.length; ++i) { - var item = opts.populated[i]; - this.populated(item.path, item._docs[id], item); - } - } - - init(this, doc, this._doc); - this.$__storeShard(); - - this.emit('init', this); - if (fn) fn(null); - return this; -}; - -/*! - * Init helper. - * - * @param {Object} self document instance - * @param {Object} obj raw mongodb doc - * @param {Object} doc object we are initializing - * @api private - */ - -function init (self, obj, doc, prefix) { - prefix = prefix || ''; - - var keys = Object.keys(obj) - , len = keys.length - , schema - , path - , i; - - while (len--) { - i = keys[len]; - path = prefix + i; - schema = self.schema.path(path); - - if (!schema && utils.isObject(obj[i]) && - (!obj[i].constructor || 'Object' == obj[i].constructor.name)) { - // assume nested object - if (!doc[i]) doc[i] = {}; - init(self, obj[i], doc[i], path + '.'); - } else { - if (obj[i] === null) { - doc[i] = null; - } else if (obj[i] !== undefined) { - if (schema) { - self.$__try(function(){ - doc[i] = schema.cast(obj[i], self, true); - }); - } else { - doc[i] = obj[i]; - } - } - // mark as hydrated - self.$__.activePaths.init(path); - } - } -}; - -/** - * Stores the current values of the shard keys. - * - * ####Note: - * - * _Shard key values do not / are not allowed to change._ - * - * @api private - * @method $__storeShard - * @memberOf Document - */ - -Document.prototype.$__storeShard = function () { - // backwards compat - var key = this.schema.options.shardKey || this.schema.options.shardkey; - if (!(key && 'Object' == key.constructor.name)) return; - - var orig = this.$__.shardval = {} - , paths = Object.keys(key) - , len = paths.length - , val - - for (var i = 0; i < len; ++i) { - val = this.getValue(paths[i]); - if (isMongooseObject(val)) { - orig[paths[i]] = val.toObject({ depopulate: true }) - } else if (null != val && val.valueOf) { - orig[paths[i]] = val.valueOf(); - } else { - orig[paths[i]] = val; - } - } -} - -/*! - * Set up middleware support - */ - -for (var k in hooks) { - Document.prototype[k] = Document[k] = hooks[k]; -} - -/** - * Sends an update command with this document `_id` as the query selector. - * - * ####Example: - * - * weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback); - * - * ####Valid options: - * - * - same as in [Model.update](#model_Model.update) - * - * @see Model.update #model_Model.update - * @param {Object} doc - * @param {Object} options - * @param {Function} callback - * @return {Query} - * @api public - */ - -Document.prototype.update = function update () { - var args = utils.args(arguments); - args.unshift({_id: this._id}); - return this.constructor.update.apply(this.constructor, args); -} - -/** - * Sets the value of a path, or many paths. - * - * ####Example: - * - * // path, value - * doc.set(path, value) - * - * // object - * doc.set({ - * path : value - * , path2 : { - * path : value - * } - * }) - * - * // only-the-fly cast to number - * doc.set(path, value, Number) - * - * // only-the-fly cast to string - * doc.set(path, value, String) - * - * // changing strict mode behavior - * doc.set(path, value, { strict: false }); - * - * @param {String|Object} path path or object of key/vals to set - * @param {Any} val the value to set - * @param {Schema|String|Number|Buffer|etc..} [type] optionally specify a type for "on-the-fly" attributes - * @param {Object} [options] optionally specify options that modify the behavior of the set - * @api public - */ - -Document.prototype.set = function (path, val, type, options) { - if (type && 'Object' == type.constructor.name) { - options = type; - type = undefined; - } - - var merge = options && options.merge - , adhoc = type && true !== type - , constructing = true === type - , adhocs - - var strict = options && 'strict' in options - ? options.strict - : this.$__.strictMode; - - if (adhoc) { - adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); - adhocs[path] = Schema.interpretAsType(path, type); - } - - if ('string' !== typeof path) { - // new Document({ key: val }) - - if (null === path || undefined === path) { - var _ = path; - path = val; - val = _; - - } else { - var prefix = val - ? val + '.' - : ''; - - if (path instanceof Document) path = path._doc; - - var keys = Object.keys(path) - , i = keys.length - , pathtype - , key - - - while (i--) { - key = keys[i]; - pathtype = this.schema.pathType(prefix + key); - if (null != path[key] - // need to know if plain object - no Buffer, ObjectId, ref, etc - && utils.isObject(path[key]) - && (!path[key].constructor || 'Object' == path[key].constructor.name) - && 'virtual' != pathtype - && !(this.$__path(prefix + key) instanceof MixedSchema) - && !(this.schema.paths[key] && this.schema.paths[key].options.ref) - ) { - this.set(path[key], prefix + key, constructing); - } else if (strict) { - if ('real' === pathtype || 'virtual' === pathtype) { - this.set(prefix + key, path[key], constructing); - } else if ('throw' == strict) { - throw new Error("Field `" + key + "` is not in schema."); - } - } else if (undefined !== path[key]) { - this.set(prefix + key, path[key], constructing); - } - } - - return this; - } - } - - // ensure _strict is honored for obj props - // docschema = new Schema({ path: { nest: 'string' }}) - // doc.set('path', obj); - var pathType = this.schema.pathType(path); - if ('nested' == pathType && val && utils.isObject(val) && - (!val.constructor || 'Object' == val.constructor.name)) { - if (!merge) this.setValue(path, null); - this.set(val, path, constructing); - return this; - } - - var schema; - var parts = path.split('.'); - - if ('adhocOrUndefined' == pathType && strict) { - - // check for roots that are Mixed types - var mixed; - - for (var i = 0; i < parts.length; ++i) { - var subpath = parts.slice(0, i+1).join('.'); - schema = this.schema.path(subpath); - if (schema instanceof MixedSchema) { - // allow changes to sub paths of mixed types - mixed = true; - break; - } - } - - if (!mixed) { - if ('throw' == strict) { - throw new Error("Field `" + path + "` is not in schema."); - } - return this; - } - - } else if ('virtual' == pathType) { - schema = this.schema.virtualpath(path); - schema.applySetters(val, this); - return this; - } else { - schema = this.$__path(path); - } - - var pathToMark; - - // When using the $set operator the path to the field must already exist. - // Else mongodb throws: "LEFT_SUBFIELD only supports Object" - - if (parts.length <= 1) { - pathToMark = path; - } else { - for (var i = 0; i < parts.length; ++i) { - var subpath = parts.slice(0, i+1).join('.'); - if (this.isDirectModified(subpath) // earlier prefixes that are already - // marked as dirty have precedence - || this.get(subpath) === null) { - pathToMark = subpath; - break; - } - } - - if (!pathToMark) pathToMark = path; - } - - // if this doc is being constructed we should not trigger getters - var priorVal = constructing - ? undefined - : this.get(path); - - if (!schema || undefined === val) { - this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); - return this; - } - - var self = this; - var shouldSet = this.$__try(function(){ - val = schema.applySetters(val, self, false, priorVal); - }); - - if (shouldSet) { - this.$__set(pathToMark, path, constructing, parts, schema, val, priorVal); - } - - return this; -} - -/** - * Determine if we should mark this change as modified. - * - * @return {Boolean} - * @api private - * @method $__shouldModify - * @memberOf Document - */ - -Document.prototype.$__shouldModify = function ( - pathToMark, path, constructing, parts, schema, val, priorVal) { - - if (this.isNew) return true; - if (this.isDirectModified(pathToMark)) return false; - - if (undefined === val && !this.isSelected(path)) { - // when a path is not selected in a query, its initial - // value will be undefined. - return true; - } - - if (undefined === val && path in this.$__.activePaths.states.default) { - // we're just unsetting the default value which was never saved - return false; - } - - if (!deepEqual(val, priorVal || this.get(path))) { - return true; - } - - if (!constructing && - null != val && - path in this.$__.activePaths.states.default && - deepEqual(val, schema.getDefault(this, constructing))) { - // a path with a default was $unset on the server - // and the user is setting it to the same value again - return true; - } - - return false; -} - -/** - * Handles the actual setting of the value and marking the path modified if appropriate. - * - * @api private - * @method $__set - * @memberOf Document - */ - -Document.prototype.$__set = function ( - pathToMark, path, constructing, parts, schema, val, priorVal) { - - var shouldModify = this.$__shouldModify.apply(this, arguments); - - if (shouldModify) { - this.markModified(pathToMark, val); - - // handle directly setting arrays (gh-1126) - MongooseArray || (MongooseArray = require('./types/array')); - if (val instanceof MongooseArray) { - val._registerAtomic('$set', val); - } - } - - var obj = this._doc - , i = 0 - , l = parts.length - - for (; i < l; i++) { - var next = i + 1 - , last = next === l; - - if (last) { - obj[parts[i]] = val; - } else { - if (obj[parts[i]] && 'Object' === obj[parts[i]].constructor.name) { - obj = obj[parts[i]]; - } else if (obj[parts[i]] && Array.isArray(obj[parts[i]])) { - obj = obj[parts[i]]; - } else { - obj = obj[parts[i]] = {}; - } - } - } -} - -/** - * Gets a raw value from a path (no getters) - * - * @param {String} path - * @api private - */ - -Document.prototype.getValue = function (path) { - return utils.getValue(path, this._doc); -} - -/** - * Sets a raw value for a path (no casting, setters, transformations) - * - * @param {String} path - * @param {Object} value - * @api private - */ - -Document.prototype.setValue = function (path, val) { - utils.setValue(path, val, this._doc); - return this; -} - -/** - * Returns the value of a path. - * - * ####Example - * - * // path - * doc.get('age') // 47 - * - * // dynamic casting to a string - * doc.get('age', String) // "47" - * - * @param {String} path - * @param {Schema|String|Number|Buffer|etc..} [type] optionally specify a type for on-the-fly attributes - * @api public - */ - -Document.prototype.get = function (path, type) { - var adhocs; - if (type) { - adhocs = this.$__.adhocPaths || (this.$__.adhocPaths = {}); - adhocs[path] = Schema.interpretAsType(path, type); - } - - var schema = this.$__path(path) || this.schema.virtualpath(path) - , pieces = path.split('.') - , obj = this._doc; - - for (var i = 0, l = pieces.length; i < l; i++) { - obj = undefined === obj || null === obj - ? undefined - : obj[pieces[i]]; - } - - if (schema) { - obj = schema.applyGetters(obj, this); - } - - return obj; -}; - -/** - * Returns the schematype for the given `path`. - * - * @param {String} path - * @api private - * @method $__path - * @memberOf Document - */ - -Document.prototype.$__path = function (path) { - var adhocs = this.$__.adhocPaths - , adhocType = adhocs && adhocs[path]; - - if (adhocType) { - return adhocType; - } else { - return this.schema.path(path); - } -}; - -/** - * Marks the path as having pending changes to write to the db. - * - * _Very helpful when using [Mixed](./schematypes.html#mixed) types._ - * - * ####Example: - * - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * doc.save() // changes to mixed.type are now persisted - * - * @param {String} path the path to mark modified - * @api public - */ - -Document.prototype.markModified = function (path) { - this.$__.activePaths.modify(path); -} - -/** - * Catches errors that occur during execution of `fn` and stores them to later be passed when `save()` is executed. - * - * @param {Function} fn function to execute - * @param {Object} scope the scope with which to call fn - * @api private - * @method $__try - * @memberOf Document - */ - -Document.prototype.$__try = function (fn, scope) { - var res; - try { - fn.call(scope); - res = true; - } catch (e) { - this.$__error(e); - res = false; - } - return res; -}; - -/** - * Returns the list of paths that have been modified. - * - * @return {Array} - * @api public - */ - -Document.prototype.modifiedPaths = function () { - var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify); - - return directModifiedPaths.reduce(function (list, path) { - var parts = path.split('.'); - return list.concat(parts.reduce(function (chains, part, i) { - return chains.concat(parts.slice(0, i).concat(part).join('.')); - }, [])); - }, []); -}; - -/** - * Returns true if this document was modified, else false. - * - * If `path` is given, checks if a path or any full path containing `path` as part of its path chain has been modified. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isModified() // true - * doc.isModified('documents') // true - * doc.isModified('documents.0.title') // true - * doc.isDirectModified('documents') // false - * - * @param {String} [path] optional - * @return {Boolean} - * @api public - */ - -Document.prototype.isModified = function (path) { - return path - ? !!~this.modifiedPaths().indexOf(path) - : this.$__.activePaths.some('modify'); -}; - -/** - * Returns true if `path` was directly set and modified, else false. - * - * ####Example - * - * doc.set('documents.0.title', 'changed'); - * doc.isDirectModified('documents.0.title') // true - * doc.isDirectModified('documents') // false - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isDirectModified = function (path) { - return (path in this.$__.activePaths.states.modify); -}; - -/** - * Checks if `path` was initialized. - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isInit = function (path) { - return (path in this.$__.activePaths.states.init); -}; - -/** - * Checks if `path` was selected in the source query which initialized this document. - * - * ####Example - * - * Thing.findOne().select('name').exec(function (err, doc) { - * doc.isSelected('name') // true - * doc.isSelected('age') // false - * }) - * - * @param {String} path - * @return {Boolean} - * @api public - */ - -Document.prototype.isSelected = function isSelected (path) { - if (this.$__.selected) { - - if ('_id' === path) { - return 0 !== this.$__.selected._id; - } - - var paths = Object.keys(this.$__.selected) - , i = paths.length - , inclusive = false - , cur - - if (1 === i && '_id' === paths[0]) { - // only _id was selected. - return 0 === this.$__.selected._id; - } - - while (i--) { - cur = paths[i]; - if ('_id' == cur) continue; - inclusive = !! this.$__.selected[cur]; - break; - } - - if (path in this.$__.selected) { - return inclusive; - } - - i = paths.length; - var pathDot = path + '.'; - - while (i--) { - cur = paths[i]; - if ('_id' == cur) continue; - - if (0 === cur.indexOf(pathDot)) { - return inclusive; - } - - if (0 === pathDot.indexOf(cur + '.')) { - return inclusive; - } - } - - return ! inclusive; - } - - return true; -} - -/** - * Executes registered validation rules for this document. - * - * ####Note: - * - * This method is called `pre` save and if a validation rule is violated, [save](#model_Model-save) is aborted and the error is returned to your `callback`. - * - * ####Example: - * - * doc.validate(function (err) { - * if (err) handleError(err); - * else // validation passed - * }); - * - * @param {Function} cb called after validation completes, passing an error if one occurred - * @api public - */ - -Document.prototype.validate = function (cb) { - var self = this - - // only validate required fields when necessary - var paths = Object.keys(this.$__.activePaths.states.require).filter(function (path) { - if (!self.isSelected(path) && !self.isModified(path)) return false; - return true; - }); - - paths = paths.concat(Object.keys(this.$__.activePaths.states.init)); - paths = paths.concat(Object.keys(this.$__.activePaths.states.modify)); - paths = paths.concat(Object.keys(this.$__.activePaths.states.default)); - - if (0 === paths.length) { - complete(); - return this; - } - - var validating = {} - , total = 0; - - paths.forEach(validatePath); - return this; - - function validatePath (path) { - if (validating[path]) return; - - validating[path] = true; - total++; - - process.nextTick(function(){ - var p = self.schema.path(path); - if (!p) return --total || complete(); - - var val = self.getValue(path); - p.doValidate(val, function (err) { - if (err) { - self.invalidate( - path - , err - , undefined - , true // embedded docs - ); - } - --total || complete(); - }, self); - }); - } - - function complete () { - var err = self.$__.validationError; - self.$__.validationError = undefined; - self.emit('validate', self); - cb(err); - } -}; - -/** - * Marks a path as invalid, causing validation to fail. - * - * The `errorMsg` argument will become the message of the `ValidationError`. - * - * The `value` argument (if passed) will be available through the `ValidationError.value` property. - * - * doc.invalidate('size', 'must be less than 20', 14); - - * doc.validate(function (err) { - * console.log(err) - * // prints - * { message: 'Validation failed', - * name: 'ValidationError', - * errors: - * { size: - * { message: 'must be less than 20', - * name: 'ValidatorError', - * path: 'size', - * type: 'user defined', - * value: 14 } } } - * }) - * - * @param {String} path the field to invalidate - * @param {String|Error} errorMsg the error which states the reason `path` was invalid - * @param {Object|String|Number|any} value optional invalid value - * @api public - */ - -Document.prototype.invalidate = function (path, err, val) { - if (!this.$__.validationError) { - this.$__.validationError = new ValidationError(this); - } - - if (!err || 'string' === typeof err) { - err = new ValidatorError(path, err, 'user defined', val) - } - - if (this.$__.validationError == err) return; - - this.$__.validationError.errors[path] = err; -} - -/** - * Resets the internal modified state of this document. - * - * @api private - * @return {Document} - * @method $__reset - * @memberOf Document - */ - -Document.prototype.$__reset = function reset () { - var self = this; - DocumentArray || (DocumentArray = require('./types/documentarray')); - - this.$__.activePaths - .map('init', 'modify', function (i) { - return self.getValue(i); - }) - .filter(function (val) { - return val && val instanceof DocumentArray && val.length; - }) - .forEach(function (array) { - var i = array.length; - while (i--) { - var doc = array[i]; - if (!doc) continue; - doc.$__reset(); - } - }); - - // clear atomics - this.$__dirty().forEach(function (dirt) { - var type = dirt.value; - if (type && type._atomics) { - type._atomics = {}; - } - }); - - // Clear 'modify'('dirty') cache - this.$__.activePaths.clear('modify'); - this.$__.validationError = undefined; - this.errors = undefined; - var self = this; - this.schema.requiredPaths().forEach(function (path) { - self.$__.activePaths.require(path); - }); - - return this; -} - -/** - * Returns this documents dirty paths / vals. - * - * @api private - * @method $__dirty - * @memberOf Document - */ - -Document.prototype.$__dirty = function () { - var self = this; - - var all = this.$__.activePaths.map('modify', function (path) { - return { path: path - , value: self.getValue(path) - , schema: self.$__path(path) }; - }); - - // Sort dirty paths in a flat hierarchy. - all.sort(function (a, b) { - return (a.path < b.path ? -1 : (a.path > b.path ? 1 : 0)); - }); - - // Ignore "foo.a" if "foo" is dirty already. - var minimal = [] - , lastPath - , top; - - all.forEach(function (item, i) { - if (item.path.indexOf(lastPath) !== 0) { - lastPath = item.path + '.'; - minimal.push(item); - top = item; - } else { - // special case for top level MongooseArrays - if (top.value && top.value._atomics && top.value.hasAtomics()) { - // the `top` array itself and a sub path of `top` are being modified. - // the only way to honor all of both modifications is through a $set - // of entire array. - top.value._atomics = {}; - top.value._atomics.$set = top.value; - } - } - }); - - top = lastPath = null; - return minimal; -} - -/*! - * Compiles schemas. - */ - -function compile (tree, proto, prefix) { - var keys = Object.keys(tree) - , i = keys.length - , limb - , key; - - while (i--) { - key = keys[i]; - limb = tree[key]; - - define(key - , (('Object' === limb.constructor.name - && Object.keys(limb).length) - && (!limb.type || limb.type.type) - ? limb - : null) - , proto - , prefix - , keys); - } -}; - -/*! - * Defines the accessor named prop on the incoming prototype. - */ - -function define (prop, subprops, prototype, prefix, keys) { - var prefix = prefix || '' - , path = (prefix ? prefix + '.' : '') + prop; - - if (subprops) { - - Object.defineProperty(prototype, prop, { - enumerable: true - , get: function () { - if (!this.$__.getters) - this.$__.getters = {}; - - if (!this.$__.getters[path]) { - var nested = Object.create(this); - - // save scope for nested getters/setters - if (!prefix) nested.$__.scope = this; - - // shadow inherited getters from sub-objects so - // thing.nested.nested.nested... doesn't occur (gh-366) - var i = 0 - , len = keys.length; - - for (; i < len; ++i) { - // over-write the parents getter without triggering it - Object.defineProperty(nested, keys[i], { - enumerable: false // It doesn't show up. - , writable: true // We can set it later. - , configurable: true // We can Object.defineProperty again. - , value: undefined // It shadows its parent. - }); - } - - nested.toObject = function () { - return this.get(path); - }; - - compile(subprops, nested, path); - this.$__.getters[path] = nested; - } - - return this.$__.getters[path]; - } - , set: function (v) { - if (v instanceof Document) v = v.toObject(); - return (this.$__.scope || this).set(path, v); - } - }); - - } else { - - Object.defineProperty(prototype, prop, { - enumerable: true - , get: function ( ) { return this.get.call(this.$__.scope || this, path); } - , set: function (v) { return this.set.call(this.$__.scope || this, path, v); } - }); - } -}; - -/** - * Assigns/compiles `schema` into this documents prototype. - * - * @param {Schema} schema - * @api private - * @method $__setSchema - * @memberOf Document - */ - -Document.prototype.$__setSchema = function (schema) { - compile(schema.tree, this); - this.schema = schema; -} - -/** - * Register default hooks - * - * @api private - * @method $__registerHooks - * @memberOf Document - */ - -Document.prototype.$__registerHooks = function () { - if (!this.save) return; - - DocumentArray || (DocumentArray = require('./types/documentarray')); - - this.pre('save', function (next) { - // validate all document arrays. - // we keep the error semaphore to make sure we don't - // call `save` unnecessarily (we only need 1 error) - var subdocs = 0 - , error = false - , self = this; - - // check for DocumentArrays - var arrays = this.$__.activePaths - .map('init', 'modify', function (i) { - return self.getValue(i); - }) - .filter(function (val) { - return val && val instanceof DocumentArray && val.length; - }); - - if (!arrays.length) - return next(); - - arrays.forEach(function (array) { - if (error) return; - - // handle sparse arrays by using for loop vs array.forEach - // which skips the sparse elements - - var len = array.length - subdocs += len; - - for (var i = 0; i < len; ++i) { - if (error) break; - - var doc = array[i]; - if (!doc) { - --subdocs || next(); - continue; - } - - doc.save(handleSave); - } - }); - - function handleSave (err) { - if (error) return; - - if (err) { - self.$__.validationError = undefined; - return next(error = err); - } - - --subdocs || next(); - } - - }, function (err) { - // emit on the Model if listening - if (this.constructor.listeners('error').length) { - this.constructor.emit('error', err); - } else { - // emit on the connection - if (!this.db.listeners('error').length) { - err.stack = 'No listeners detected, throwing. ' - + 'Consider adding an error listener to your connection.\n' - + err.stack - } - this.db.emit('error', err); - } - }).pre('save', function checkForExistingErrors (next) { - // if any doc.set() calls failed - var err = this.$__.saveError; - if (err) { - this.$__.saveError = null; - next(err); - } else { - next(); - } - }).pre('save', function validation (next) { - return this.validate(next); - }); - - // add user defined queues - this.$__doQueue(); -}; - -/** - * Registers an error - * - * @param {Error} err - * @api private - * @method $__error - * @memberOf Document - */ - -Document.prototype.$__error = function (err) { - this.$__.saveError = err; - return this; -}; - -/** - * Executes methods queued from the Schema definition - * - * @api private - * @method $__doQueue - * @memberOf Document - */ - -Document.prototype.$__doQueue = function () { - var q = this.schema && this.schema.callQueue; - if (q) { - for (var i = 0, l = q.length; i < l; i++) { - this[q[i][0]].apply(this, q[i][1]); - } - } - return this; -}; - -/** - * Converts this document into a plain javascript object, ready for storage in MongoDB. - * - * Buffers are converted to instances of [mongodb.Binary](http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html) for proper storage. - * - * ####Options: - * - * - `getters` apply all getters (path and virtual getters) - * - `virtuals` apply virtual getters (can override `getters` option) - * - `minimize` remove empty objects (defaults to true) - * - `transform` a transform function to apply to the resulting document before returning - * - * ####Getters/Virtuals - * - * Example of only applying path getters - * - * doc.toObject({ getters: true, virtuals: false }) - * - * Example of only applying virtual getters - * - * doc.toObject({ virtuals: true }) - * - * Example of applying both path and virtual getters - * - * doc.toObject({ getters: true }) - * - * To apply these options to every document of your schema by default, set your [schemas](#schema_Schema) `toObject` option to the same argument. - * - * schema.set('toObject', { virtuals: true }) - * - * ####Transform - * - * We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional `transform` function. - * - * Transform functions receive three arguments - * - * function (doc, ret, options) {} - * - * - `doc` The mongoose document which is being converted - * - `ret` The plain object representation which has been converted - * - `options` The options in use (either schema options or the options passed inline) - * - * ####Example - * - * // specify the transform schema option - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * // remove the _id of every document before returning the result - * delete ret._id; - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { name: 'Wreck-it Ralph' } - * - * With transformations we can do a lot more than remove properties. We can even return completely new customized objects: - * - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.transform = function (doc, ret, options) { - * return { movie: ret.name } - * } - * - * // without the transformation in the schema - * doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' } - * - * // with the transformation - * doc.toObject(); // { movie: 'Wreck-it Ralph' } - * - * _Note: if a transform function returns `undefined`, the return value will be ignored._ - * - * Transformations may also be applied inline, overridding any transform set in the options: - * - * function xform (doc, ret, options) { - * return { inline: ret.name, custom: true } - * } - * - * // pass the transform as an inline option - * doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } - * - * _Note: if you call `toObject` and pass any options, the transform declared in your schema options will __not__ be applied. To force its application pass `transform: true`_ - * - * if (!schema.options.toObject) schema.options.toObject = {}; - * schema.options.toObject.hide = '_id'; - * schema.options.toObject.transform = function (doc, ret, options) { - * if (options.hide) { - * options.hide.split(' ').forEach(function (prop) { - * delete ret[prop]; - * }); - * } - * } - * - * var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); - * doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id' }); // { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } - * doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } - * - * Transforms are applied to the document _and each of its sub-documents_. To determine whether or not you are currently operating on a sub-document you might use the following guard: - * - * if ('function' == typeof doc.ownerDocument) { - * // working with a sub doc - * } - * - * Transforms, like all of these options, are also available for `toJSON`. - * - * See [schema options](/docs/guide.html#toObject) for some more details. - * - * _During save, no custom options are applied to the document before being sent to the database._ - * - * @param {Object} [options] - * @return {Object} js object - * @see mongodb.Binary http://mongodb.github.com/node-mongodb-native/api-bson-generated/binary.html - * @api public - */ - -Document.prototype.toObject = function (options) { - if (options && options.depopulate && this.$__.wasPopulated) { - // populated paths that we set to a document - return clone(this._id, options); - } - - // When internally saving this document we always pass options, - // bypassing the custom schema options. - if (!(options && 'Object' == options.constructor.name)) { - options = this.schema.options.toObject - ? clone(this.schema.options.toObject) - : {}; - } - - ;('minimize' in options) || (options.minimize = this.schema.options.minimize); - - var ret = clone(this._doc, options); - - if (options.virtuals || options.getters && false !== options.virtuals) { - applyGetters(this, ret, 'virtuals', options); - } - - if (options.getters) { - applyGetters(this, ret, 'paths', options); - // applyGetters for paths will add nested empty objects; - // if minimize is set, we need to remove them. - if (options.minimize) { - ret = minimize(ret) || {}; - } - } - - // In the case where a subdocument has its own transform function, we need to - // check and see if the parent has a transform (options.transform) and if the - // child schema has a transform (this.schema.options.toObject) In this case, - // we need to adjust options.transform to be the child schema's transform and - // not the parent schema's - if (true === options.transform || - (this.schema.options.toObject && options.transform)) { - var opts = options.json - ? this.schema.options.toJSON - : this.schema.options.toObject; - if (opts) { - options.transform = opts.transform; - } - } - - if ('function' == typeof options.transform) { - var xformed = options.transform(this, ret, options); - if ('undefined' != typeof xformed) ret = xformed; - } - - return ret; -}; - -/*! - * Minimizes an object, removing undefined values and empty objects - * - * @param {Object} object to minimize - * @return {Object} - */ - -function minimize (obj) { - var keys = Object.keys(obj) - , i = keys.length - , hasKeys - , key - , val - - while (i--) { - key = keys[i]; - val = obj[key]; - - if (utils.isObject(val)) { - obj[key] = minimize(val); - } - - if (undefined === obj[key]) { - delete obj[key]; - continue; - } - - hasKeys = true; - } - - return hasKeys - ? obj - : undefined; -} - -/*! - * Applies virtuals properties to `json`. - * - * @param {Document} self - * @param {Object} json - * @param {String} type either `virtuals` or `paths` - * @return {Object} `json` - */ - -function applyGetters (self, json, type, options) { - var schema = self.schema - , paths = Object.keys(schema[type]) - , i = paths.length - , path - - while (i--) { - path = paths[i]; - - var parts = path.split('.') - , plen = parts.length - , last = plen - 1 - , branch = json - , part - - for (var ii = 0; ii < plen; ++ii) { - part = parts[ii]; - if (ii === last) { - branch[part] = clone(self.get(path), options); - } else { - branch = branch[part] || (branch[part] = {}); - } - } - } - - return json; -} - -/** - * The return value of this method is used in calls to JSON.stringify(doc). - * - * This method accepts the same options as [Document#toObject](#document_Document-toObject). To apply the options to every document of your schema by default, set your [schemas](#schema_Schema) `toJSON` option to the same argument. - * - * schema.set('toJSON', { virtuals: true }) - * - * See [schema options](/docs/guide.html#toJSON) for details. - * - * @param {Object} options - * @return {Object} - * @see Document#toObject #document_Document-toObject - * @api public - */ - -Document.prototype.toJSON = function (options) { - // check for object type since an array of documents - // being stringified passes array indexes instead - // of options objects. JSON.stringify([doc, doc]) - // The second check here is to make sure that populated documents (or - // subdocuments) use their own options for `.toJSON()` instead of their - // parent's - if (!(options && 'Object' == options.constructor.name) - || ((!options || options.json) && this.schema.options.toJSON)) { - options = this.schema.options.toJSON - ? clone(this.schema.options.toJSON) - : {}; - } - options.json = true; - - return this.toObject(options); -}; - -/** - * Helper for console.log - * - * @api public - */ - -Document.prototype.inspect = function (options) { - var opts = options && 'Object' == options.constructor.name ? options : - this.schema.options.toObject ? clone(this.schema.options.toObject) : - {}; - opts.minimize = false; - return inspect(this.toObject(opts)); -}; - -/** - * Helper for console.log - * - * @api public - * @method toString - */ - -Document.prototype.toString = Document.prototype.inspect; - -/** - * Returns true if the Document stores the same data as doc. - * - * Documents are considered equal when they have matching `_id`s. - * - * @param {Document} doc a document to compare - * @return {Boolean} - * @api public - */ - -Document.prototype.equals = function (doc) { - var tid = this.get('_id'); - var docid = doc.get('_id'); - return tid && tid.equals - ? tid.equals(docid) - : tid === docid; -} - -/** - * Populates document references, executing the `callback` when complete. - * - * ####Example: - * - * doc - * .populate('company') - * .populate({ - * path: 'notes', - * match: /airline/, - * select: 'text', - * model: 'modelName' - * options: opts - * }, function (err, user) { - * assert(doc._id == user._id) // the document itself is passed - * }) - * - * // summary - * doc.populate(path) // not executed - * doc.populate(options); // not executed - * doc.populate(path, callback) // executed - * doc.populate(options, callback); // executed - * doc.populate(callback); // executed - * - * - * ####NOTE: - * - * Population does not occur unless a `callback` is passed. - * Passing the same path a second time will overwrite the previous path options. - * See [Model.populate()](#model_Model.populate) for explaination of options. - * - * @see Model.populate #model_Model.populate - * @param {String|Object} [path] The path to populate or an options object - * @param {Function} [callback] When passed, population is invoked - * @api public - * @return {Document} this - */ - -Document.prototype.populate = function populate () { - if (0 === arguments.length) return this; - - var pop = this.$__.populate || (this.$__.populate = {}); - var args = utils.args(arguments); - var fn; - - if ('function' == typeof args[args.length-1]) { - fn = args.pop(); - } - - // allow `doc.populate(callback)` - if (args.length) { - // use hash to remove duplicate paths - var res = utils.populate.apply(null, args); - for (var i = 0; i < res.length; ++i) { - pop[res[i].path] = res[i]; - } - } - - if (fn) { - var paths = utils.object.vals(pop); - this.$__.populate = undefined; - this.constructor.populate(this, paths, fn); - } - - return this; -} - -/** - * Gets _id(s) used during population of the given `path`. - * - * ####Example: - * - * Model.findOne().populate('author').exec(function (err, doc) { - * console.log(doc.author.name) // Dr.Seuss - * console.log(doc.populated('author')) // '5144cf8050f071d979c118a7' - * }) - * - * If the path was not populated, undefined is returned. - * - * @param {String} path - * @return {Array|ObjectId|Number|Buffer|String|undefined} - * @api public - */ - -Document.prototype.populated = function (path, val, options) { - // val and options are internal - - if (null == val) { - if (!this.$__.populated) return undefined; - var v = this.$__.populated[path]; - if (v) return v.value; - return undefined; - } - - // internal - - if (true === val) { - if (!this.$__.populated) return undefined; - return this.$__.populated[path]; - } - - this.$__.populated || (this.$__.populated = {}); - this.$__.populated[path] = { value: val, options: options }; - return val; -} - -/** - * Returns the full path to this document. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf Document - */ - -Document.prototype.$__fullPath = function (path) { - // overridden in SubDocuments - return path || ''; -} - -/*! - * Module exports. - */ - -Document.ValidationError = ValidationError; -module.exports = exports = Document; diff --git a/node_modules/mongoose/lib/drivers/SPEC.md b/node_modules/mongoose/lib/drivers/SPEC.md deleted file mode 100644 index 64646931e..000000000 --- a/node_modules/mongoose/lib/drivers/SPEC.md +++ /dev/null @@ -1,4 +0,0 @@ - -# Driver Spec - -TODO diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js deleted file mode 100644 index 0480d3122..000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/binary.js +++ /dev/null @@ -1,8 +0,0 @@ - -/*! - * Module dependencies. - */ - -var Binary = require('mongodb').BSONPure.Binary; - -module.exports = exports = Binary; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js deleted file mode 100644 index 426502126..000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js +++ /dev/null @@ -1,211 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseCollection = require('../../collection') - , Collection = require('mongodb').Collection - , STATES = require('../../connectionstate') - , utils = require('../../utils') - -/** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) collection implementation. - * - * All methods methods from the [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver are copied and wrapped in queue management. - * - * @inherits Collection - * @api private - */ - -function NativeCollection () { - this.collection = null; - MongooseCollection.apply(this, arguments); -} - -/*! - * Inherit from abstract Collection. - */ - -NativeCollection.prototype.__proto__ = MongooseCollection.prototype; - -/** - * Called when the connection opens. - * - * @api private - */ - -NativeCollection.prototype.onOpen = function () { - var self = this; - - // always get a new collection in case the user changed host:port - // of parent db instance when re-opening the connection. - - if (!self.opts.capped.size) { - // non-capped - return self.conn.db.collection(self.name, callback); - } - - // capped - return self.conn.db.collection(self.name, function (err, c) { - if (err) return callback(err); - - // discover if this collection exists and if it is capped - c.options(function (err, exists) { - if (err) return callback(err); - - if (exists) { - if (exists.capped) { - callback(null, c); - } else { - var msg = 'A non-capped collection exists with the name: '+ self.name +'\n\n' - + ' To use this collection as a capped collection, please ' - + 'first convert it.\n' - + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped' - err = new Error(msg); - callback(err); - } - } else { - // create - var opts = utils.clone(self.opts.capped); - opts.capped = true; - self.conn.db.createCollection(self.name, opts, callback); - } - }); - }); - - function callback (err, collection) { - if (err) { - // likely a strict mode error - self.conn.emit('error', err); - } else { - self.collection = collection; - MongooseCollection.prototype.onOpen.call(self); - } - }; -}; - -/** - * Called when the connection closes - * - * @api private - */ - -NativeCollection.prototype.onClose = function () { - MongooseCollection.prototype.onClose.call(this); -}; - -/*! - * Copy the collection methods and make them subject to queues - */ - -for (var i in Collection.prototype) { - (function(i){ - NativeCollection.prototype[i] = function () { - if (this.buffer) { - this.addQueue(i, arguments); - return; - } - - var collection = this.collection - , args = arguments - , self = this - , debug = self.conn.base.options.debug; - - if (debug) { - if ('function' === typeof debug) { - debug.apply(debug - , [self.name, i].concat(utils.args(args, 0, args.length-1))); - } else { - console.error('\x1B[0;36mMongoose:\x1B[0m %s.%s(%s) %s %s %s' - , self.name - , i - , print(args[0]) - , print(args[1]) - , print(args[2]) - , print(args[3])) - } - } - - return collection[i].apply(collection, args); - }; - })(i); -} - -/*! - * Debug print helper - */ - -function print (arg) { - var type = typeof arg; - if ('function' === type || 'undefined' === type) return ''; - return format(arg); -} - -/*! - * Debug print helper - */ - -function format (obj, sub) { - var x = utils.clone(obj); - if (x) { - if ('Binary' === x.constructor.name) { - x = '[object Buffer]'; - } else if ('ObjectID' === x.constructor.name) { - var representation = 'ObjectId("' + x.toHexString() + '")'; - x = { inspect: function() { return representation; } }; - } else if ('Date' === x.constructor.name) { - var representation = 'new Date("' + x.toUTCString() + '")'; - x = { inspect: function() { return representation; } }; - } else if ('Object' === x.constructor.name) { - var keys = Object.keys(x) - , i = keys.length - , key - while (i--) { - key = keys[i]; - if (x[key]) { - if ('Binary' === x[key].constructor.name) { - x[key] = '[object Buffer]'; - } else if ('Object' === x[key].constructor.name) { - x[key] = format(x[key], true); - } else if ('ObjectID' === x[key].constructor.name) { - ;(function(x){ - var representation = 'ObjectId("' + x[key].toHexString() + '")'; - x[key] = { inspect: function() { return representation; } }; - })(x) - } else if ('Date' === x[key].constructor.name) { - ;(function(x){ - var representation = 'new Date("' + x[key].toUTCString() + '")'; - x[key] = { inspect: function() { return representation; } }; - })(x) - } else if (Array.isArray(x[key])) { - x[key] = x[key].map(function (o) { - return format(o, true) - }); - } - } - } - } - if (sub) return x; - } - - return require('util') - .inspect(x, false, 10, true) - .replace(/\n/g, '') - .replace(/\s{2,}/g, ' ') -} - -/** - * Retreives information about this collections indexes. - * - * @param {Function} callback - * @method getIndexes - * @api public - */ - -NativeCollection.prototype.getIndexes = NativeCollection.prototype.indexInformation; - -/*! - * Module exports. - */ - -module.exports = NativeCollection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js deleted file mode 100644 index b4f352045..000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/connection.js +++ /dev/null @@ -1,371 +0,0 @@ -/*! - * Module dependencies. - */ - -var MongooseConnection = require('../../connection') - , mongo = require('mongodb') - , Db = mongo.Db - , Server = mongo.Server - , Mongos = mongo.Mongos - , STATES = require('../../connectionstate') - , ReplSetServers = mongo.ReplSetServers - , utils = require('../../utils'); - -/** - * A [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) connection implementation. - * - * @inherits Connection - * @api private - */ - -function NativeConnection() { - MongooseConnection.apply(this, arguments); - this._listening = false; -}; - -/** - * Expose the possible connection states. - * @api public - */ - -NativeConnection.STATES = STATES; - -/*! - * Inherits from Connection. - */ - -NativeConnection.prototype.__proto__ = MongooseConnection.prototype; - -/** - * Opens the connection to MongoDB. - * - * @param {Function} fn - * @return {Connection} this - * @api private - */ - -NativeConnection.prototype.doOpen = function (fn) { - if (this.db) { - mute(this); - } - - var server = new Server(this.host, this.port, this.options.server); - this.db = new Db(this.name, server, this.options.db); - - var self = this; - this.db.open(function (err) { - if (err) return fn(err); - listen(self); - fn(); - }); - - return this; -}; - -/** - * Switches to a different database using the same connection pool. - * - * Returns a new connection object, with the new db. - * - * @param {String} name The database name - * @return {Connection} New Connection Object - * @api public - */ - -NativeConnection.prototype.useDb = function (name) { - // we have to manually copy all of the attributes... - var newConn = new this.constructor(); - newConn.name = name; - newConn.base = this.base; - newConn.collections = {}; - newConn.models = {}; - newConn.replica = this.replica; - newConn.hosts = this.hosts; - newConn.host = this.host; - newConn.port = this.port; - newConn.user = this.user; - newConn.pass = this.pass; - newConn.options = this.options; - newConn._readyState = this._readyState; - newConn._closeCalled = this._closeCalled; - newConn._hasOpened = this._hasOpened; - newConn._listening = false; - - // First, when we create another db object, we are not guaranteed to have a - // db object to work with. So, in the case where we have a db object and it - // is connected, we can just proceed with setting everything up. However, if - // we do not have a db or the state is not connected, then we need to wait on - // the 'open' event of the connection before doing the rest of the setup - // the 'connected' event is the first time we'll have access to the db object - - var self = this; - - if (this.db && this.db._state == 'connected') { - wireup(); - } else { - this.once('connected', wireup); - } - - function wireup () { - newConn.db = self.db.db(name); - newConn.onOpen(); - // setup the events appropriately - listen(newConn); - } - - newConn.name = name; - - // push onto the otherDbs stack, this is used when state changes - this.otherDbs.push(newConn); - newConn.otherDbs.push(this); - - return newConn; -}; - -/*! - * Register listeners for important events and bubble appropriately. - */ - -function listen (conn) { - if (conn._listening) return; - conn._listening = true; - - conn.db.on('close', function(){ - if (conn._closeCalled) return; - - // the driver never emits an `open` event. auto_reconnect still - // emits a `close` event but since we never get another - // `open` we can't emit close - if (conn.db.serverConfig.autoReconnect) { - conn.readyState = STATES.disconnected; - conn.emit('close'); - return; - } - conn.onClose(); - }); - conn.db.on('error', function(err){ - conn.emit('error', err); - }); - conn.db.on('timeout', function(err){ - var error = new Error(err && err.err || 'connection timeout'); - conn.emit('error', error); - }); - conn.db.on('open', function (err, db) { - if (STATES.disconnected === conn.readyState && db && db.databaseName) { - conn.readyState = STATES.connected; - conn.emit('reconnected') - } - }) -} - -/*! - * Remove listeners registered in `listen` - */ - -function mute (conn) { - if (!conn.db) throw new Error('missing db'); - conn.db.removeAllListeners("close"); - conn.db.removeAllListeners("error"); - conn.db.removeAllListeners("timeout"); - conn.db.removeAllListeners("open"); - conn.db.removeAllListeners("fullsetup"); - conn._listening = false; -} - -/** - * Opens a connection to a MongoDB ReplicaSet. - * - * See description of [doOpen](#NativeConnection-doOpen) for server options. In this case `options.replset` is also passed to ReplSetServers. - * - * @param {Function} fn - * @api private - * @return {Connection} this - */ - -NativeConnection.prototype.doOpenSet = function (fn) { - if (this.db) { - mute(this); - } - - var servers = [] - , self = this; - - this.hosts.forEach(function (server) { - var host = server.host || server.ipc; - var port = server.port || 27017; - servers.push(new Server(host, port, self.options.server)); - }) - - var server = this.options.mongos - ? new Mongos(servers, this.options.mongos) - : new ReplSetServers(servers, this.options.replset); - this.db = new Db(this.name, server, this.options.db); - - this.db.on('fullsetup', function () { - self.emit('fullsetup') - }); - - this.db.open(function (err) { - if (err) return fn(err); - fn(); - listen(self); - }); - - return this; -}; - -/** - * Closes the connection - * - * @param {Function} fn - * @return {Connection} this - * @api private - */ - -NativeConnection.prototype.doClose = function (fn) { - this.db.close(); - if (fn) fn(); - return this; -} - -/** - * Prepares default connection options for the node-mongodb-native driver. - * - * _NOTE: `passed` options take precedence over connection string options._ - * - * @param {Object} passed options that were passed directly during connection - * @param {Object} [connStrOptions] options that were passed in the connection string - * @api private - */ - -NativeConnection.prototype.parseOptions = function (passed, connStrOpts) { - var o = passed || {}; - o.db || (o.db = {}); - o.auth || (o.auth = {}); - o.server || (o.server = {}); - o.replset || (o.replset = {}); - o.server.socketOptions || (o.server.socketOptions = {}); - o.replset.socketOptions || (o.replset.socketOptions = {}); - - var opts = connStrOpts || {}; - Object.keys(opts).forEach(function (name) { - switch (name) { - case 'poolSize': - if ('undefined' == typeof o.server.poolSize) { - o.server.poolSize = o.replset.poolSize = opts[name]; - } - break; - case 'slaveOk': - if ('undefined' == typeof o.server.slave_ok) { - o.server.slave_ok = opts[name]; - } - break; - case 'autoReconnect': - if ('undefined' == typeof o.server.auto_reconnect) { - o.server.auto_reconnect = opts[name]; - } - break; - case 'ssl': - case 'socketTimeoutMS': - case 'connectTimeoutMS': - if ('undefined' == typeof o.server.socketOptions[name]) { - o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name]; - } - break; - case 'authdb': - if ('undefined' == typeof o.auth.authdb) { - o.auth.authdb = opts[name]; - } - break; - case 'authSource': - if ('undefined' == typeof o.auth.authSource) { - o.auth.authSource = opts[name]; - } - break; - case 'retries': - case 'reconnectWait': - case 'rs_name': - if ('undefined' == typeof o.replset[name]) { - o.replset[name] = opts[name]; - } - break; - case 'replicaSet': - if ('undefined' == typeof o.replset.rs_name) { - o.replset.rs_name = opts[name]; - } - break; - case 'readSecondary': - if ('undefined' == typeof o.replset.read_secondary) { - o.replset.read_secondary = opts[name]; - } - break; - case 'nativeParser': - if ('undefined' == typeof o.db.native_parser) { - o.db.native_parser = opts[name]; - } - break; - case 'w': - case 'safe': - case 'fsync': - case 'journal': - case 'wtimeoutMS': - if ('undefined' == typeof o.db[name]) { - o.db[name] = opts[name]; - } - break; - case 'readPreference': - if ('undefined' == typeof o.db.read_preference) { - o.db.read_preference = opts[name]; - } - break; - case 'readPreferenceTags': - if ('undefined' == typeof o.db.read_preference_tags) { - o.db.read_preference_tags = opts[name]; - } - break; - } - }) - - if (!('auto_reconnect' in o.server)) { - o.server.auto_reconnect = true; - } - - if (!o.db.read_preference) { - // read from primaries by default - o.db.read_preference = 'primary'; - } - - // mongoose creates its own ObjectIds - o.db.forceServerObjectId = false; - - // default safe using new nomenclature - if (!('journal' in o.db || 'j' in o.db || - 'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) { - o.db.w = 1; - } - - validate(o); - return o; -} - -/*! - * Validates the driver db options. - * - * @param {Object} o - */ - -function validate (o) { - if (-1 === o.db.w || 0 === o.db.w) { - if (o.db.journal || o.db.fsync || o.db.safe) { - throw new Error( - 'Invalid writeConcern: ' - + 'w set to -1 or 0 cannot be combined with safe|fsync|journal'); - } - } -} - -/*! - * Module exports. - */ - -module.exports = NativeConnection; diff --git a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js b/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js deleted file mode 100644 index d00e00768..000000000 --- a/node_modules/mongoose/lib/drivers/node-mongodb-native/objectid.js +++ /dev/null @@ -1,15 +0,0 @@ - -/*! - * [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) ObjectId - * @constructor NodeMongoDbObjectId - * @see ObjectId - */ - -var ObjectId = require('mongodb').BSONPure.ObjectID; - -/*! - * ignore - */ - -module.exports = exports = ObjectId; - diff --git a/node_modules/mongoose/lib/error.js b/node_modules/mongoose/lib/error.js deleted file mode 100644 index f4e308c41..000000000 --- a/node_modules/mongoose/lib/error.js +++ /dev/null @@ -1,63 +0,0 @@ - -/** - * MongooseError constructor - * - * @param {String} msg Error message - * @inherits Error https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error - */ - -function MongooseError (msg) { - Error.call(this); - Error.captureStackTrace(this, arguments.callee); - this.message = msg; - this.name = 'MongooseError'; -}; - -/*! - * Formats error messages - */ - -MongooseError.prototype.formatMessage = function (msg, path, type, val) { - if (!msg) throw new TypeError('message is required'); - - return msg.replace(/{PATH}/, path) - .replace(/{VALUE}/, String(val||'')) - .replace(/{TYPE}/, type || 'declared type'); -} - -/*! - * Inherits from Error. - */ - -MongooseError.prototype.__proto__ = Error.prototype; - -/*! - * Module exports. - */ - -module.exports = exports = MongooseError; - -/** - * The default built-in validator error messages. - * - * @see Error.messages #error_messages_MongooseError-messages - * @api public - */ - -MongooseError.messages = require('./error/messages'); - -// backward compat -MongooseError.Messages = MongooseError.messages; - -/*! - * Expose subclasses - */ - -MongooseError.CastError = require('./error/cast'); -MongooseError.ValidationError = require('./error/validation') -MongooseError.ValidatorError = require('./error/validator') -MongooseError.VersionError =require('./error/version') -MongooseError.OverwriteModelError = require('./error/overwriteModel') -MongooseError.MissingSchemaError = require('./error/missingSchema') -MongooseError.DivergentArrayError = require('./error/divergentArray') - diff --git a/node_modules/mongoose/lib/error/cast.js b/node_modules/mongoose/lib/error/cast.js deleted file mode 100644 index 9e383fa0a..000000000 --- a/node_modules/mongoose/lib/error/cast.js +++ /dev/null @@ -1,35 +0,0 @@ -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/** - * Casting Error constructor. - * - * @param {String} type - * @param {String} value - * @inherits MongooseError - * @api private - */ - -function CastError (type, value, path) { - MongooseError.call(this, 'Cast to ' + type + ' failed for value "' + value + '" at path "' + path + '"'); - Error.captureStackTrace(this, arguments.callee); - this.name = 'CastError'; - this.type = type; - this.value = value; - this.path = path; -}; - -/*! - * Inherits from MongooseError. - */ - -CastError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = CastError; diff --git a/node_modules/mongoose/lib/error/divergentArray.js b/node_modules/mongoose/lib/error/divergentArray.js deleted file mode 100644 index 5fe0db6e6..000000000 --- a/node_modules/mongoose/lib/error/divergentArray.js +++ /dev/null @@ -1,40 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/*! - * DivergentArrayError constructor. - * - * @inherits MongooseError - */ - -function DivergentArrayError (paths) { - var msg = 'For your own good, using `document.save()` to update an array ' - + 'which was selected using an $elemMatch projection OR ' - + 'populated using skip, limit, query conditions, or exclusion of ' - + 'the _id field when the operation results in a $pop or $set of ' - + 'the entire array is not supported. The following ' - + 'path(s) would have been modified unsafely:\n' - + ' ' + paths.join('\n ') + '\n' - + 'Use Model.update() to update these arrays instead.' - // TODO write up a docs page (FAQ) and link to it - - MongooseError.call(this, msg); - Error.captureStackTrace(this, arguments.callee); - this.name = 'DivergentArrayError'; -}; - -/*! - * Inherits from MongooseError. - */ - -DivergentArrayError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = DivergentArrayError; diff --git a/node_modules/mongoose/lib/error/messages.js b/node_modules/mongoose/lib/error/messages.js deleted file mode 100644 index ccafb81f2..000000000 --- a/node_modules/mongoose/lib/error/messages.js +++ /dev/null @@ -1,37 +0,0 @@ - -/** - * The default built-in validator error messages. These may be customized. - * - * // customize within each schema or globally like so - * var mongoose = require('mongoose'); - * mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; - * - * As you might have noticed, error messages support basic templating - * - * - `{PATH}` is replaced with the invalid document path - * - `{VALUE}` is replaced with the invalid value - * - `{TYPE}` is replaced with the validator type such as "regexp", "min", or "user defined" - * - `{MIN}` is replaced with the declared min value for the Number.min validator - * - `{MAX}` is replaced with the declared max value for the Number.max validator - * - * Click the "show code" link below to see all defaults. - * - * @property messages - * @receiver MongooseError - * @api public - */ - -var msg = module.exports = exports = {}; - -msg.general = {}; -msg.general.default = "Validator failed for path `{PATH}` with value `{VALUE}`"; -msg.general.required = "Path `{PATH}` is required."; - -msg.Number = {}; -msg.Number.min = "Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN})."; -msg.Number.max = "Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX})."; - -msg.String = {}; -msg.String.enum = "`{VALUE}` is not a valid enum value for path `{PATH}`."; -msg.String.match = "Path `{PATH}` is invalid ({VALUE})."; - diff --git a/node_modules/mongoose/lib/error/missingSchema.js b/node_modules/mongoose/lib/error/missingSchema.js deleted file mode 100644 index 7d80e2f9c..000000000 --- a/node_modules/mongoose/lib/error/missingSchema.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/*! - * MissingSchema Error constructor. - * - * @inherits MongooseError - */ - -function MissingSchemaError (name) { - var msg = 'Schema hasn\'t been registered for model "' + name + '".\n' - + 'Use mongoose.model(name, schema)'; - MongooseError.call(this, msg); - Error.captureStackTrace(this, arguments.callee); - this.name = 'MissingSchemaError'; -}; - -/*! - * Inherits from MongooseError. - */ - -MissingSchemaError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = MissingSchemaError; diff --git a/node_modules/mongoose/lib/error/overwriteModel.js b/node_modules/mongoose/lib/error/overwriteModel.js deleted file mode 100644 index ee13cb918..000000000 --- a/node_modules/mongoose/lib/error/overwriteModel.js +++ /dev/null @@ -1,30 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/*! - * OverwriteModel Error constructor. - * - * @inherits MongooseError - */ - -function OverwriteModelError (name) { - MongooseError.call(this, 'Cannot overwrite `' + name + '` model once compiled.'); - Error.captureStackTrace(this, arguments.callee); - this.name = 'OverwriteModelError'; -}; - -/*! - * Inherits from MongooseError. - */ - -OverwriteModelError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = OverwriteModelError; diff --git a/node_modules/mongoose/lib/error/validation.js b/node_modules/mongoose/lib/error/validation.js deleted file mode 100644 index b05706c47..000000000 --- a/node_modules/mongoose/lib/error/validation.js +++ /dev/null @@ -1,49 +0,0 @@ - -/*! - * Module requirements - */ - -var MongooseError = require('../error.js') - -/** - * Document Validation Error - * - * @api private - * @param {Document} instance - * @inherits MongooseError - */ - -function ValidationError (instance) { - MongooseError.call(this, "Validation failed"); - Error.captureStackTrace(this, arguments.callee); - this.name = 'ValidationError'; - this.errors = instance.errors = {}; -}; - -/** - * Console.log helper - */ - -ValidationError.prototype.toString = function () { - var ret = this.name + ': '; - var msgs = []; - - Object.keys(this.errors).forEach(function (key) { - if (this == this.errors[key]) return; - msgs.push(String(this.errors[key])); - }, this) - - return ret + msgs.join(', '); -}; - -/*! - * Inherits from MongooseError. - */ - -ValidationError.prototype.__proto__ = MongooseError.prototype; - -/*! - * Module exports - */ - -module.exports = exports = ValidationError; diff --git a/node_modules/mongoose/lib/error/validator.js b/node_modules/mongoose/lib/error/validator.js deleted file mode 100644 index 965c00c6f..000000000 --- a/node_modules/mongoose/lib/error/validator.js +++ /dev/null @@ -1,47 +0,0 @@ -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); -var errorMessages = MongooseError.messages; - -/** - * Schema validator error - * - * @param {String} path - * @param {String} msg - * @param {String|Number|any} val - * @inherits MongooseError - * @api private - */ - -function ValidatorError (path, msg, type, val) { - if (!msg) msg = errorMessages.general.default; - var message = this.formatMessage(msg, path, type, val); - MongooseError.call(this, message); - Error.captureStackTrace(this, arguments.callee); - this.name = 'ValidatorError'; - this.path = path; - this.type = type; - this.value = val; -}; - -/*! - * toString helper - */ - -ValidatorError.prototype.toString = function () { - return this.message; -} - -/*! - * Inherits from MongooseError - */ - -ValidatorError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = ValidatorError; diff --git a/node_modules/mongoose/lib/error/version.js b/node_modules/mongoose/lib/error/version.js deleted file mode 100644 index 514e4dc0b..000000000 --- a/node_modules/mongoose/lib/error/version.js +++ /dev/null @@ -1,31 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseError = require('../error.js'); - -/** - * Version Error constructor. - * - * @inherits MongooseError - * @api private - */ - -function VersionError () { - MongooseError.call(this, 'No matching document found.'); - Error.captureStackTrace(this, arguments.callee); - this.name = 'VersionError'; -}; - -/*! - * Inherits from MongooseError. - */ - -VersionError.prototype.__proto__ = MongooseError.prototype; - -/*! - * exports - */ - -module.exports = VersionError; diff --git a/node_modules/mongoose/lib/index.js b/node_modules/mongoose/lib/index.js deleted file mode 100644 index c52ee0cc2..000000000 --- a/node_modules/mongoose/lib/index.js +++ /dev/null @@ -1,641 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var Schema = require('./schema') - , SchemaType = require('./schematype') - , VirtualType = require('./virtualtype') - , SchemaDefaults = require('./schemadefault') - , Types = require('./types') - , Query = require('./query') - , Promise = require('./promise') - , Model = require('./model') - , Document = require('./document') - , utils = require('./utils') - , format = utils.toCollectionName - , mongodb = require('mongodb') - , pkg = require('../package.json') - -/*! - * Warn users if they are running an unstable release. - * - * Disable the warning by setting the MONGOOSE_DISABLE_STABILITY_WARNING - * environment variable. - */ - -if (pkg.publishConfig && 'unstable' == pkg.publishConfig.tag) { - if (!process.env.MONGOOSE_DISABLE_STABILITY_WARNING) { - console.log('\u001b[33m'); - console.log('##############################################################'); - console.log('#'); - console.log('# !!! MONGOOSE WARNING !!!'); - console.log('#'); - console.log('# This is an UNSTABLE release of Mongoose.'); - console.log('# Unstable releases are available for preview/testing only.'); - console.log('# DO NOT run this in production.'); - console.log('#'); - console.log('##############################################################'); - console.log('\u001b[0m'); - } -} - -/** - * Mongoose constructor. - * - * The exports object of the `mongoose` module is an instance of this class. - * Most apps will only use this one instance. - * - * @api public - */ - -function Mongoose () { - this.connections = []; - this.plugins = []; - this.models = {}; - this.modelSchemas = {}; - // default global options - this.options = { - pluralization: true - }; - this.createConnection(); // default connection -}; - -/** - * Sets mongoose options - * - * ####Example: - * - * mongoose.set('test', value) // sets the 'test' option to `value` - * - * mongoose.set('debug', true) // enable logging collection methods + arguments to the console - * - * @param {String} key - * @param {String} value - * @api public - */ - -Mongoose.prototype.set = function (key, value) { - if (arguments.length == 1) { - return this.options[key]; - } - - this.options[key] = value; - return this; -}; - -/** - * Gets mongoose options - * - * ####Example: - * - * mongoose.get('test') // returns the 'test' value - * - * @param {String} key - * @method get - * @api public - */ - -Mongoose.prototype.get = Mongoose.prototype.set; - -/*! - * ReplSet connection string check. - */ - -var rgxReplSet = /^.+,.+$/; - -/** - * Creates a Connection instance. - * - * Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections. - * - * If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. This means we can pass `db`, `server`, and `replset` options to the driver. _Note that the `safe` option specified in your schema will overwrite the `safe` db option specified here unless you set your schemas `safe` option to `undefined`. See [this](/docs/guide.html#safe) for more information._ - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Example: - * - * // with mongodb:// URI - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); - * - * // and options - * var opts = { db: { native_parser: true }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts); - * - * // replica sets - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port'); - * - * // and options - * var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }} - * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', opts); - * - * // with [host, database_name[, port] signature - * db = mongoose.createConnection('localhost', 'database', port) - * - * // and options - * var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' } - * db = mongoose.createConnection('localhost', 'database', port, opts) - * - * // initialize now, connect later - * db = mongoose.createConnection(); - * db.open('localhost', 'database', port, [opts]); - * - * @param {String} [uri] a mongodb:// URI - * @param {Object} [options] options to pass to the driver - * @see Connection#open #connection_Connection-open - * @see Connection#openSet #connection_Connection-openSet - * @return {Connection} the created Connection object - * @api public - */ - -Mongoose.prototype.createConnection = function () { - var conn = new Connection(this); - this.connections.push(conn); - - if (arguments.length) { - if (rgxReplSet.test(arguments[0])) { - conn.openSet.apply(conn, arguments); - } else { - conn.open.apply(conn, arguments); - } - } - - return conn; -}; - -/** - * Opens the default mongoose connection. - * - * If arguments are passed, they are proxied to either [Connection#open](#connection_Connection-open) or [Connection#openSet](#connection_Connection-openSet) appropriately. - * - * _Options passed take precedence over options included in connection strings._ - * - * ####Example: - * - * mongoose.connect('mongodb://user:pass@localhost:port/database'); - * - * // replica sets - * var uri = 'mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port'; - * mongoose.connect(uri); - * - * // with options - * mongoose.connect(uri, options); - * - * // connecting to multiple mongos - * var uri = 'mongodb://hostA:27501,hostB:27501'; - * var opts = { mongos: true }; - * mongoose.connect(uri, opts); - * - * @param {String} uri(s) - * @param {Object} [options] - * @param {Function} [callback] - * @see Mongoose#createConnection #index_Mongoose-createConnection - * @api public - * @return {Mongoose} this - */ - -Mongoose.prototype.connect = function () { - var conn = this.connection; - - if (rgxReplSet.test(arguments[0])) { - conn.openSet.apply(conn, arguments); - } else { - conn.open.apply(conn, arguments); - } - - return this; -}; - -/** - * Disconnects all connections. - * - * @param {Function} [fn] called after all connection close. - * @return {Mongoose} this - * @api public - */ - -Mongoose.prototype.disconnect = function (fn) { - var count = this.connections.length - , error - - this.connections.forEach(function(conn){ - conn.close(function(err){ - if (error) return; - - if (err) { - error = err; - if (fn) return fn(err); - throw err; - } - - if (fn) - --count || fn(); - }); - }); - return this; -}; - -/** - * Defines a model or retrieves it. - * - * Models defined on the `mongoose` instance are available to all connection created by the same `mongoose` instance. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * - * // define an Actor model with this mongoose instance - * mongoose.model('Actor', new Schema({ name: String })); - * - * // create a new connection - * var conn = mongoose.createConnection(..); - * - * // retrieve the Actor model - * var Actor = conn.model('Actor'); - * - * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports.toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._ - * - * ####Example: - * - * var schema = new Schema({ name: String }, { collection: 'actor' }); - * - * // or - * - * schema.set('collection', 'actor'); - * - * // or - * - * var collectionName = 'actor' - * var M = mongoose.model('Actor', schema, collectionName) - * - * @param {String} name model name - * @param {Schema} [schema] - * @param {String} [collection] name (optional, induced from model name) - * @param {Boolean} [skipInit] whether to skip initialization (defaults to false) - * @api public - */ - -Mongoose.prototype.model = function (name, schema, collection, skipInit) { - if ('string' == typeof schema) { - collection = schema; - schema = false; - } - - if (utils.isObject(schema) && !(schema instanceof Schema)) { - schema = new Schema(schema); - } - - if ('boolean' === typeof collection) { - skipInit = collection; - collection = null; - } - - // handle internal options from connection.model() - var options; - if (skipInit && utils.isObject(skipInit)) { - options = skipInit; - skipInit = true; - } else { - options = {}; - } - - // look up schema for the collection. this might be a - // default schema like system.indexes stored in SchemaDefaults. - if (!this.modelSchemas[name]) { - if (!schema && name in SchemaDefaults) { - schema = SchemaDefaults[name]; - } - - if (schema) { - // cache it so we only apply plugins once - this.modelSchemas[name] = schema; - this._applyPlugins(schema); - } else { - throw new mongoose.Error.MissingSchemaError(name); - } - } - - var model; - var sub; - - // connection.model() may be passing a different schema for - // an existing model name. in this case don't read from cache. - if (this.models[name] && false !== options.cache) { - if (schema instanceof Schema && schema != this.models[name].schema) { - throw new mongoose.Error.OverwriteModelError(name); - } - - if (collection) { - // subclass current model with alternate collection - model = this.models[name]; - schema = model.prototype.schema; - sub = model.__subclass(this.connection, schema, collection); - // do not cache the sub model - return sub; - } - - return this.models[name]; - } - - // ensure a schema exists - if (!schema) { - schema = this.modelSchemas[name]; - if (!schema) { - throw new mongoose.Error.MissingSchemaError(name); - } - } - - // Apply relevant "global" options to the schema - if (!('pluralization' in schema.options)) schema.options.pluralization = this.options.pluralization; - - - if (!collection) { - collection = schema.get('collection') || format(name, schema.options); - } - - var connection = options.connection || this.connection; - model = Model.compile(name, schema, collection, connection, this); - - if (!skipInit) { - model.init(); - } - - if (false === options.cache) { - return model; - } - - return this.models[name] = model; -} - -/** - * Returns an array of model names created on this instance of Mongoose. - * - * ####Note: - * - * _Does not include names of models created using `connection.model()`._ - * - * @api public - * @return {Array} - */ - -Mongoose.prototype.modelNames = function () { - var names = Object.keys(this.models); - return names; -} - -/** - * Applies global plugins to `schema`. - * - * @param {Schema} schema - * @api private - */ - -Mongoose.prototype._applyPlugins = function (schema) { - for (var i = 0, l = this.plugins.length; i < l; i++) { - schema.plugin(this.plugins[i][0], this.plugins[i][1]); - } -} - -/** - * Declares a global plugin executed on all Schemas. - * - * Equivalent to calling `.plugin(fn)` on each Schema you create. - * - * @param {Function} fn plugin callback - * @param {Object} [opts] optional options - * @return {Mongoose} this - * @see plugins ./plugins.html - * @api public - */ - -Mongoose.prototype.plugin = function (fn, opts) { - this.plugins.push([fn, opts]); - return this; -}; - -/** - * The default connection of the mongoose module. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * mongoose.connect(...); - * mongoose.connection.on('error', cb); - * - * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model). - * - * @property connection - * @return {Connection} - * @api public - */ - -Mongoose.prototype.__defineGetter__('connection', function(){ - return this.connections[0]; -}); - -/*! - * Driver depentend APIs - */ - -var driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native'; - -/*! - * Connection - */ - -var Connection = require(driver + '/connection'); - -/*! - * Collection - */ - -var Collection = require(driver + '/collection'); - -/** - * The Mongoose Collection constructor - * - * @method Collection - * @api public - */ - -Mongoose.prototype.Collection = Collection; - -/** - * The Mongoose [Connection](#connection_Connection) constructor - * - * @method Connection - * @api public - */ - -Mongoose.prototype.Connection = Connection; - -/** - * The Mongoose version - * - * @property version - * @api public - */ - -Mongoose.prototype.version = pkg.version; - -/** - * The Mongoose constructor - * - * The exports of the mongoose module is an instance of this class. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var mongoose2 = new mongoose.Mongoose(); - * - * @method Mongoose - * @api public - */ - -Mongoose.prototype.Mongoose = Mongoose; - -/** - * The Mongoose [Schema](#schema_Schema) constructor - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var Schema = mongoose.Schema; - * var CatSchema = new Schema(..); - * - * @method Schema - * @api public - */ - -Mongoose.prototype.Schema = Schema; - -/** - * The Mongoose [SchemaType](#schematype_SchemaType) constructor - * - * @method SchemaType - * @api public - */ - -Mongoose.prototype.SchemaType = SchemaType; - -/** - * The various Mongoose SchemaTypes. - * - * ####Note: - * - * _Alias of mongoose.Schema.Types for backwards compatibility._ - * - * @property SchemaTypes - * @see Schema.SchemaTypes #schema_Schema.Types - * @api public - */ - -Mongoose.prototype.SchemaTypes = Schema.Types; - -/** - * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor - * - * @method VirtualType - * @api public - */ - -Mongoose.prototype.VirtualType = VirtualType; - -/** - * The various Mongoose Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var array = mongoose.Types.Array; - * - * ####Types: - * - * - [ObjectId](#types-objectid-js) - * - [Buffer](#types-buffer-js) - * - [SubDocument](#types-embedded-js) - * - [Array](#types-array-js) - * - [DocumentArray](#types-documentarray-js) - * - * Using this exposed access to the `ObjectId` type, we can construct ids on demand. - * - * var ObjectId = mongoose.Types.ObjectId; - * var id1 = new ObjectId; - * - * @property Types - * @api public - */ - -Mongoose.prototype.Types = Types; - -/** - * The Mongoose [Query](#query_Query) constructor. - * - * @method Query - * @api public - */ - -Mongoose.prototype.Query = Query; - -/** - * The Mongoose [Promise](#promise_Promise) constructor. - * - * @method Promise - * @api public - */ - -Mongoose.prototype.Promise = Promise; - -/** - * The Mongoose [Model](#model_Model) constructor. - * - * @method Model - * @api public - */ - -Mongoose.prototype.Model = Model; - -/** - * The Mongoose [Document](#document-js) constructor. - * - * @method Document - * @api public - */ - -Mongoose.prototype.Document = Document; - -/** - * The [MongooseError](#error_MongooseError) constructor. - * - * @method Error - * @api public - */ - -Mongoose.prototype.Error = require('./error'); - -/** - * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses. - * - * @property mongo - * @api public - */ - -Mongoose.prototype.mongo = require('mongodb'); - -/** - * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses. - * - * @property mquery - * @api public - */ - -Mongoose.prototype.mquery = require('mquery'); - -/*! - * The exports object is an instance of Mongoose. - * - * @api public - */ - -var mongoose = module.exports = exports = new Mongoose; diff --git a/node_modules/mongoose/lib/internal.js b/node_modules/mongoose/lib/internal.js deleted file mode 100644 index d5a3f1246..000000000 --- a/node_modules/mongoose/lib/internal.js +++ /dev/null @@ -1,31 +0,0 @@ -/*! - * Dependencies - */ - -var StateMachine = require('./statemachine') -var ActiveRoster = StateMachine.ctor('require', 'modify', 'init', 'default') - -module.exports = exports = InternalCache; - -function InternalCache () { - this.strictMode = undefined; - this.selected = undefined; - this.shardval = undefined; - this.saveError = undefined; - this.validationError = undefined; - this.adhocPaths = undefined; - this.removing = undefined; - this.inserting = undefined; - this.version = undefined; - this.getters = {}; - this._id = undefined; - this.populate = undefined; // what we want to populate in this doc - this.populated = undefined;// the _ids that have been populated - this.wasPopulated = false; // if this doc was the result of a population - this.scope = undefined; - this.activePaths = new ActiveRoster; - - // embedded docs - this.ownerDocument = undefined; - this.fullPath = undefined; -} diff --git a/node_modules/mongoose/lib/model.js b/node_modules/mongoose/lib/model.js deleted file mode 100644 index 07a69d24d..000000000 --- a/node_modules/mongoose/lib/model.js +++ /dev/null @@ -1,2586 +0,0 @@ -/*! - * Module dependencies. - */ - -var Document = require('./document') - , MongooseArray = require('./types/array') - , MongooseBuffer = require('./types/buffer') - , MongooseError = require('./error') - , VersionError = MongooseError.VersionError - , DivergentArrayError = MongooseError.DivergentArrayError - , Query = require('./query') - , Aggregate = require('./aggregate') - , Schema = require('./schema') - , Types = require('./schema/index') - , utils = require('./utils') - , hasOwnProperty = utils.object.hasOwnProperty - , isMongooseObject = utils.isMongooseObject - , EventEmitter = require('events').EventEmitter - , merge = utils.merge - , Promise = require('./promise') - , assert = require('assert') - , util = require('util') - , tick = utils.tick - , Query = require('./query.js') - -var VERSION_WHERE = 1 - , VERSION_INC = 2 - , VERSION_ALL = VERSION_WHERE | VERSION_INC; - -/** - * Model constructor - * - * Provides the interface to MongoDB collections as well as creates document instances. - * - * @param {Object} doc values with which to create the document - * @inherits Document - * @event `error`: If listening to this event, it is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. - * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. - * @api public - */ - -function Model (doc, fields, skipId) { - Document.call(this, doc, fields, skipId); -}; - -/*! - * Inherits from Document. - * - * All Model.prototype features are available on - * top level (non-sub) documents. - */ - -Model.prototype.__proto__ = Document.prototype; - -/** - * Connection the model uses. - * - * @api public - * @property db - */ - -Model.prototype.db; - -/** - * Collection the model uses. - * - * @api public - * @property collection - */ - -Model.prototype.collection; - -/** - * The name of the model - * - * @api public - * @property modelName - */ - -Model.prototype.modelName; - -/*! - * Handles doc.save() callbacks - */ - -function handleSave (promise, self) { - return tick(function handleSave (err, result) { - if (err) { - // If the initial insert fails provide a second chance. - // (If we did this all the time we would break updates) - if (self.$__.inserting) { - self.isNew = true; - self.emit('isNew', true); - } - promise.error(err); - promise = self = null; - return; - } - - self.$__storeShard(); - - var numAffected; - if (result) { - // when inserting, the array of created docs is returned - numAffected = result.length - ? result.length - : result; - } else { - numAffected = 0; - } - - // was this an update that required a version bump? - if (self.$__.version && !self.$__.inserting) { - var doIncrement = VERSION_INC === (VERSION_INC & self.$__.version); - self.$__.version = undefined; - - // increment version if was successful - if (numAffected > 0) { - if (doIncrement) { - var key = self.schema.options.versionKey; - var version = self.getValue(key) | 0; - self.setValue(key, version + 1); - } - } else { - // the update failed. pass an error back - promise.error(new VersionError); - promise = self = null; - return; - } - } - - self.emit('save', self, numAffected); - promise.complete(self, numAffected); - promise = self = null; - }); -} - -/** - * Saves this document. - * - * ####Example: - * - * product.sold = Date.now(); - * product.save(function (err, product, numberAffected) { - * if (err) .. - * }) - * - * The callback will receive three parameters, `err` if an error occurred, `product` which is the saved `product`, and `numberAffected` which will be 1 when the document was found and updated in the database, otherwise 0. - * - * The `fn` callback is optional. If no `fn` is passed and validation fails, the validation error will be emitted on the connection used to create this model. - * - * var db = mongoose.createConnection(..); - * var schema = new Schema(..); - * var Product = db.model('Product', schema); - * - * db.on('error', handleError); - * - * However, if you desire more local error handling you can add an `error` listener to the model and handle errors there instead. - * - * Product.on('error', handleError); - * - * @param {Function} [fn] optional callback - * @api public - * @see middleware http://mongoosejs.com/docs/middleware.html - */ - -Model.prototype.save = function save (fn) { - var promise = new Promise(fn) - , complete = handleSave(promise, this) - , options = {} - - if (this.schema.options.safe) { - options.safe = this.schema.options.safe; - } - - if (this.isNew) { - // send entire doc - var obj = this.toObject({ depopulate: 1 }); - - if (!utils.object.hasOwnProperty(obj || {}, '_id')) { - // documents must have an _id else mongoose won't know - // what to update later if more changes are made. the user - // wouldn't know what _id was generated by mongodb either - // nor would the ObjectId generated my mongodb necessarily - // match the schema definition. - return complete(new Error('document must have an _id before saving')); - } - - this.$__version(true, obj); - this.collection.insert(obj, options, complete); - this.$__reset(); - this.isNew = false; - this.emit('isNew', false); - // Make it possible to retry the insert - this.$__.inserting = true; - - } else { - // Make sure we don't treat it as a new object on error, - // since it already exists - this.$__.inserting = false; - - var delta = this.$__delta(); - - if (delta) { - if (delta instanceof Error) return complete(delta); - var where = this.$__where(delta[0]); - this.$__reset(); - this.collection.update(where, delta[1], options, complete); - } else { - this.$__reset(); - complete(null); - } - - this.emit('isNew', false); - } -}; - -/*! - * Apply the operation to the delta (update) clause as - * well as track versioning for our where clause. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Mixed} val - * @param {String} [operation] - */ - -function operand (self, where, delta, data, val, op) { - // delta - op || (op = '$set'); - if (!delta[op]) delta[op] = {}; - delta[op][data.path] = val; - - // disabled versioning? - if (false === self.schema.options.versionKey) return; - - // already marked for versioning? - if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; - - switch (op) { - case '$set': - case '$unset': - case '$pop': - case '$pull': - case '$pullAll': - case '$push': - case '$pushAll': - case '$addToSet': - break; - default: - // nothing to do - return; - } - - // ensure updates sent with positional notation are - // editing the correct array element. - // only increment the version if an array position changes. - // modifying elements of an array is ok if position does not change. - - if ('$push' == op || '$pushAll' == op || '$addToSet' == op) { - self.$__.version = VERSION_INC; - } - else if (/^\$p/.test(op)) { - // potentially changing array positions - self.increment(); - } - else if (Array.isArray(val)) { - // $set an array - self.increment(); - } - // now handling $set, $unset - else if (/\.\d+\.|\.\d+$/.test(data.path)) { - // subpath of array - self.$__.version = VERSION_WHERE; - } -} - -/*! - * Compiles an update and where clause for a `val` with _atomics. - * - * @param {Document} self - * @param {Object} where - * @param {Object} delta - * @param {Object} data - * @param {Array} value - */ - -function handleAtomics (self, where, delta, data, value) { - if (delta.$set && delta.$set[data.path]) { - // $set has precedence over other atomics - return; - } - - if ('function' == typeof value.$__getAtomics) { - value.$__getAtomics().forEach(function (atomic) { - var op = atomic[0]; - var val = atomic[1]; - operand(self, where, delta, data, val, op); - }) - return; - } - - // legacy support for plugins - - var atomics = value._atomics - , ops = Object.keys(atomics) - , i = ops.length - , val - , op; - - if (0 === i) { - // $set - - if (isMongooseObject(value)) { - value = value.toObject({ depopulate: 1 }); - } else if (value.valueOf) { - value = value.valueOf(); - } - - return operand(self, where, delta, data, value); - } - - while (i--) { - op = ops[i]; - val = atomics[op]; - - if (isMongooseObject(val)) { - val = val.toObject({ depopulate: 1 }) - } else if (Array.isArray(val)) { - val = val.map(function (mem) { - return isMongooseObject(mem) - ? mem.toObject({ depopulate: 1 }) - : mem; - }) - } else if (val.valueOf) { - val = val.valueOf() - } - - if ('$addToSet' === op) - val = { $each: val }; - - operand(self, where, delta, data, val, op); - } -} - -/** - * Produces a special query document of the modified properties used in updates. - * - * @api private - * @method $__delta - * @memberOf Model - */ - -Model.prototype.$__delta = function () { - var dirty = this.$__dirty(); - if (!dirty.length && VERSION_ALL != this.$__.version) return; - - var where = {} - , delta = {} - , len = dirty.length - , divergent = [] - , d = 0 - , val - , obj - - for (; d < len; ++d) { - var data = dirty[d] - var value = data.value - var schema = data.schema - - var match = checkDivergentArray(this, data.path, value); - if (match) { - divergent.push(match); - continue; - } - - if (divergent.length) continue; - - if (undefined === value) { - operand(this, where, delta, data, 1, '$unset'); - - } else if (null === value) { - operand(this, where, delta, data, null); - - } else if (value._path && value._atomics) { - // arrays and other custom types (support plugins etc) - handleAtomics(this, where, delta, data, value); - - } else if (value._path && Buffer.isBuffer(value)) { - // MongooseBuffer - value = value.toObject(); - operand(this, where, delta, data, value); - - } else { - value = utils.clone(value, { depopulate: 1 }); - operand(this, where, delta, data, value); - } - } - - if (divergent.length) { - return new DivergentArrayError(divergent); - } - - if (this.$__.version) { - this.$__version(where, delta); - } - - return [where, delta]; -} - -/*! - * Determine if array was populated with some form of filter and is now - * being updated in a manner which could overwrite data unintentionally. - * - * @see https://github.com/LearnBoost/mongoose/issues/1334 - * @param {Document} doc - * @param {String} path - * @return {String|undefined} - */ - -function checkDivergentArray (doc, path, array) { - // see if we populated this path - var pop = doc.populated(path, true); - - if (!pop && doc.$__.selected) { - // If any array was selected using an $elemMatch projection, we deny the update. - // NOTE: MongoDB only supports projected $elemMatch on top level array. - var top = path.split('.')[0]; - if (doc.$__.selected[top] && doc.$__.selected[top].$elemMatch) { - return top; - } - } - - if (!(pop && array instanceof MongooseArray)) return; - - // If the array was populated using options that prevented all - // documents from being returned (match, skip, limit) or they - // deselected the _id field, $pop and $set of the array are - // not safe operations. If _id was deselected, we do not know - // how to remove elements. $pop will pop off the _id from the end - // of the array in the db which is not guaranteed to be the - // same as the last element we have here. $set of the entire array - // would be similarily destructive as we never received all - // elements of the array and potentially would overwrite data. - var check = pop.options.match || - pop.options.options && hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted - pop.options.options && pop.options.options.skip || // 0 is permitted - pop.options.select && // deselected _id? - (0 === pop.options.select._id || - /\s?-_id\s?/.test(pop.options.select)) - - if (check) { - var atomics = array._atomics; - if (0 === Object.keys(atomics).length || atomics.$set || atomics.$pop) { - return path; - } - } -} - -/** - * Appends versioning to the where and update clauses. - * - * @api private - * @method $__version - * @memberOf Model - */ - -Model.prototype.$__version = function (where, delta) { - var key = this.schema.options.versionKey; - - if (true === where) { - // this is an insert - if (key) this.setValue(key, delta[key] = 0); - return; - } - - // updates - - // only apply versioning if our versionKey was selected. else - // there is no way to select the correct version. we could fail - // fast here and force them to include the versionKey but - // thats a bit intrusive. can we do this automatically? - if (!this.isSelected(key)) { - return; - } - - // $push $addToSet don't need the where clause set - if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { - where[key] = this.getValue(key); - } - - if (VERSION_INC === (VERSION_INC & this.$__.version)) { - delta.$inc || (delta.$inc = {}); - delta.$inc[key] = 1; - } -} - -/** - * Signal that we desire an increment of this documents version. - * - * ####Example: - * - * Model.findById(id, function (err, doc) { - * doc.increment(); - * doc.save(function (err) { .. }) - * }) - * - * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey - * @api public - */ - -Model.prototype.increment = function increment () { - this.$__.version = VERSION_ALL; - return this; -} - -/** - * Returns a query object which applies shardkeys if they exist. - * - * @api private - * @method $__where - * @memberOf Model - */ - -Model.prototype.$__where = function _where (where) { - where || (where = {}); - - var paths - , len - - if (this.$__.shardval) { - paths = Object.keys(this.$__.shardval) - len = paths.length - - for (var i = 0; i < len; ++i) { - where[paths[i]] = this.$__.shardval[paths[i]]; - } - } - - where._id = this._doc._id; - return where; -} - -/** - * Removes this document from the db. - * - * ####Example: - * - * product.remove(function (err, product) { - * if (err) return handleError(err); - * Product.findById(product._id, function (err, product) { - * console.log(product) // null - * }) - * }) - * - * @param {Function} [fn] optional callback - * @api public - */ - -Model.prototype.remove = function remove (fn) { - if (this.$__.removing) { - this.$__.removing.addBack(fn); - return this; - } - - var promise = this.$__.removing = new Promise(fn) - , where = this.$__where() - , self = this - , options = {} - - if (this.schema.options.safe) { - options.safe = this.schema.options.safe; - } - - this.collection.remove(where, options, tick(function (err) { - if (err) { - promise.error(err); - promise = self = self.$__.removing = where = options = null; - return; - } - self.emit('remove', self); - promise.complete(self); - promise = self = where = options = null; - })); - - return this; -}; - -/** - * Returns another Model instance. - * - * ####Example: - * - * var doc = new Tank; - * doc.model('User').findById(id, callback); - * - * @param {String} name model name - * @api public - */ - -Model.prototype.model = function model (name) { - return this.db.model(name); -}; - -/** - * Adds a discriminator type. - * - * ####Example: - * - * function BaseSchema() { - * Schema.apply(this, arguments); - * - * this.add({ - * name: String, - * createdAt: Date - * }); - * } - * util.inherits(BaseSchema, Schema); - * - * var PersonSchema = new BaseSchema(); - * var BossSchema = new BaseSchema({ department: String }); - * - * var Person = mongoose.model('Person', PersonSchema); - * var Boss = Person.discriminator('Boss', BossSchema); - * - * @param {String} name discriminator model name - * @param {Schema} schema discriminator model schema - * @api public - */ - -Model.discriminator = function discriminator (name, schema) { - if (!(schema instanceof Schema)) { - throw new Error("You must pass a valid discriminator Schema"); - } - - if (this.schema.discriminatorMapping && !this.schema.discriminatorMapping.isRoot) { - throw new Error("Discriminator \"" + name + "\" can only be a discriminator of the root model"); - } - - var key = this.schema.options.discriminatorKey; - if (schema.path(key)) { - throw new Error("Discriminator \"" + name + "\" cannot have field with name \"" + key + "\""); - } - - // merges base schema into new discriminator schema and sets new type field. - (function mergeSchemas(schema, baseSchema) { - utils.merge(schema, baseSchema); - - var obj = {}; - obj[key] = { type: String, default: name }; - schema.add(obj); - schema.discriminatorMapping = { key: key, value: name, isRoot: false }; - - if (baseSchema.options.collection) { - schema.options.collection = baseSchema.options.collection; - } - - // throws error if options are invalid - (function validateOptions(a, b) { - a = utils.clone(a); - b = utils.clone(b); - delete a.toJSON; - delete a.toObject; - delete b.toJSON; - delete b.toObject; - - if (!utils.deepEqual(a, b)) { - throw new Error("Discriminator options are not customizable (except toJSON & toObject)"); - } - })(schema.options, baseSchema.options); - - var toJSON = schema.options.toJSON - , toObject = schema.options.toObject; - - schema.options = utils.clone(baseSchema.options); - if (toJSON) schema.options.toJSON = toJSON; - if (toObject) schema.options.toObject = toObject; - - schema.callQueue = baseSchema.callQueue.concat(schema.callQueue); - schema._requiredpaths = undefined; // reset just in case Schema#requiredPaths() was called on either schema - })(schema, this.schema); - - if (!this.discriminators) { - this.discriminators = {}; - } - - if (!this.schema.discriminatorMapping) { - this.schema.discriminatorMapping = { key: key, value: null, isRoot: true }; - } - - if (this.discriminators[name]) { - throw new Error("Discriminator with name \"" + name + "\" already exists"); - } - - this.discriminators[name] = this.db.model(name, schema, this.collection.name); - this.discriminators[name].prototype.__proto__ = this.prototype; - - return this.discriminators[name]; -}; - -// Model (class) features - -/*! - * Give the constructor the ability to emit events. - */ - -for (var i in EventEmitter.prototype) - Model[i] = EventEmitter.prototype[i]; - -/** - * Called when the model compiles. - * - * @api private - */ - -Model.init = function init () { - if (this.schema.options.autoIndex) { - this.ensureIndexes(); - } - - this.schema.emit('init', this); -}; - -/** - * Sends `ensureIndex` commands to mongo for each index declared in the schema. - * - * ####Example: - * - * Event.ensureIndexes(function (err) { - * if (err) return handleError(err); - * }); - * - * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. - * - * ####Example: - * - * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) - * var Event = mongoose.model('Event', eventSchema); - * - * Event.on('index', function (err) { - * if (err) console.error(err); // error occurred during index creation - * }) - * - * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ - * - * The `ensureIndex` commands are not sent in parallel. This is to avoid the `MongoError: cannot add index with a background operation in progress` error. See [this ticket](https://github.com/LearnBoost/mongoose/issues/1365) for more information. - * - * @param {Function} [cb] optional callback - * @return {Promise} - * @api public - */ - -Model.ensureIndexes = function ensureIndexes (cb) { - var promise = new Promise(cb); - - var indexes = this.schema.indexes(); - if (!indexes.length) { - process.nextTick(promise.fulfill.bind(promise)); - return promise; - } - - // Indexes are created one-by-one to support how MongoDB < 2.4 deals - // with background indexes. - - var self = this - , safe = self.schema.options.safe - - function done (err) { - self.emit('index', err); - promise.resolve(err); - } - - function create () { - var index = indexes.shift(); - if (!index) return done(); - - var options = index[1]; - options.safe = safe; - self.collection.ensureIndex(index[0], options, tick(function (err) { - if (err) return done(err); - create(); - })); - } - - create(); - return promise; -} - -/** - * Schema the model uses. - * - * @property schema - * @receiver Model - * @api public - */ - -Model.schema; - -/*! - * Connection instance the model uses. - * - * @property db - * @receiver Model - * @api public - */ - -Model.db; - -/*! - * Collection the model uses. - * - * @property collection - * @receiver Model - * @api public - */ - -Model.collection; - -/** - * Base Mongoose instance the model uses. - * - * @property base - * @receiver Model - * @api public - */ - -Model.base; - -/** - * Registered discriminators for this model. - * - * @property discriminators - * @receiver Model - * @api public - */ - -Model.discriminators; - -/** - * Removes documents from the collection. - * - * ####Example: - * - * Comment.remove({ title: 'baby born from alien father' }, function (err) { - * - * }); - * - * ####Note: - * - * To remove documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): - * - * var query = Comment.remove({ _id: id }); - * query.exec(); - * - * ####Note: - * - * This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, _no middleware (hooks) are executed_. - * - * @param {Object} conditions - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.remove = function remove (conditions, callback) { - if ('function' === typeof conditions) { - callback = conditions; - conditions = {}; - } - - // get the mongodb collection object - var mq = new Query(conditions, {}, this, this.collection); - - return mq.remove(callback); -}; - -/** - * Finds documents - * - * The `conditions` are cast to their respective SchemaTypes before the command is sent. - * - * ####Examples: - * - * // named john and at least 18 - * MyModel.find({ name: 'john', age: { $gte: 18 }}); - * - * // executes immediately, passing results to callback - * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); - * - * // name LIKE john and only selecting the "name" and "friends" fields, executing immediately - * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) - * - * // passing options - * MyModel.find({ name: /john/i }, null, { skip: 10 }) - * - * // passing options and executing immediately - * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); - * - * // executing a query explicitly - * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }) - * query.exec(function (err, docs) {}); - * - * // using the promise returned from executing a query - * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); - * var promise = query.exec(); - * promise.addBack(function (err, docs) {}); - * - * @param {Object} conditions - * @param {Object} [fields] optional fields to select - * @param {Object} [options] optional - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see promise #promise-js - * @api public - */ - -Model.find = function find (conditions, fields, options, callback) { - if ('function' == typeof conditions) { - callback = conditions; - conditions = {}; - fields = null; - options = null; - } else if ('function' == typeof fields) { - callback = fields; - fields = null; - options = null; - } else if ('function' == typeof options) { - callback = options; - options = null; - } - - // get the raw mongodb collection object - var mq = new Query({}, options, this, this.collection); - mq.select(fields); - if (this.schema.discriminatorMapping && mq._selectedInclusively()) { - mq.select(this.schema.options.discriminatorKey); - } - - return mq.find(conditions, callback); -}; - -/** - * Finds a single document by id. - * - * The `id` is cast based on the Schema before sending the command. - * - * ####Example: - * - * // find adventure by id and execute immediately - * Adventure.findById(id, function (err, adventure) {}); - * - * // same as above - * Adventure.findById(id).exec(callback); - * - * // select only the adventures name and length - * Adventure.findById(id, 'name length', function (err, adventure) {}); - * - * // same as above - * Adventure.findById(id, 'name length').exec(callback); - * - * // include all properties except for `length` - * Adventure.findById(id, '-length').exec(function (err, adventure) {}); - * - * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean` - * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {}); - * - * // same as above - * Adventure.findById(id, 'name').lean().exec(function (err, doc) {}); - * - * @param {ObjectId|HexId} id objectid, or a value that can be casted to one - * @param {Object} [fields] optional fields to select - * @param {Object} [options] optional - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries #query_Query-lean - * @api public - */ - -Model.findById = function findById (id, fields, options, callback) { - return this.findOne({ _id: id }, fields, options, callback); -}; - -/** - * Finds one document. - * - * The `conditions` are cast to their respective SchemaTypes before the command is sent. - * - * ####Example: - * - * // find one iphone adventures - iphone adventures?? - * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {}); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); - * - * // select only the adventures name - * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); - * - * // specify options, in this case lean - * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback); - * - * // same as above - * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback); - * - * // chaining findOne queries (same as above) - * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback); - * - * @param {Object} conditions - * @param {Object} [fields] optional fields to select - * @param {Object} [options] optional - * @param {Function} [callback] - * @return {Query} - * @see field selection #query_Query-select - * @see lean queries #query_Query-lean - * @api public - */ - -Model.findOne = function findOne (conditions, fields, options, callback) { - if ('function' == typeof options) { - callback = options; - options = null; - } else if ('function' == typeof fields) { - callback = fields; - fields = null; - options = null; - } else if ('function' == typeof conditions) { - callback = conditions; - conditions = {}; - fields = null; - options = null; - } - - // get the mongodb collection object - var mq = new Query({}, options, this, this.collection); - mq.select(fields); - if (this.schema.discriminatorMapping && mq._selectedInclusively()) { - mq.select(this.schema.options.discriminatorKey); - } - - return mq.findOne(conditions, callback); -}; - -/** - * Counts number of matching documents in a database collection. - * - * ####Example: - * - * Adventure.count({ type: 'jungle' }, function (err, count) { - * if (err) .. - * console.log('there are %d jungle adventures', count); - * }); - * - * @param {Object} conditions - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.count = function count (conditions, callback) { - if ('function' === typeof conditions) - callback = conditions, conditions = {}; - - // get the mongodb collection object - var mq = new Query({}, {}, this, this.collection); - - return mq.count(conditions, callback); -}; - -/** - * Creates a Query for a `distinct` operation. - * - * Passing a `callback` immediately executes the query. - * - * ####Example - * - * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { - * if (err) return handleError(err); - * - * assert(Array.isArray(result)); - * console.log('unique urls with more than 100 clicks', result); - * }) - * - * var query = Link.distinct('url'); - * query.exec(callback); - * - * @param {String} field - * @param {Object} [conditions] optional - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.distinct = function distinct (field, conditions, callback) { - // get the mongodb collection object - var mq = new Query({}, {}, this, this.collection); - - if ('function' == typeof conditions) { - callback = conditions; - conditions = {}; - } - - return mq.distinct(conditions, field, callback); -}; - -/** - * Creates a Query, applies the passed conditions, and returns the Query. - * - * For example, instead of writing: - * - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * we can instead write: - * - * User.where('age').gte(21).lte(65).exec(callback); - * - * Since the Query class also supports `where` you can continue chaining - * - * User - * .where('age').gte(21).lte(65) - * .where('name', /^b/i) - * ... etc - * - * @param {String} path - * @param {Object} [val] optional value - * @return {Query} - * @api public - */ - -Model.where = function where (path, val) { - // get the mongodb collection object - var mq = new Query({}, {}, this, this.collection).find({}); - return mq.where.apply(mq, arguments); -}; - -/** - * Creates a `Query` and specifies a `$where` condition. - * - * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. - * - * Blog.$where('this.comments.length > 5').exec(function (err, docs) {}); - * - * @param {String|Function} argument is a javascript string or anonymous function - * @method $where - * @memberOf Model - * @return {Query} - * @see Query.$where #query_Query-%24where - * @api public - */ - -Model.$where = function $where () { - var mq = new Query({}, {}, this, this.collection).find({}); - return mq.$where.apply(mq, arguments); -}; - -/** - * Issues a mongodb findAndModify update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - * ####Examples: - * - * A.findOneAndUpdate(conditions, update, options, callback) // executes - * A.findOneAndUpdate(conditions, update, options) // returns Query - * A.findOneAndUpdate(conditions, update, callback) // executes - * A.findOneAndUpdate(conditions, update) // returns Query - * A.findOneAndUpdate() // returns Query - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * var query = { name: 'borne' }; - * Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback) - * - * // is sent as - * Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. - * - * ####Note: - * - * Although values are cast to their appropriate types when using the findAndModify helpers, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findOne({ name: 'borne' }, function (err, doc) { - * if (err) .. - * doc.name = 'jason borne'; - * doc.save(callback); - * }) - * - * @param {Object} [conditions] - * @param {Object} [update] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findOneAndUpdate = function (conditions, update, options, callback) { - if ('function' == typeof options) { - callback = options; - options = null; - } - else if (1 === arguments.length) { - if ('function' == typeof conditions) { - var msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' - + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' - + ' ' + this.modelName + '.findOneAndUpdate(update)\n' - + ' ' + this.modelName + '.findOneAndUpdate()\n'; - throw new TypeError(msg) - } - update = conditions; - conditions = undefined; - } - - var fields; - if (options && options.fields) { - fields = options.fields; - options.fields = undefined; - } - - var mq = new Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndUpdate(conditions, update, options, callback); -} - -/** - * Issues a mongodb findAndModify update command by a documents id. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - * ####Examples: - * - * A.findByIdAndUpdate(id, update, options, callback) // executes - * A.findByIdAndUpdate(id, update, options) // returns Query - * A.findByIdAndUpdate(id, update, callback) // executes - * A.findByIdAndUpdate(id, update) // returns Query - * A.findByIdAndUpdate() // returns Query - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Note: - * - * All top level update keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback) - * - * // is sent as - * Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback) - * - * This helps prevent accidentally overwriting your document with `{ name: 'jason borne' }`. - * - * ####Note: - * - * Although values are cast to their appropriate types when using the findAndModify helpers, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.name = 'jason borne'; - * doc.save(callback); - * }) - * - * @param {ObjectId|HexId} id an ObjectId or string that can be cast to one. - * @param {Object} [update] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findByIdAndUpdate = function (id, update, options, callback) { - var args; - - if (1 === arguments.length) { - if ('function' == typeof id) { - var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' - + ' ' + this.modelName + '.findByIdAndUpdate()\n'; - throw new TypeError(msg) - } - return this.findOneAndUpdate({_id: id }, undefined); - } - - args = utils.args(arguments, 1); - - // if a model is passed in instead of an id - if (id && id._id) { - id = id._id; - } - if (id) { - args.unshift({ _id: id }); - } - return this.findOneAndUpdate.apply(this, args); -} - -/** - * Issue a mongodb findAndModify remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes immediately if `callback` is passed else a Query object is returned. - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - * ####Examples: - * - * A.findOneAndRemove(conditions, options, callback) // executes - * A.findOneAndRemove(conditions, options) // return Query - * A.findOneAndRemove(conditions, callback) // executes - * A.findOneAndRemove(conditions) // returns Query - * A.findOneAndRemove() // returns Query - * - * Although values are cast to their appropriate types when using the findAndModify helpers, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findById(id, function (err, doc) { - * if (err) .. - * doc.remove(callback); - * }) - * - * @param {Object} conditions - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Model.findOneAndRemove = function (conditions, options, callback) { - if (1 === arguments.length && 'function' == typeof conditions) { - var msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' - + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' - + ' ' + this.modelName + '.findOneAndRemove()\n'; - throw new TypeError(msg) - } - - if ('function' == typeof options) { - callback = options; - options = undefined; - } - - var fields; - if (options) { - fields = options.select; - options.select = undefined; - } - - var mq = new Query({}, {}, this, this.collection); - mq.select(fields); - - return mq.findOneAndRemove(conditions, options, callback); -} - -/** - * Issue a mongodb findAndModify remove command by a documents id. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * - * Executes immediately if `callback` is passed, else a `Query` object is returned. - * - * ####Options: - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - `select`: sets the document fields to return - * - * ####Examples: - * - * A.findByIdAndRemove(id, options, callback) // executes - * A.findByIdAndRemove(id, options) // return Query - * A.findByIdAndRemove(id, callback) // executes - * A.findByIdAndRemove(id) // returns Query - * A.findByIdAndRemove() // returns Query - * - * @param {ObjectId|HexString} id ObjectId or string that can be cast to one - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @see Model.findOneAndRemove #model_Model.findOneAndRemove - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - */ - -Model.findByIdAndRemove = function (id, options, callback) { - if (1 === arguments.length && 'function' == typeof id) { - var msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' - + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' - + ' ' + this.modelName + '.findByIdAndRemove(id)\n' - + ' ' + this.modelName + '.findByIdAndRemove()\n'; - throw new TypeError(msg) - } - - return this.findOneAndRemove({ _id: id }, options, callback); -} - -/** - * Shortcut for creating a new Document that is automatically saved to the db if valid. - * - * ####Example: - * - * // pass individual docs - * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { - * if (err) // ... - * }); - * - * // pass an array - * var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; - * Candy.create(array, function (err, jellybean, snickers) { - * if (err) // ... - * }); - * - * // callback is optional; use the returned promise if you like: - * var promise = Candy.create({ type: 'jawbreaker' }); - * promise.then(function (jawbreaker) { - * // ... - * }) - * - * @param {Array|Object...} doc(s) - * @param {Function} [fn] callback - * @return {Promise} - * @api public - */ - -Model.create = function create (doc, fn) { - var promise = new Promise - , args - - if (Array.isArray(doc)) { - args = doc; - - if ('function' == typeof fn) { - promise.onResolve(fn); - } - - } else { - var last = arguments[arguments.length - 1]; - - if ('function' == typeof last) { - promise.onResolve(last); - args = utils.args(arguments, 0, arguments.length - 1); - } else { - args = utils.args(arguments); - } - } - - var count = args.length; - - if (0 === count) { - promise.complete(); - return promise; - } - - var self = this; - var docs = []; - - args.forEach(function (arg, i) { - var doc = new self(arg); - docs[i] = doc; - doc.save(function (err) { - if (err) return promise.error(err); - --count || promise.complete.apply(promise, docs); - }); - }); - - return promise; -}; - -/** - * Updates documents in the database without returning them. - * - * ####Examples: - * - * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); - * MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, numberAffected, raw) { - * if (err) return handleError(err); - * console.log('The number of updated documents was %d', numberAffected); - * console.log('The raw response from Mongo was ', raw); - * }); - * - * ####Valid options: - * - * - `safe` (boolean) safe mode (defaults to value set in schema (true)) - * - `upsert` (boolean) whether to create the doc if it doesn't match (false) - * - `multi` (boolean) whether multiple documents should be updated (false) - * - `strict` (boolean) overrides the `strict` option for this update - * - * All `update` values are cast to their appropriate SchemaTypes before being sent. - * - * The `callback` function receives `(err, numberAffected, rawResponse)`. - * - * - `err` is the error if any occurred - * - `numberAffected` is the count of updated documents Mongo reported - * - `rawResponse` is the full response from Mongo - * - * ####Note: - * - * All top level keys which are not `atomic` operation names are treated as set operations: - * - * ####Example: - * - * var query = { name: 'borne' }; - * Model.update(query, { name: 'jason borne' }, options, callback) - * - * // is sent as - * Model.update(query, { $set: { name: 'jason borne' }}, options, callback) - * - * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason borne' }`. - * - * ####Note: - * - * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. - * - * ####Note: - * - * To update documents without waiting for a response from MongoDB, do not pass a `callback`, then call `exec` on the returned [Query](#query-js): - * - * Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec(); - * - * ####Note: - * - * Although values are casted to their appropriate types when using update, the following are *not* applied: - * - * - defaults - * - setters - * - validators - * - middleware - * - * If you need those features, use the traditional approach of first retrieving the document. - * - * Model.findOne({ name: 'borne' }, function (err, doc) { - * if (err) .. - * doc.name = 'jason borne'; - * doc.save(callback); - * }) - * - * @see strict schemas http://mongoosejs.com/docs/guide.html#strict - * @param {Object} conditions - * @param {Object} update - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} - * @api public - */ - -Model.update = function update (conditions, doc, options, callback) { - var mq = new Query({}, {}, this, this.collection); - return mq.update(conditions, doc, options, callback); -}; - -/** - * Executes a mapReduce command. - * - * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. - * - * ####Example: - * - * var o = {}; - * o.map = function () { emit(this.name, 1) } - * o.reduce = function (k, vals) { return vals.length } - * User.mapReduce(o, function (err, results) { - * console.log(results) - * }) - * - * ####Other options: - * - * - `query` {Object} query filter object. - * - `limit` {Number} max number of documents - * - `keeptemp` {Boolean, default:false} keep temporary data - * - `finalize` {Function} finalize function - * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution - * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X - * - `verbose` {Boolean, default:false} provide statistics on job execution time. - * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. - * - * ####* out options: - * - * - `{inline:1}` the results are returned in an array - * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection - * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions - * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old - * - * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the `lean` option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). - * - * ####Example: - * - * var o = {}; - * o.map = function () { emit(this.name, 1) } - * o.reduce = function (k, vals) { return vals.length } - * o.out = { replace: 'createdCollectionNameForResults' } - * o.verbose = true; - * - * User.mapReduce(o, function (err, model, stats) { - * console.log('map reduce took %d ms', stats.processtime) - * model.find().where('value').gt(10).exec(function (err, docs) { - * console.log(docs); - * }); - * }) - * - * // a promise is returned so you may instead write - * var promise = User.mapReduce(o); - * promise.then(function (model, stats) { - * console.log('map reduce took %d ms', stats.processtime) - * return model.find().where('value').gt(10).exec(); - * }).then(function (docs) { - * console.log(docs); - * }).then(null, handleError).end() - * - * @param {Object} o an object specifying map-reduce options - * @param {Function} [callback] optional callback - * @see http://www.mongodb.org/display/DOCS/MapReduce - * @return {Promise} - * @api public - */ - -Model.mapReduce = function mapReduce (o, callback) { - var promise = new Promise(callback); - var self = this; - - if (!Model.mapReduce.schema) { - var opts = { noId: true, noVirtualId: true, strict: false } - Model.mapReduce.schema = new Schema({}, opts); - } - - if (!o.out) o.out = { inline: 1 }; - if (false !== o.verbose) o.verbose = true; - - o.map = String(o.map); - o.reduce = String(o.reduce); - - if (o.query) { - var q = new Query(o.query); - q.cast(this); - o.query = q._conditions; - q = undefined; - } - - this.collection.mapReduce(null, null, o, function (err, ret, stats) { - if (err) return promise.error(err); - - if (ret.findOne && ret.mapReduce) { - // returned a collection, convert to Model - var model = Model.compile( - '_mapreduce_' + ret.collectionName - , Model.mapReduce.schema - , ret.collectionName - , self.db - , self.base); - - model._mapreduce = true; - - return promise.fulfill(model, stats); - } - - promise.fulfill(ret, stats); - }); - - return promise; -} - -/** - * geoNear support for Mongoose - * - * ####Options: - * - `lean` {Boolean} return the raw object - * - All options supported by the driver are also supported - * - * ####Example: - * - * // Legacy point - * Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { - * console.log(results); - * }); - * - * // geoJson - * var point = { type : "Point", coordinates : [9,9] }; - * Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) { - * console.log(results); - * }); - * - * @param {Object/Array} GeoJSON point or legacy coordinate pair [x,y] to search near - * @param {Object} options for the qurery - * @param {Function} [callback] optional callback for the query - * @return {Promise} - * @see http://docs.mongodb.org/manual/core/2dsphere/ - * @see http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=geonear#geoNear - * @api public - */ - -Model.geoNear = function (near, options, callback) { - if ('function' == typeof options) { - callback = options; - options = {}; - } - - var promise = new Promise(callback); - if (!near) { - promise.error(new Error("Must pass a near option to geoNear")); - return promise; - } - - var x,y; - - if (Array.isArray(near)) { - if (near.length != 2) { - promise.error(new Error("If using legacy coordinates, must be an array of size 2 for geoNear")); - return promise; - } - x = near[0]; - y = near[1]; - } else { - if (near.type != "Point" || !Array.isArray(near.coordinates)) { - promise.error(new Error("Must pass either a legacy coordinate array or GeoJSON Point to geoNear")); - return promise; - } - - x = near.coordinates[0]; - y = near.coordinates[1]; - } - - var self = this; - this.collection.geoNear(x, y, options, function (err, res) { - if (err) return promise.error(err); - if (options.lean) return promise.fulfill(res.results, res.stats); - - var count = res.results.length; - // if there are no results, fulfill the promise now - if (count == 0) { - return promise.fulfill(res.results, res.stats); - } - - var errSeen = false; - for (var i=0; i < res.results.length; i++) { - var temp = res.results[i].obj; - res.results[i].obj = new self(); - res.results[i].obj.init(temp, function (err) { - if (err && !errSeen) { - errSeen = true; - return promise.error(err); - } - --count || promise.fulfill(res.results, res.stats); - }); - } - }); - return promise; -}; - -/** - * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. - * - * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. - * - * ####Example: - * - * // Find the max balance of all accounts - * Users.aggregate( - * { $group: { _id: null, maxBalance: { $max: '$balance' }}} - * , { $project: { _id: 0, maxBalance: 1 }} - * , function (err, res) { - * if (err) return handleError(err); - * console.log(res); // [ { maxBalance: 98000 } ] - * }); - * - * // Or use the aggregation pipeline builder. - * Users.aggregate() - * .group({ _id: null, maxBalance: { $max: '$balance' } }) - * .select('-id maxBalance') - * .exec(function (err, res) { - * if (err) return handleError(err); - * console.log(res); // [ { maxBalance: 98 } ] - * }); - * - * ####NOTE: - * - * - Arguments are not cast to the model's schema because `$project` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. - * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). - * - Requires MongoDB >= 2.1 - * - * @see Aggregate #aggregate_Aggregate - * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ - * @param {Object|Array} [...] aggregation pipeline operator(s) or operator array - * @param {Function} [callback] - * @return {Aggregate|Promise} - * @api public - */ - -Model.aggregate = function aggregate () { - var args = [].slice.call(arguments) - , aggregate - , callback; - - if ('function' === typeof args[args.length - 1]) { - callback = args.pop(); - } - - if (1 === args.length && util.isArray(args[0])) { - aggregate = new Aggregate(args[0]); - } else { - aggregate = new Aggregate(args); - } - - aggregate.bind(this); - - if ('undefined' === typeof callback) { - return aggregate; - } - - return aggregate.exec(callback); -} - -/** - * Implements `$geoSearch` functionality for Mongoose - * - * ####Example: - * - * var options = { near: [10, 10], maxDistance: 5 }; - * Locations.geoSearch({ type : "house" }, options, function(err, res) { - * console.log(res); - * }); - * - * ####Options: - * - `near` {Array} x,y point to search for - * - `maxDistance` {Number} the maximum distance from the point near that a result can be - * - `limit` {Number} The maximum number of results to return - * - `lean` {Boolean} return the raw object instead of the Mongoose Model - * - * @param {Object} condition an object that specifies the match condition (required) - * @param {Object} options for the geoSearch, some (near, maxDistance) are required - * @param {Function} [callback] optional callback - * @return {Promise} - * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ - * @see http://docs.mongodb.org/manual/core/geohaystack/ - * @api public - */ - -Model.geoSearch = function (conditions, options, callback) { - if ('function' == typeof options) { - callback = options; - options = {}; - } - - var promise = new Promise(callback); - - if (conditions == undefined || !utils.isObject(conditions)) { - return promise.error(new Error("Must pass conditions to geoSearch")); - } - - if (!options.near) { - return promise.error(new Error("Must specify the near option in geoSearch")); - } - - if (!Array.isArray(options.near)) { - return promise.error(new Error("near option must be an array [x, y]")); - } - - - // send the conditions in the options object - options.search = conditions; - var self = this; - - this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function (err, res) { - // have to deal with driver problem. Should be fixed in a soon-ish release - // (7/8/2013) - if (err || res.errmsg) { - if (!err) err = new Error(res.errmsg); - if (res && res.code !== undefined) err.code = res.code; - return promise.error(err); - } - - var count = res.results.length; - if (options.lean || (count == 0)) return promise.fulfill(res.results, res.stats); - - var errSeen = false; - for (var i=0; i < res.results.length; i++) { - var temp = res.results[i]; - res.results[i] = new self(); - res.results[i].init(temp, {}, function (err) { - if (err && !errSeen) { - errSeen = true; - return promise.error(err); - } - - --count || (!errSeen && promise.fulfill(res.results, res.stats)); - }); - } - }); - - return promise; -}; - -/** - * Populates document references. - * - * ####Available options: - * - * - path: space delimited path(s) to populate - * - select: optional fields to select - * - match: optional query conditions to match - * - model: optional name of the model to use for population - * - options: optional query options like sort, limit, etc - * - * ####Examples: - * - * // populates a single object - * User.findById(id, function (err, user) { - * var opts = [ - * { path: 'company', match: { x: 1 }, select: 'name' } - * , { path: 'notes', options: { limit: 10 }, model: 'override' } - * ] - * - * User.populate(user, opts, function (err, user) { - * console.log(user); - * }) - * }) - * - * // populates an array of objects - * User.find(match, function (err, users) { - * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] - * - * var promise = User.populate(users, opts); - * promise.then(console.log).end(); - * }) - * - * // imagine a Weapon model exists with two saved documents: - * // { _id: 389, name: 'whip' } - * // { _id: 8921, name: 'boomerang' } - * - * var user = { name: 'Indiana Jones', weapon: 389 } - * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { - * console.log(user.weapon.name) // whip - * }) - * - * // populate many plain objects - * var users = [{ name: 'Indiana Jones', weapon: 389 }] - * users.push({ name: 'Batman', weapon: 8921 }) - * Weapon.populate(users, { path: 'weapon' }, function (err, users) { - * users.forEach(function (user) { - * console.log('%s uses a %s', users.name, user.weapon.name) - * // Indiana Jones uses a whip - * // Batman uses a boomerang - * }) - * }) - * // Note that we didn't need to specify the Weapon model because - * // we were already using it's populate() method. - * - * @param {Document|Array} docs Either a single document or array of documents to populate. - * @param {Object} options A hash of key/val (path, options) used for population. - * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. - * @return {Promise} - * @api public - */ - -Model.populate = function (docs, paths, cb) { - var promise = new Promise(cb); - - // always resolve on nextTick for consistent async behavior - function resolve () { - var args = utils.args(arguments); - process.nextTick(function () { - promise.resolve.apply(promise, args); - }); - } - - // normalized paths - var paths = utils.populate(paths); - var pending = paths.length; - - if (0 === pending) { - resolve(null, docs); - return promise; - } - - // each path has its own query options and must be executed separately - var i = pending; - var path; - while (i--) { - path = paths[i]; - populate(this, docs, path, next); - } - - return promise; - - function next (err) { - if (err) return resolve(err); - if (--pending) return; - resolve(null, docs); - } -} - -/*! - * Populates `docs` - */ - -function populate (model, docs, options, cb) { - var select = options.select - , match = options.match - , path = options.path - - var schema = model._getSchema(path); - var subpath; - - // handle document arrays - if (schema && schema.caster) { - schema = schema.caster; - } - - // model name for the populate query - var modelName = options.model && options.model.modelName - || options.model // query options - || schema && schema.options.ref // declared in schema - || model.modelName // an ad-hoc structure - - var Model = model.db.model(modelName); - - // expose the model used - options.model = Model; - - // normalize single / multiple docs passed - if (!Array.isArray(docs)) { - docs = [docs]; - } - - if (0 === docs.length || docs.every(utils.isNullOrUndefined)) { - return cb(); - } - - var rawIds = []; - var i, doc, id; - var len = docs.length; - var ret; - var found = 0; - var isDocument; - - for (i = 0; i < len; i++) { - ret = undefined; - doc = docs[i]; - id = String(utils.getValue("_id", doc)); - isDocument = !! doc.$__; - - if (isDocument && !doc.isModified(path)) { - // it is possible a previously populated path is being - // populated again. Because users can specify matcher - // clauses in their populate arguments we use the cached - // _ids from the original populate call to ensure all _ids - // are looked up, but only if the path wasn't modified which - // signifies the users intent of the state of the path. - ret = doc.populated(path); - } - - if (!ret || Array.isArray(ret) && 0 === ret.length) { - ret = utils.getValue(path, doc); - } - - if (ret) { - ret = convertTo_id(ret); - - // previously we always assigned this even if the document had no _id - options._docs[id] = Array.isArray(ret) - ? ret.slice() - : ret; - } - - // always retain original values, even empty values. these are - // used to map the query results back to the correct position. - rawIds.push(ret); - - if (isDocument) { - // cache original populated _ids and model used - doc.populated(path, options._docs[id], options); - } - } - - var ids = utils.array.flatten(rawIds, function (item) { - // no need to include undefined values in our query - return undefined !== item; - }); - - if (0 === ids.length || ids.every(utils.isNullOrUndefined)) { - return cb(); - } - - // preserve original match conditions by copying - if (match) { - match = utils.object.shallowCopy(match); - } else { - match = {}; - } - - match._id || (match._id = { $in: ids }); - - var assignmentOpts = {}; - assignmentOpts.sort = options.options && options.options.sort || undefined; - assignmentOpts.excludeId = /\s?-_id\s?/.test(select) || (select && 0 === select._id); - - if (assignmentOpts.excludeId) { - // override the exclusion from the query so we can use the _id - // for document matching during assignment. we'll delete the - // _id back off before returning the result. - if ('string' == typeof select) { - select = select.replace(/\s?-_id\s?/g, ' '); - } else { - // preserve original select conditions by copying - select = utils.object.shallowCopy(select); - delete select._id; - } - } - - // if a limit option is passed, we should have the limit apply to *each* - // document, not apply in the aggregate - if (options.options && options.options.limit) { - options.options.limit = options.options.limit * len; - } - - Model.find(match, select, options.options, function (err, vals) { - if (err) return cb(err); - - var lean = options.options && options.options.lean; - var len = vals.length; - var rawOrder = {}; - var rawDocs = {} - var key; - var val; - - // optimization: - // record the document positions as returned by - // the query result. - for (var i = 0; i < len; i++) { - val = vals[i]; - key = String(utils.getValue('_id', val)); - rawDocs[key] = val; - rawOrder[key] = i; - - // flag each as result of population - if (!lean) val.$__.wasPopulated = true; - } - - assignVals({ - rawIds: rawIds, - rawDocs: rawDocs, - rawOrder: rawOrder, - docs: docs, - path: path, - options: assignmentOpts - }); - - cb(); - }); -} - -/*! - * Retrieve the _id of `val` if a Document or Array of Documents. - * - * @param {Array|Document|Any} val - * @return {Array|Document|Any} - */ - -function convertTo_id (val) { - if (val instanceof Model) return val._id; - - if (Array.isArray(val)) { - for (var i = 0; i < val.length; ++i) { - if (val[i] instanceof Model) { - val[i] = val[i]._id; - } - } - return val; - } - - return val; -} - -/*! - * Assigns documents returned from a population query back - * to the original document path. - */ - -function assignVals (o) { - // replace the original ids in our intermediate _ids structure - // with the documents found by query - - assignRawDocsToIdStructure(o.rawIds, o.rawDocs, o.rawOrder, o.options); - - // now update the original documents being populated using the - // result structure that contains real documents. - - var docs = o.docs; - var path = o.path; - var rawIds = o.rawIds; - var options = o.options; - - for (var i = 0; i < docs.length; ++i) { - utils.setValue(path, rawIds[i], docs[i], function (val) { - return valueFilter(val, options); - }); - } -} - -/*! - * 1) Apply backwards compatible find/findOne behavior to sub documents - * - * find logic: - * a) filter out non-documents - * b) remove _id from sub docs when user specified - * - * findOne - * a) if no doc found, set to null - * b) remove _id from sub docs when user specified - * - * 2) Remove _ids when specified by users query. - * - * background: - * _ids are left in the query even when user excludes them so - * that population mapping can occur. - */ - -function valueFilter (val, assignmentOpts) { - if (Array.isArray(val)) { - // find logic - var ret = []; - for (var i = 0; i < val.length; ++i) { - var subdoc = val[i]; - if (!isDoc(subdoc)) continue; - maybeRemoveId(subdoc, assignmentOpts); - ret.push(subdoc); - } - return ret; - } - - // findOne - if (isDoc(val)) { - maybeRemoveId(val, assignmentOpts); - return val; - } - - return null; -} - -/*! - * Remove _id from `subdoc` if user specified "lean" query option - */ - -function maybeRemoveId (subdoc, assignmentOpts) { - if (assignmentOpts.excludeId) { - if ('function' == typeof subdoc.setValue) { - subdoc.setValue('_id', undefined); - } else { - delete subdoc._id; - } - } -} - -/*! - * Determine if `doc` is a document returned - * by a populate query. - */ - -function isDoc (doc) { - if (null == doc) - return false; - - var type = typeof doc; - if ('string' == type) - return false; - - if ('number' == type) - return false; - - if (Buffer.isBuffer(doc)) - return false; - - if ('ObjectID' == doc.constructor.name) - return false; - - // only docs - return true; -} - -/*! - * Assign `vals` returned by mongo query to the `rawIds` - * structure returned from utils.getVals() honoring - * query sort order if specified by user. - * - * This can be optimized. - * - * Rules: - * - * if the value of the path is not an array, use findOne rules, else find. - * for findOne the results are assigned directly to doc path (including null results). - * for find, if user specified sort order, results are assigned directly - * else documents are put back in original order of array if found in results - * - * @param {Array} rawIds - * @param {Array} vals - * @param {Boolean} sort - * @api private - */ - -function assignRawDocsToIdStructure (rawIds, resultDocs, resultOrder, options, recursed) { - // honor user specified sort order - var newOrder = []; - var sorting = options.sort && rawIds.length > 1; - var found; - var doc; - var sid; - var id; - - for (var i = 0; i < rawIds.length; ++i) { - id = rawIds[i]; - - if (Array.isArray(id)) { - // handle [ [id0, id2], [id3] ] - assignRawDocsToIdStructure(id, resultDocs, resultOrder, options, true); - newOrder.push(id); - continue; - } - - if (null === id && !sorting) { - // keep nulls for findOne unless sorting, which always - // removes them (backward compat) - newOrder.push(id); - continue; - } - - sid = String(id); - found = false; - - if (recursed) { - // apply find behavior - - // assign matching documents in original order unless sorting - doc = resultDocs[sid]; - if (doc) { - if (sorting) { - newOrder[resultOrder[sid]] = doc; - } else { - newOrder.push(doc); - } - } else { - newOrder.push(id); - } - } else { - // apply findOne behavior - if document in results, assign, else assign null - newOrder[i] = doc = resultDocs[sid] || null; - } - } - - rawIds.length = 0; - if (newOrder.length) { - // reassign the documents based on corrected order - - // forEach skips over sparse entries in arrays so we - // can safely use this to our advantage dealing with sorted - // result sets too. - newOrder.forEach(function (doc, i) { - rawIds[i] = doc; - }); - } -} - -/** - * Finds the schema for `path`. This is different than - * calling `schema.path` as it also resolves paths with - * positional selectors (something.$.another.$.path). - * - * @param {String} path - * @return {Schema} - * @api private - */ - -Model._getSchema = function _getSchema (path) { - var schema = this.schema - , pathschema = schema.path(path); - - if (pathschema) - return pathschema; - - // look for arrays - return (function search (parts, schema) { - var p = parts.length + 1 - , foundschema - , trypath - - while (p--) { - trypath = parts.slice(0, p).join('.'); - foundschema = schema.path(trypath); - if (foundschema) { - if (foundschema.caster) { - - // array of Mixed? - if (foundschema.caster instanceof Types.Mixed) { - return foundschema.caster; - } - - // Now that we found the array, we need to check if there - // are remaining document paths to look up for casting. - // Also we need to handle array.$.path since schema.path - // doesn't work for that. - // If there is no foundschema.schema we are dealing with - // a path like array.$ - if (p !== parts.length && foundschema.schema) { - if ('$' === parts[p]) { - // comments.$.comments.$.title - return search(parts.slice(p+1), foundschema.schema); - } else { - // this is the last path of the selector - return search(parts.slice(p), foundschema.schema); - } - } - } - return foundschema; - } - } - })(path.split('.'), schema) -} - -/*! - * Compiler utility. - * - * @param {String} name model name - * @param {Schema} schema - * @param {String} collectionName - * @param {Connection} connection - * @param {Mongoose} base mongoose instance - */ - -Model.compile = function compile (name, schema, collectionName, connection, base) { - var versioningEnabled = false !== schema.options.versionKey; - - if (versioningEnabled && !schema.paths[schema.options.versionKey]) { - // add versioning to top level documents only - var o = {}; - o[schema.options.versionKey] = Number; - schema.add(o); - } - - // generate new class - function model (doc, fields, skipId) { - if (!(this instanceof model)) - return new model(doc, fields, skipId); - Model.call(this, doc, fields, skipId); - }; - - model.base = base; - model.modelName = name; - model.__proto__ = Model; - model.prototype.__proto__ = Model.prototype; - model.model = Model.prototype.model; - model.db = model.prototype.db = connection; - model.discriminators = model.prototype.discriminators = undefined; - - model.prototype.$__setSchema(schema); - - var collectionOptions = { - bufferCommands: schema.options.bufferCommands - , capped: schema.options.capped - }; - - model.prototype.collection = connection.collection( - collectionName - , collectionOptions - ); - - // apply methods - for (var i in schema.methods) - model.prototype[i] = schema.methods[i]; - - // apply statics - for (var i in schema.statics) - model[i] = schema.statics[i]; - - model.schema = model.prototype.schema; - model.options = model.prototype.options; - model.collection = model.prototype.collection; - - return model; -}; - -/*! - * Subclass this model with `conn`, `schema`, and `collection` settings. - * - * @param {Connection} conn - * @param {Schema} [schema] - * @param {String} [collection] - * @return {Model} - */ - -Model.__subclass = function subclass (conn, schema, collection) { - // subclass model using this connection and collection name - var model = this; - - var Model = function Model (doc, fields, skipId) { - if (!(this instanceof Model)) { - return new Model(doc, fields, skipId); - } - model.call(this, doc, fields, skipId); - } - - Model.__proto__ = model; - Model.prototype.__proto__ = model.prototype; - Model.db = Model.prototype.db = conn; - - var s = schema && 'string' != typeof schema - ? schema - : model.prototype.schema; - - var options = s.options || {}; - - if (!collection) { - collection = model.prototype.schema.get('collection') - || utils.toCollectionName(model.modelName, options); - } - - var collectionOptions = { - bufferCommands: s ? options.bufferCommands : true - , capped: s && options.capped - }; - - Model.prototype.collection = conn.collection(collection, collectionOptions); - Model.collection = Model.prototype.collection; - Model.init(); - return Model; -} - -/*! - * Module exports. - */ - -module.exports = exports = Model; diff --git a/node_modules/mongoose/lib/promise.js b/node_modules/mongoose/lib/promise.js deleted file mode 100644 index ba0f0268a..000000000 --- a/node_modules/mongoose/lib/promise.js +++ /dev/null @@ -1,261 +0,0 @@ - -/*! - * Module dependencies - */ - -var MPromise = require('mpromise'); - -/** - * Promise constructor. - * - * Promises are returned from executed queries. Example: - * - * var query = Candy.find({ bar: true }); - * var promise = query.exec(); - * - * @param {Function} fn a function which will be called when the promise is resolved that accepts `fn(err, ...){}` as signature - * @inherits mpromise https://github.com/aheckmann/mpromise - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `err`: Emits when the promise is rejected - * @event `complete`: Emits when the promise is fulfilled - * @api public - */ - -function Promise (fn) { - MPromise.call(this, fn); -} - -/*! - * Inherit from mpromise - */ - -Promise.prototype = Object.create(MPromise.prototype, { - constructor: { - value: Promise - , enumerable: false - , writable: true - , configurable: true - } -}); - -/*! - * Override event names for backward compatibility. - */ - -Promise.SUCCESS = 'complete'; -Promise.FAILURE = 'err'; - -/** - * Adds `listener` to the `event`. - * - * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event. - * - * @see mpromise#on https://github.com/aheckmann/mpromise#on - * @method on - * @memberOf Promise - * @param {String} event - * @param {Function} listener - * @return {Promise} this - * @api public - */ - -/** - * Rejects this promise with `reason`. - * - * If the promise has already been fulfilled or rejected, not action is taken. - * - * @see mpromise#reject https://github.com/aheckmann/mpromise#reject - * @method reject - * @memberOf Promise - * @param {Object|String|Error} reason - * @return {Promise} this - * @api public - */ - -/** - * Rejects this promise with `err`. - * - * If the promise has already been fulfilled or rejected, not action is taken. - * - * Differs from [#reject](#promise_Promise-reject) by first casting `err` to an `Error` if it is not `instanceof Error`. - * - * @api public - * @param {Error|String} err - * @return {Promise} this - */ - -Promise.prototype.error = function (err) { - if (!(err instanceof Error)) err = new Error(err); - return this.reject(err); -} - -/** - * Resolves this promise to a rejected state if `err` is passed or a fulfilled state if no `err` is passed. - * - * If the promise has already been fulfilled or rejected, not action is taken. - * - * `err` will be cast to an Error if not already instanceof Error. - * - * _NOTE: overrides [mpromise#resolve](https://github.com/aheckmann/mpromise#resolve) to provide error casting._ - * - * @param {Error} [err] error or null - * @param {Object} [val] value to fulfill the promise with - * @api public - */ - -Promise.prototype.resolve = function (err, val) { - if (err) return this.error(err); - return this.fulfill(val); -} - -/** - * Adds a single function as a listener to both err and complete. - * - * It will be executed with traditional node.js argument position when the promise is resolved. - * - * promise.addBack(function (err, args...) { - * if (err) return handleError(err); - * console.log('success'); - * }) - * - * Alias of [mpromise#onResolve](https://github.com/aheckmann/mpromise#onresolve). - * - * _Deprecated. Use `onResolve` instead._ - * - * @method addBack - * @param {Function} listener - * @return {Promise} this - * @deprecated - */ - -Promise.prototype.addBack = Promise.prototype.onResolve; - -/** - * Fulfills this promise with passed arguments. - * - * @method fulfill - * @see https://github.com/aheckmann/mpromise#fulfill - * @param {any} args - * @api public - */ - -/** - * Fulfills this promise with passed arguments. - * - * @method fulfill - * @see https://github.com/aheckmann/mpromise#fulfill - * @param {any} args - * @api public - */ - -/** - * Fulfills this promise with passed arguments. - * - * Alias of [mpromise#fulfill](https://github.com/aheckmann/mpromise#fulfill). - * - * _Deprecated. Use `fulfill` instead._ - * - * @method complete - * @param {any} args - * @api public - * @deprecated - */ - -Promise.prototype.complete = MPromise.prototype.fulfill; - -/** - * Adds a listener to the `complete` (success) event. - * - * Alias of [mpromise#onFulfill](https://github.com/aheckmann/mpromise#onfulfill). - * - * _Deprecated. Use `onFulfill` instead._ - * - * @method addCallback - * @param {Function} listener - * @return {Promise} this - * @api public - * @deprecated - */ - -Promise.prototype.addCallback = Promise.prototype.onFulfill; - -/** - * Adds a listener to the `err` (rejected) event. - * - * Alias of [mpromise#onReject](https://github.com/aheckmann/mpromise#onreject). - * - * _Deprecated. Use `onReject` instead._ - * - * @method addErrback - * @param {Function} listener - * @return {Promise} this - * @api public - * @deprecated - */ - -Promise.prototype.addErrback = Promise.prototype.onReject; - -/** - * Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick. - * - * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification. - * - * ####Example: - * - * var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec(); - * promise.then(function (meetups) { - * var ids = meetups.map(function (m) { - * return m._id; - * }); - * return People.find({ meetups: { $in: ids }).exec(); - * }).then(function (people) { - * if (people.length < 10000) { - * throw new Error('Too few people!!!'); - * } else { - * throw new Error('Still need more people!!!'); - * } - * }).then(null, function (err) { - * assert.ok(err instanceof Error); - * }); - * - * @see promises-A+ https://github.com/promises-aplus/promises-spec - * @see mpromise#then https://github.com/aheckmann/mpromise#then - * @method then - * @memberOf Promise - * @param {Function} onFulFill - * @param {Function} onReject - * @return {Promise} newPromise - */ - -/** - * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught. - * - * ####Example: - * - * var p = new Promise; - * p.then(function(){ throw new Error('shucks') }); - * setTimeout(function () { - * p.fulfill(); - * // error was caught and swallowed by the promise returned from - * // p.then(). we either have to always register handlers on - * // the returned promises or we can do the following... - * }, 10); - * - * // this time we use .end() which prevents catching thrown errors - * var p = new Promise; - * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- - * setTimeout(function () { - * p.fulfill(); // throws "shucks" - * }, 10); - * - * @api public - * @see mpromise#end https://github.com/aheckmann/mpromise#end - * @method end - * @memberOf Promise - */ - -/*! - * expose - */ - -module.exports = Promise; diff --git a/node_modules/mongoose/lib/query.js b/node_modules/mongoose/lib/query.js deleted file mode 100644 index f3c8a7c49..000000000 --- a/node_modules/mongoose/lib/query.js +++ /dev/null @@ -1,2889 +0,0 @@ -/*! - * Module dependencies. - */ - -var mquery = require('mquery'); -var util = require('util'); -var events = require('events'); - -var utils = require('./utils'); -var Promise = require('./promise'); -var helpers = require('./queryhelpers'); -var Types = require('./schema/index'); -var Document = require('./document'); -var QueryStream = require('./querystream'); - -/** - * Query constructor used for building queries. - * - * ####Example: - * - * var query = new Query(); - * query.setOptions({ lean : true }); - * query.collection(model.collection); - * query.where('age').gte(21).exec(callback); - * - * @param {Object} [options] - * @param {Object} [model] - * @param {Object} [conditions] - * @param {Object} [collection] Mongoose collection - * @api private - */ - -function Query(conditions, options, model, collection) { - // this stuff is for dealing with custom queries created by #toConstructor - if (!this._mongooseOptions) { - this._mongooseOptions = options || {}; - } else { - // this is the case where we have a CustomQuery, we need to check if we got - // options passed in, and if we did, merge them in - - if (options) { - var keys = Object.keys(options); - for (var i=0; i < keys.length; i++) { - var k = keys[i]; - this._mongooseOptions[k] = options[k]; - } - } - } - - if (collection) { - this.mongooseCollection = collection; - } - - if (model) { - this.model = model; - } - - // this is needed because map reduce returns a model that can be queried, but - // all of the queries on said model should be lean - if (this.model && this.model._mapreduce) { - this.lean(); - } - - // inherit mquery - mquery.call(this, this.mongooseCollection, options); - - if (conditions) { - this.find(conditions); - } -} - -/*! - * inherit mquery - */ - -Query.prototype = new mquery; -Query.prototype.constructor = Query; -Query.base = mquery.prototype; - -/** - * Flag to opt out of using `$geoWithin`. - * - * mongoose.Query.use$geoWithin = false; - * - * MongoDB 2.4 deprecated the use of `$within`, replacing it with `$geoWithin`. Mongoose uses `$geoWithin` by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to `false` so your `within()` queries continue to work. - * - * @see http://docs.mongodb.org/manual/reference/operator/geoWithin/ - * @default true - * @property use$geoWithin - * @memberOf Query - * @receiver Query - * @api public - */ - -Query.use$geoWithin = mquery.use$geoWithin; - -/** - * Converts this query to a customized, reusable query constructor with all arguments and options retained. - * - * ####Example - * - * // Create a query for adventure movies and read from the primary - * // node in the replica-set unless it is down, in which case we'll - * // read from a secondary node. - * var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred'); - * - * // create a custom Query constructor based off these settings - * var Adventure = query.toConstructor(); - * - * // Adventure is now a subclass of mongoose.Query and works the same way but with the - * // default query parameters and options set. - * Adventure().exec(callback) - * - * // further narrow down our query results while still using the previous settings - * Adventure().where({ name: /^Life/ }).exec(callback); - * - * // since Adventure is a stand-alone constructor we can also add our own - * // helper methods and getters without impacting global queries - * Adventure.prototype.startsWith = function (prefix) { - * this.where({ name: new RegExp('^' + prefix) }) - * return this; - * } - * Object.defineProperty(Adventure.prototype, 'highlyRated', { - * get: function () { - * this.where({ rating: { $gt: 4.5 }}); - * return this; - * } - * }) - * Adventure().highlyRated.startsWith('Life').exec(callback) - * - * New in 3.7.3 - * - * @return {Query} subclass-of-Query - * @api public - */ - -Query.prototype.toConstructor = function toConstructor () { - function CustomQuery (criteria, options) { - if (!(this instanceof CustomQuery)) - return new CustomQuery(criteria, options); - Query.call(this, criteria, options || null); - } - - util.inherits(CustomQuery, Query); - - // set inherited defaults - var p = CustomQuery.prototype; - - p.options = {}; - - p.setOptions(this.options); - - p.op = this.op; - p._conditions = utils.clone(this._conditions); - p._fields = utils.clone(this._fields); - p._update = utils.clone(this._update); - p._path = this._path; - p._distict = this._distinct; - p._collection = this._collection; - p.model = this.model; - p.mongooseCollection = this.mongooseCollection; - p._mongooseOptions = this._mongooseOptions; - - return CustomQuery; -} - -/** - * Specifies a javascript function or expression to pass to MongoDBs query system. - * - * ####Example - * - * query.$where('this.comments.length > 10 || this.name.length > 5') - * - * // or - * - * query.$where(function () { - * return this.comments.length > 10 || this.name.length > 5; - * }) - * - * ####NOTE: - * - * Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. - * **Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.** - * - * @see $where http://docs.mongodb.org/manual/reference/operator/where/ - * @method $where - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @method $where - * @api public - */ - -/** - * Specifies a `path` for use with chaining. - * - * ####Example - * - * // instead of writing: - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * // we can instead write: - * User.where('age').gte(21).lte(65); - * - * // passing query conditions is permitted - * User.find().where({ name: 'vonderful' }) - * - * // chaining - * User - * .where('age').gte(21).lte(65) - * .where('name', /^vonderful/i) - * .where('friends').slice(10) - * .exec(callback) - * - * @method where - * @memberOf Query - * @param {String|Object} [path] - * @param {any} [val] - * @return {Query} this - * @api public - */ - -/** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @method equals - * @memberOf Query - * @param {Object} val - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @see $or http://docs.mongodb.org/manual/reference/operator/or/ - * @method or - * @memberOf Query - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @see $nor http://docs.mongodb.org/manual/reference/operator/nor/ - * @method nor - * @memberOf Query - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @method and - * @memberOf Query - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -/** - * Specifies a $gt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * Thing.find().where('age').gt(21) - * - * // or - * Thing.find().gt('age', 21) - * - * @method gt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @see $gt http://docs.mongodb.org/manual/reference/operator/gt/ - * @api public - */ - -/** - * Specifies a $gte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method gte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @see $gte http://docs.mongodb.org/manual/reference/operator/gte/ - * @api public - */ - -/** - * Specifies a $lt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @see $lt http://docs.mongodb.org/manual/reference/operator/lt/ - * @api public - */ - -/** - * Specifies a $lte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @see $lte http://docs.mongodb.org/manual/reference/operator/lte/ - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $ne query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $ne http://docs.mongodb.org/manual/reference/operator/ne/ - * @method ne - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $in query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $in http://docs.mongodb.org/manual/reference/operator/in/ - * @method in - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $nin query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $nin http://docs.mongodb.org/manual/reference/operator/nin/ - * @method nin - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $all query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $all http://docs.mongodb.org/manual/reference/operator/all/ - * @method all - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $size query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * MyModel.where('tags').size(0).exec(function (err, docs) { - * if (err) return handleError(err); - * - * assert(Array.isArray(docs)); - * console.log('documents with 0 tags', docs); - * }) - * - * @see $size http://docs.mongodb.org/manual/reference/operator/size/ - * @method size - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $regex query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $regex http://docs.mongodb.org/manual/reference/operator/regex/ - * @method regex - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $maxDistance query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @method maxDistance - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a `$mod` condition - * - * @method mod - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @see $mod http://docs.mongodb.org/manual/reference/operator/mod/ - * @api public - */ - -/** - * Specifies an `$exists` condition - * - * ####Example - * - * // { name: { $exists: true }} - * Thing.where('name').exists() - * Thing.where('name').exists(true) - * Thing.find().exists('name') - * - * // { name: { $exists: false }} - * Thing.where('name').exists(false); - * Thing.find().exists('name', false); - * - * @method exists - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @see $exists http://docs.mongodb.org/manual/reference/operator/exists/ - * @api public - */ - -/** - * Specifies an `$elemMatch` condition - * - * ####Example - * - * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) - * - * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - * - * query.elemMatch('comment', function (elem) { - * elem.where('author').equals('autobot'); - * elem.where('votes').gte(5); - * }) - * - * query.where('comment').elemMatch(function (elem) { - * elem.where({ author: 'autobot' }); - * elem.where('votes').gte(5); - * }) - * - * @method elemMatch - * @memberOf Query - * @param {String|Object|Function} path - * @param {Object|Function} criteria - * @return {Query} this - * @see $elemMatch http://docs.mongodb.org/manual/reference/operator/elemMatch/ - * @api public - */ - -/** - * Defines a `$within` or `$geoWithin` argument for geo-spatial queries. - * - * ####Example - * - * query.where(path).within().box() - * query.where(path).within().circle() - * query.where(path).within().geometry() - * - * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); - * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); - * query.where('loc').within({ polygon: [[],[],[],[]] }); - * - * query.where('loc').within([], [], []) // polygon - * query.where('loc').within([], []) // box - * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * As of Mongoose 3.7, `$geoWithin` is always used for queries. To change this behavior, see [Query.use$geoWithin](#query_Query-use%2524geoWithin). - * - * ####NOTE: - * - * In Mongoose 3.7, `within` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method within - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @memberOf Query - * @return {Query} this - * @api public - */ - -/** - * Specifies a $slice projection for an array. - * - * ####Example - * - * query.slice('comments', 5) - * query.slice('comments', -5) - * query.slice('comments', [10, 5]) - * query.where('comments').slice(5) - * query.where('comments').slice([-10, 5]) - * - * @method slice - * @memberOf Query - * @param {String} [path] - * @param {Number} val number/range of elements to slice - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements - * @see $slice http://docs.mongodb.org/manual/reference/projection/slice/#prj._S_slice - * @api public - */ - -/** - * Specifies the maximum number of documents the query will return. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @param {Number} val - * @api public - */ - -/** - * Specifies the number of documents to skip. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @param {Number} val - * @see cursor.skip http://docs.mongodb.org/manual/reference/method/cursor.skip/ - * @api public - */ - -/** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @param {Number} val - * @see maxScan http://docs.mongodb.org/manual/reference/operator/maxScan/ - * @api public - */ - -/** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @param {Number} val - * @see batchSize http://docs.mongodb.org/manual/reference/method/cursor.batchSize/ - * @api public - */ - -/** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @param {Number} val - * @see comment http://docs.mongodb.org/manual/reference/operator/comment/ - * @api public - */ - -/** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * query.snapshot() // true - * query.snapshot(true) - * query.snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method snapshot - * @memberOf Query - * @see snapshot http://docs.mongodb.org/manual/reference/operator/snapshot/ - * @return {Query} this - * @api public - */ - -/** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method hint - * @memberOf Query - * @param {Object} val a hint object - * @return {Query} this - * @see $hint http://docs.mongodb.org/manual/reference/operator/hint/ - * @api public - */ - -/** - * Specifies which document fields to include or exclude - * - * When using string syntax, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. Lastly, if a path is prefixed with `+`, it forces inclusion of the path, which is useful for paths excluded at the [schema level](/docs/api.html#schematype_SchemaType-select). - * - * ####Example - * - * // include a and b, exclude c - * query.select('a b -c'); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({a: 1, b: 1, c: 0}); - * - * // force inclusion of field excluded at schema level - * query.select('+path') - * - * ####NOTE: - * - * Cannot be used with `distinct()`. - * - * _v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3._ - * - * @method select - * @memberOf Query - * @param {Object|String} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - -/** - * _DEPRECATED_ Sets the slaveOk option. - * - * **Deprecated** in MongoDB 2.2 in favor of [read preferences](#query_Query-read). - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @method slaveOk - * @memberOf Query - * @deprecated use read() preferences instead if on mongodb >= 2.2 - * @param {Boolean} v defaults to true - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see slaveOk http://docs.mongodb.org/manual/reference/method/rs.slaveOk/ - * @see read() #query_Query-read - * @return {Query} this - * @api public - */ - -/** - * Determines the MongoDB nodes from which to read. - * - * ####Preferences: - * - * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. - * secondary Read from secondary if available, otherwise error. - * primaryPreferred Read from primary if available, otherwise a secondary. - * secondaryPreferred Read from a secondary if available, otherwise read from the primary. - * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - * - * Aliases - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * ####Example: - * - * new Query().read('primary') - * new Query().read('p') // same as primary - * - * new Query().read('primaryPreferred') - * new Query().read('pp') // same as primaryPreferred - * - * new Query().read('secondary') - * new Query().read('s') // same as secondary - * - * new Query().read('secondaryPreferred') - * new Query().read('sp') // same as secondaryPreferred - * - * new Query().read('nearest') - * new Query().read('n') // same as nearest - * - * // read from secondaries with matching tags - * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) - * - * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - * - * @method read - * @memberOf Query - * @param {String} pref one of the listed preference options or aliases - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - * @return {Query} this - * @api public - */ - -/** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * New in 3.7.0 - * - * @method merge - * @memberOf Query - * @param {Query|Object} source - * @return {Query} this - */ - -/** - * Sets query options. - * - * ####Options: - * - * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * - * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * - * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * - * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * - * - [maxscan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * - * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * - * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * - * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * - * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * - * - [lean](./api.html#query_Query-lean) * - * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) - * - * _* denotes a query helper method is also available_ - * - * @param {Object} options - * @api public - */ - -Query.prototype.setOptions = function (options, overwrite) { - // overwrite is only for internal use - if (overwrite) { - // ensure that _mongooseOptions & options are two different objects - this._mongooseOptions = (options && utils.clone(options)) || {}; - this.options = options || {}; - - if('populate' in options) { - this.populate(this._mongooseOptions); - } - return this; - } - - if (!(options && 'Object' == options.constructor.name)) { - return this; - } - - return Query.base.setOptions.call(this, options); -} - -/** - * Returns fields selection for this query. - * - * @method _fieldsForExec - * @return {Object} - * @api private - */ - -/** - * Return an update document with corrected $set operations. - * - * @method _updateForExec - * @api private - */ - -/** - * Makes sure _path is set. - * - * @method _ensurePath - * @param {String} method - * @api private - */ - -/** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @method canMerge - * @memberOf Query - * @param {Object} conds - * @return {Boolean} - * @api private - */ - -/** - * Returns default options for this query. - * - * @param {Model} model - * @api private - */ - -Query.prototype._optionsForExec = function (model) { - var options = Query.base._optionsForExec.call(this); - - delete options.populate; - - if (!model) { - return options; - } else { - if (!('safe' in options) && model.schema.options.safe) { - options.safe = model.schema.options.safe; - } - - if(!('readPreference' in options) && model.schema.options.read) { - options.readPreference = model.schema.options.read; - } - - return options; - } -}; - -/** - * Sets the lean option. - * - * Documents returned from queries with the `lean` option enabled are plain javascript objects, not [MongooseDocuments](#document-js). They have no `save` method, getters/setters or other Mongoose magic applied. - * - * ####Example: - * - * new Query().lean() // true - * new Query().lean(true) - * new Query().lean(false) - * - * Model.find().lean().exec(function (err, docs) { - * docs[0] instanceof mongoose.Document // false - * }); - * - * This is a [great](https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion) option in high-performance read-only scenarios, especially when combined with [stream](#query_Query-stream). - * - * @param {Boolean} bool defaults to true - * @return {Query} this - * @api public - */ - -Query.prototype.lean = function (v) { - this._mongooseOptions.lean = arguments.length ? !!v : true; - return this; -} - -/** - * Finds documents. - * - * When no `callback` is passed, the query is not executed. - * - * ####Example - * - * query.find({ name: 'Los Pollos Hermanos' }).find(callback) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.find = function (conditions, callback) { - if ('function' == typeof conditions) { - callback = conditions; - conditions = {}; - } else if (conditions instanceof Document) { - conditions = conditions.toObject(); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - prepareDiscriminatorCriteria(this); - - try { - this.cast(this.model); - this._castError = null; - } catch (err) { - this._castError = err; - } - - // if we don't have a callback, then just return the query object - if (!callback) { - return Query.base.find.call(this); - } - - var promise = new Promise(callback); - if (this._castError) { - promise.error(this._castError); - return this; - } - - this._applyPaths(); - this._fields = this._castFields(this._fields); - - var fields = this._fieldsForExec(); - var options = this._mongooseOptions; - var self = this; - - return Query.base.find.call(this, {}, cb); - - function cb(err, docs) { - if (err) return promise.error(err); - - if (0 === docs.length) { - return promise.complete(docs); - } - - if (!options.populate) { - return true === options.lean - ? promise.complete(docs) - : completeMany(self.model, docs, fields, self, null, promise); - } - - var pop = helpers.preparePopulationOptionsMQ(self, options); - self.model.populate(docs, pop, function (err, docs) { - if(err) return promise.error(err); - return true === options.lean - ? promise.complete(docs) - : completeMany(self.model, docs, fields, self, pop, promise); - }); - } -} - -/*! - * hydrates many documents - * - * @param {Model} model - * @param {Array} docs - * @param {Object} fields - * @param {Query} self - * @param {Array} [pop] array of paths used in population - * @param {Promise} promise - */ - -function completeMany (model, docs, fields, self, pop, promise) { - var arr = []; - var count = docs.length; - var len = count; - var opts = pop ? - { populated: pop } - : undefined; - for (var i=0; i < len; ++i) { - arr[i] = helpers.createModel(model, docs[i], fields); - arr[i].init(docs[i], opts, function (err) { - if (err) return promise.error(err); - --count || promise.complete(arr); - }); - } -} - -/** - * Declares the query a findOne operation. When executed, the first found document is passed to the callback. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * var query = Kitten.where({ color: 'white' }); - * query.findOne(function (err, kitten) { - * if (err) return handleError(err); - * if (kitten) { - * // doc may be null if no document matched - * } - * }); - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see findOne http://docs.mongodb.org/manual/reference/method/db.collection.findOne/ - * @api public - */ - -Query.prototype.findOne = function (conditions, fields, options, callback) { - if ('function' == typeof conditions) { - callback = conditions; - conditions = null; - fields = null; - options = null; - } - - if ('function' == typeof fields) { - callback = fields; - options = null; - fields = null; - } - - if ('function' == typeof options) { - callback = options; - options = null; - } - - // make sure we don't send in the whole Document to merge() - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } - - if (options) { - this.setOptions(options); - } - - if (fields) { - this.select(fields); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - prepareDiscriminatorCriteria(this); - - try { - this.cast(this.model); - this._castError = null; - } catch (err) { - this._castError = err; - } - - if (!callback) { - // already merged in the conditions, don't need to send them in. - return Query.base.findOne.call(this); - } - - var promise = new Promise(callback); - - if (this._castError) { - promise.error(this._castError); - return this; - } - - this._applyPaths(); - this._fields = this._castFields(this._fields); - - var options = this._mongooseOptions; - var fields = this._fieldsForExec(); - var self = this; - - // don't pass in the conditions because we already merged them in - Query.base.findOne.call(this, {}, function cb (err, doc) { - if (err) return promise.error(err); - if (!doc) return promise.complete(null); - - if (!options.populate) { - return true === options.lean - ? promise.complete(doc) - : completeOne(self.model, doc, fields, self, null, promise); - } - - var pop = helpers.preparePopulationOptionsMQ(self, options); - self.model.populate(doc, pop, function (err, doc) { - if (err) return promise.error(err); - - return true === options.lean - ? promise.complete(doc) - : completeOne(self.model, doc, fields, self, pop, promise); - }); - }) - - return this; -} - -/** - * Specifying this query as a `count` query. - * - * Passing a `callback` executes the query. - * - * ####Example: - * - * var countQuery = model.where({ 'color': 'black' }).count(); - * - * query.count({ color: 'black' }).count(callback) - * - * query.count({ color: 'black' }, callback) - * - * query.where('color', 'black').count(function (err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see count http://docs.mongodb.org/manual/reference/method/db.collection.count/ - * @api public - */ - -Query.prototype.count = function (conditions, callback) { - if ('function' == typeof conditions) { - callback = conditions; - conditions = undefined; - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions); - } - - try { - this.cast(this.model); - } catch (err) { - callback(err); - return this; - } - - return Query.base.count.call(this, {}, callback); -} - -/** - * Declares or executes a distict() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * distinct(criteria, field, fn) - * distinct(criteria, field) - * distinct(field, fn) - * distinct(field) - * distinct(fn) - * distinct() - * - * @param {Object|Query} [criteria] - * @param {String} [field] - * @param {Function} [callback] - * @return {Query} this - * @see distinct http://docs.mongodb.org/manual/reference/method/db.collection.distinct/ - * @api public - */ - -Query.prototype.distinct = function (conditions, field, callback) { - if (!callback) { - if('function' == typeof field) { - callback = field; - if ('string' == typeof conditions) { - field = conditions; - conditions = undefined; - } - } - - switch (typeof conditions) { - case 'string': - field = conditions; - conditions = undefined; - break; - case 'function': - callback = conditions; - field = undefined; - conditions = undefined; - break; - } - } - - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } - - if (mquery.canMerge(conditions)) { - this.merge(conditions) - } - - try { - this.cast(this.model); - } catch (err) { - callback(err); - return this; - } - - return Query.base.distinct.call(this, {}, field, callback); -} - -/** - * Sets the sort order - * - * If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - * - * If a string is passed, it must be a space delimited list of path names. The - * sort order of each path is ascending unless the path name is prefixed with `-` - * which will be treated as descending. - * - * ####Example - * - * // sort by "field" ascending and "test" descending - * query.sort({ field: 'asc', test: -1 }); - * - * // equivalent - * query.sort('field -test'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see cursor.sort http://docs.mongodb.org/manual/reference/method/cursor.sort/ - * @api public - */ - -Query.prototype.sort = function (arg) { - var nArg = {}; - - if (arguments.length > 1) { - throw new Error("sort() only takes 1 Argument"); - } - - if (Array.isArray(arg)) { - // time to deal with the terrible syntax - for (var i=0; i < arg.length; i++) { - if (!Array.isArray(arg[i])) throw new Error("Invalid sort() argument."); - nArg[arg[i][0]] = arg[i][1]; - } - - } else { - nArg = arg; - } - - return Query.base.sort.call(this, nArg); -} - -/** - * Declare and/or execute this query as a remove() operation. - * - * ####Example - * - * Model.remove({ artist: 'Anne Murray' }, callback) - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. - * - * // not executed - * var query = Model.find().remove({ name: 'Anne Murray' }) - * - * // executed - * query.remove({ name: 'Anne Murray' }, callback) - * query.remove({ name: 'Anne Murray' }).remove(callback) - * - * // executed without a callback (unsafe write) - * query.exec() - * - * // summary - * query.remove(conds, fn); // executes - * query.remove(conds) - * query.remove(fn) // executes - * query.remove() - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see remove http://docs.mongodb.org/manual/reference/method/db.collection.remove/ - * @api public - */ - -Query.prototype.remove = function (cond, callback) { - if ('function' == typeof cond) { - callback = cond; - cond = null; - } - - var cb = 'function' == typeof callback; - - try { - this.cast(this.model); - } catch (err) { - if (cb) return process.nextTick(callback.bind(null, err)); - return this; - } - - return Query.base.remove.call(this, cond, callback); -} - -/*! - * hydrates a document - * - * @param {Model} model - * @param {Document} doc - * @param {Object} fields - * @param {Query} self - * @param {Array} [pop] array of paths used in population - * @param {Promise} promise - */ - -function completeOne (model, doc, fields, self, pop, promise) { - var opts = pop ? - { populated: pop } - : undefined; - - var casted = helpers.createModel(model, doc, fields) - casted.init(doc, opts, function (err) { - if (err) return promise.error(err); - promise.complete(casted); - }); -} - -/*! - * If the model is a discriminator type and not root, then add the key & value to the criteria. - */ - -function prepareDiscriminatorCriteria(query) { - if (!query || !query.model || !query.model.schema) { - return; - } - - var schema = query.model.schema; - - if (schema && schema.discriminatorMapping && !schema.discriminatorMapping.isRoot) { - query._conditions[schema.discriminatorMapping.key] = schema.discriminatorMapping.value; - } -} - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. - * - * ####Available options - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * query.findOneAndUpdate(conditions, update, options, callback) // executes - * query.findOneAndUpdate(conditions, update, options) // returns Query - * query.findOneAndUpdate(conditions, update, callback) // executes - * query.findOneAndUpdate(conditions, update) // returns Query - * query.findOneAndUpdate(update, callback) // returns Query - * query.findOneAndUpdate(update) // returns Query - * query.findOneAndUpdate(callback) // executes - * query.findOneAndUpdate() // returns Query - * - * @method findOneAndUpdate - * @memberOf Query - * @param {Object|Query} [query] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Function} [callback] - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @return {Query} this - * @api public - */ - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * A.where().findOneAndRemove(conditions, options, callback) // executes - * A.where().findOneAndRemove(conditions, options) // return Query - * A.where().findOneAndRemove(conditions, callback) // executes - * A.where().findOneAndRemove(conditions) // returns Query - * A.where().findOneAndRemove(callback) // executes - * A.where().findOneAndRemove() // returns Query - * - * @method findOneAndRemove - * @memberOf Query - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -/** - * Override mquery.prototype._findAndModify to provide casting etc. - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ - -Query.prototype._findAndModify = function (type, callback) { - if ('function' != typeof callback) { - throw new Error("Expected callback in _findAndModify"); - } - - var model = this.model - , promise = new Promise(callback) - , self = this - , castedQuery - , castedDoc - , fields - , opts; - - castedQuery = castQuery(this); - if (castedQuery instanceof Error) { - process.nextTick(promise.error.bind(promise, castedQuery)); - return promise; - } - - opts = this._optionsForExec(model); - - if ('remove' == type) { - opts.remove = true; - } else { - if (!('new' in opts)) opts.new = true; - if (!('upsert' in opts)) opts.upsert = false; - - castedDoc = castDoc(this); - if (!castedDoc) { - if (opts.upsert) { - // still need to do the upsert to empty doc - castedDoc = { $set: {} }; - } else { - return this.findOne(callback); - } - } else if (castedDoc instanceof Error) { - process.nextTick(promise.error.bind(promise, castedDoc)); - return promise; - } - } - - this._applyPaths(); - - var self = this; - var options = this._mongooseOptions; - - if (this._fields) { - fields = utils.clone(this._fields); - opts.fields = this._castFields(fields); - if (opts.fields instanceof Error) { - process.nextTick(promise.error.bind(promise, opts.fields)); - return promise; - } - } - - this._collection.findAndModify(castedQuery, castedDoc, opts, utils.tick(cb)); - function cb (err, doc) { - if (err) return promise.error(err); - - if (!doc || (utils.isObject(doc) && Object.keys(doc).length === 0)) { - return promise.complete(null); - } - - if (!options.populate) { - return true === options.lean - ? promise.complete(doc) - : completeOne(self.model, doc, fields, self, null, promise); - } - - var pop = helpers.preparePopulationOptionsMQ(self, options); - self.model.populate(doc, pop, function (err, doc) { - if (err) return promise.error(err); - - return true === options.lean - ? promise.complete(doc) - : completeOne(self.model, doc, fields, self, pop, promise); - }); - } - - return promise; -} - -/** - * Declare and/or execute this query as an update() operation. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * Model.where({ _id: id }).update({ title: 'words' }) - * - * // becomes - * - * Model.where({ _id: id }).update({ $set: { title: 'words' }}) - * - * ####Note - * - * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. - * - * var q = Model.where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe - * - * // keys that are not $atomic ops become $set. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).exec(); - * - * // overwriting with empty docs - * var q = Model.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * var q = Model.where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * Model.where() - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * - * // more multi updates - * Model.where() - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * Model.where({ email: 'address@example.com' }) - * .update({ $inc: { counter: 1 }}, callback) - * - * API summary - * - * update(criteria, doc, options, cb) // executes - * update(criteria, doc, options) - * update(criteria, doc, cb) // executes - * update(criteria, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes (unsafe write) - * update() - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @see Model.update #model_Model.update - * @see update http://docs.mongodb.org/manual/reference/method/db.collection.update/ - * @api public - */ - -Query.prototype.update = function (conditions, doc, options, callback) { - if ('function' === typeof options) { - // Scenario: update(conditions, doc, callback) - callback = options; - options = null; - } else if ('function' === typeof doc) { - // Scenario: update(doc, callback); - callback = doc; - doc = conditions; - conditions = {}; - options = null; - } else if ('function' === typeof conditions) { - callback = conditions; - conditions = undefined; - doc = undefined; - options = undefined; - } - - // make sure we don't send in the whole Document to merge() - if (conditions instanceof Document) { - conditions = conditions.toObject(); - } - - // strict is an option used in the update checking, make sure it gets set - if (options) { - if ('strict' in options) { - this._mongooseOptions.strict = options.strict; - } - } - - // if doc is undefined at this point, this means this function is being - // executed by exec(not always see below). Grab the update doc from here in - // order to validate - // This could also be somebody calling update() or update({}). Probably not a - // common use case, check for _update to make sure we don't do anything bad - if (!doc && this._update) { - doc = this._updateForExec(); - } - - if (conditions) { - this._conditions = conditions; - } - - // validate the selector part of the query - var castedQuery = castQuery(this); - if (castedQuery instanceof Error) { - if(callback) { - callback(castedQuery); - return this; - } else { - throw castedQuery; - } - } - - // validate the update part of the query - var castedDoc; - try { - castedDoc = this._castUpdate(doc, options && options.overwrite); - } catch (err) { - if (callback) { - callback(err); - return this; - } else { - throw err; - } - } - - if (!castedDoc) { - callback && callback(null, 0); - return this; - } - - return Query.base.update.call(this, castedQuery, castedDoc, options, callback); -} - -/** - * Executes the query - * - * ####Examples: - * - * var promise = query.exec(); - * var promise = query.exec('update'); - * - * query.exec(callback); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Query.prototype.exec = function exec (op, callback) { - var promise = new Promise(); - - if ('function' == typeof op) { - callback = op; - op = null; - } else if ('string' == typeof op) { - this.op = op; - } - - if (callback) promise.addBack(callback); - - if (!this.op) { - promise.complete(); - return promise; - } - - Query.base.exec.call(this, op, promise.resolve.bind(promise)); - - return promise; -} - -/** - * Finds the schema for `path`. This is different than - * calling `schema.path` as it also resolves paths with - * positional selectors (something.$.another.$.path). - * - * @param {String} path - * @api private - */ - -Query.prototype._getSchema = function _getSchema (path) { - return this.model._getSchema(path); -} - -/*! - * These operators require casting docs - * to real Documents for Update operations. - */ - -var castOps = { - $push: 1 - , $pushAll: 1 - , $addToSet: 1 - , $set: 1 -}; - -/*! - * These operators should be cast to numbers instead - * of their path schema type. - */ - -var numberOps = { - $pop: 1 - , $unset: 1 - , $inc: 1 -} - -/** - * Casts obj for an update command. - * - * @param {Object} obj - * @return {Object} obj after casting its values - * @api private - */ - -Query.prototype._castUpdate = function _castUpdate (obj, overwrite) { - if (!obj) return undefined; - - var ops = Object.keys(obj) - , i = ops.length - , ret = {} - , hasKeys - , val - - while (i--) { - var op = ops[i]; - // if overwrite is set, don't do any of the special $set stuff - if ('$' !== op[0] && !overwrite) { - // fix up $set sugar - if (!ret.$set) { - if (obj.$set) { - ret.$set = obj.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = obj[op]; - ops.splice(i, 1); - if (!~ops.indexOf('$set')) ops.push('$set'); - } else if ('$set' === op) { - if (!ret.$set) { - ret[op] = obj[op]; - } - } else { - ret[op] = obj[op]; - } - } - - // cast each value - i = ops.length; - - // if we get passed {} for the update, we still need to respect that when it - // is an overwrite scenario - if (overwrite) { - hasKeys = true; - } - - while (i--) { - op = ops[i]; - val = ret[op]; - if ('Object' === val.constructor.name && !overwrite) { - hasKeys |= this._walkUpdatePath(val, op); - } else if (overwrite && 'Object' === ret.constructor.name) { - // if we are just using overwrite, cast the query and then we will - // *always* return the value, even if it is an empty object. We need to - // set hasKeys above because we need to account for the case where the - // user passes {} and wants to clobber the whole document - // Also, _walkUpdatePath expects an operation, so give it $set since that - // is basically what we're doing - this._walkUpdatePath(ret, '$set'); - } else { - var msg = 'Invalid atomic update value for ' + op + '. ' - + 'Expected an object, received ' + typeof val; - throw new Error(msg); - } - } - - return hasKeys && ret; -} - -/** - * Walk each path of obj and cast its values - * according to its schema. - * - * @param {Object} obj - part of a query - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {String} pref - path prefix (internal only) - * @return {Bool} true if this path has keys to update - * @api private - */ - -Query.prototype._walkUpdatePath = function _walkUpdatePath (obj, op, pref) { - var prefix = pref ? pref + '.' : '' - , keys = Object.keys(obj) - , i = keys.length - , hasKeys = false - , schema - , key - , val - - var strict = 'strict' in this._mongooseOptions - ? this._mongooseOptions.strict - : this.model.schema.options.strict; - - while (i--) { - key = keys[i]; - val = obj[key]; - - if (val && 'Object' === val.constructor.name) { - // watch for embedded doc schemas - schema = this._getSchema(prefix + key); - if (schema && schema.caster && op in castOps) { - // embedded doc schema - - if (strict && !schema) { - // path is not in our strict schema - if ('throw' == strict) { - throw new Error('Field `' + key + '` is not in schema.'); - } else { - // ignore paths not specified in schema - delete obj[key]; - } - } else { - hasKeys = true; - - if ('$each' in val) { - obj[key] = { - $each: this._castUpdateVal(schema, val.$each, op) - } - - if (val.$slice) { - obj[key].$slice = val.$slice | 0; - } - - if (val.$sort) { - obj[key].$sort = val.$sort; - } - - } else { - obj[key] = this._castUpdateVal(schema, val, op); - } - } - } else { - hasKeys |= this._walkUpdatePath(val, op, prefix + key); - } - } else { - schema = '$each' === key - ? this._getSchema(pref) - : this._getSchema(prefix + key); - - var skip = strict && - !schema && - !/real|nested/.test(this.model.schema.pathType(prefix + key)); - - if (skip) { - if ('throw' == strict) { - throw new Error('Field `' + prefix + key + '` is not in schema.'); - } else { - delete obj[key]; - } - } else { - hasKeys = true; - obj[key] = this._castUpdateVal(schema, val, op, key); - } - } - } - return hasKeys; -} - -/** - * Casts `val` according to `schema` and atomic `op`. - * - * @param {Schema} schema - * @param {Object} val - * @param {String} op - the atomic operator ($pull, $set, etc) - * @param {String} [$conditional] - * @api private - */ - -Query.prototype._castUpdateVal = function _castUpdateVal (schema, val, op, $conditional) { - if (!schema) { - // non-existing schema path - return op in numberOps - ? Number(val) - : val - } - - if (schema.caster && op in castOps && - (utils.isObject(val) || Array.isArray(val))) { - // Cast values for ops that add data to MongoDB. - // Ensures embedded documents get ObjectIds etc. - var tmp = schema.cast(val); - - if (Array.isArray(val)) { - val = tmp; - } else { - val = tmp[0]; - } - } - - if (op in numberOps) return Number(val); - if (/^\$/.test($conditional)) return schema.castForQuery($conditional, val); - return schema.castForQuery(val) -} - -/*! - * castQuery - * @api private - */ - -function castQuery (query) { - try { - return query.cast(query.model); - } catch (err) { - return err; - } -} - -/*! - * castDoc - * @api private - */ - -function castDoc (query) { - try { - return query._castUpdate(query._update); - } catch (err) { - return err; - } -} - -/** - * Specifies paths which should be populated with other documents. - * - * ####Example: - * - * Kitten.findOne().populate('owner').exec(function (err, kitten) { - * console.log(kitten.owner.name) // Max - * }) - * - * Kitten.find().populate({ - * path: 'owner' - * , select: 'name' - * , match: { color: 'black' } - * , options: { sort: { name: -1 }} - * }).exec(function (err, kittens) { - * console.log(kittens[0].owner.name) // Zoopa - * }) - * - * // alternatively - * Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { - * console.log(kittens[0].owner.name) // Zoopa - * }) - * - * Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback. - * - * @param {Object|String} path either the path to populate or an object specifying all parameters - * @param {Object|String} [select] Field selection for the population query - * @param {Model} [model] The name of the model you wish to use for population. If not specified, the name is looked up from the Schema ref. - * @param {Object} [match] Conditions for the population query - * @param {Object} [options] Options for the population query (sort, etc) - * @see population ./populate.html - * @see Query#select #query_Query-select - * @see Model.populate #model_Model.populate - * @return {Query} this - * @api public - */ - -Query.prototype.populate = function () { - var res = utils.populate.apply(null, arguments); - var opts = this._mongooseOptions; - - if (!utils.isObject(opts.populate)) { - opts.populate = {}; - } - - for (var i = 0; i < res.length; ++i) { - opts.populate[res[i].path] = res[i]; - } - - return this; -} - -/** - * Casts this query to the schema of `model` - * - * ####Note - * - * If `obj` is present, it is cast instead of this query. - * - * @param {Model} model - * @param {Object} [obj] - * @return {Object} - * @api public - */ - -Query.prototype.cast = function (model, obj) { - obj || (obj = this._conditions); - - var schema = model.schema - , paths = Object.keys(obj) - , i = paths.length - , any$conditionals - , schematype - , nested - , path - , type - , val; - - while (i--) { - path = paths[i]; - val = obj[path]; - - if ('$or' === path || '$nor' === path || '$and' === path) { - var k = val.length - , orComponentQuery; - - while (k--) { - orComponentQuery = new Query(val[k], {}, null, this.mongooseCollection); - orComponentQuery.cast(model); - val[k] = orComponentQuery._conditions; - } - - } else if (path === '$where') { - type = typeof val; - - if ('string' !== type && 'function' !== type) { - throw new Error("Must have a string or function for $where"); - } - - if ('function' === type) { - obj[path] = val.toString(); - } - - continue; - - } else { - - if (!schema) { - // no casting for Mixed types - continue; - } - - schematype = schema.path(path); - - if (!schematype) { - // Handle potential embedded array queries - var split = path.split('.') - , j = split.length - , pathFirstHalf - , pathLastHalf - , remainingConds - , castingQuery; - - // Find the part of the var path that is a path of the Schema - while (j--) { - pathFirstHalf = split.slice(0, j).join('.'); - schematype = schema.path(pathFirstHalf); - if (schematype) break; - } - - // If a substring of the input path resolves to an actual real path... - if (schematype) { - // Apply the casting; similar code for $elemMatch in schema/array.js - if (schematype.caster && schematype.caster.schema) { - remainingConds = {}; - pathLastHalf = split.slice(j).join('.'); - remainingConds[pathLastHalf] = val; - castingQuery = new Query(remainingConds, {}, null, this.mongooseCollection); - castingQuery.cast(schematype.caster); - obj[path] = castingQuery._conditions[pathLastHalf]; - } else { - obj[path] = val; - } - continue; - } - - if (utils.isObject(val)) { - // handle geo schemas that use object notation - // { loc: { long: Number, lat: Number } - - var geo = val.$near ? '$near' : - val.$nearSphere ? '$nearSphere' : - val.$within ? '$within' : - val.$geoIntersects ? '$geoIntersects' : ''; - - if (!geo) { - continue; - } - - var numbertype = new Types.Number('__QueryCasting__') - var value = val[geo]; - - if (val.$maxDistance) { - val.$maxDistance = numbertype.castForQuery(val.$maxDistance); - } - - if ('$within' == geo) { - var withinType = value.$center - || value.$centerSphere - || value.$box - || value.$polygon; - - if (!withinType) { - throw new Error('Bad $within paramater: ' + JSON.stringify(val)); - } - - value = withinType; - - } else if ('$near' == geo && - 'string' == typeof value.type && Array.isArray(value.coordinates)) { - // geojson; cast the coordinates - value = value.coordinates; - - } else if (('$near' == geo || '$geoIntersects' == geo) && - value.$geometry && 'string' == typeof value.$geometry.type && - Array.isArray(value.$geometry.coordinates)) { - // geojson; cast the coordinates - value = value.$geometry.coordinates; - } - - ;(function _cast (val) { - if (Array.isArray(val)) { - val.forEach(function (item, i) { - if (Array.isArray(item) || utils.isObject(item)) { - return _cast(item); - } - val[i] = numbertype.castForQuery(item); - }); - } else { - var nearKeys= Object.keys(val); - var nearLen = nearKeys.length; - while (nearLen--) { - var nkey = nearKeys[nearLen]; - var item = val[nkey]; - if (Array.isArray(item) || utils.isObject(item)) { - _cast(item); - val[nkey] = item; - } else { - val[nkey] = numbertype.castForQuery(item); - } - } - } - })(value); - } - - } else if (val === null || val === undefined) { - continue; - } else if ('Object' === val.constructor.name) { - - any$conditionals = Object.keys(val).some(function (k) { - return k.charAt(0) === '$' && k !== '$id' && k !== '$ref'; - }); - - if (!any$conditionals) { - obj[path] = schematype.castForQuery(val); - } else { - - var ks = Object.keys(val) - , k = ks.length - , $cond; - - while (k--) { - $cond = ks[k]; - nested = val[$cond]; - - if ('$exists' === $cond) { - if ('boolean' !== typeof nested) { - throw new Error("$exists parameter must be Boolean"); - } - continue; - } - - if ('$type' === $cond) { - if ('number' !== typeof nested) { - throw new Error("$type parameter must be Number"); - } - continue; - } - - if ('$not' === $cond) { - this.cast(model, nested); - } else { - val[$cond] = schematype.castForQuery($cond, nested); - } - } - } - } else { - obj[path] = schematype.castForQuery(val); - } - } - } - - return obj; -} - -/** - * Casts selected field arguments for field selection with mongo 2.2 - * - * query.select({ ids: { $elemMatch: { $in: [hexString] }}) - * - * @param {Object} fields - * @see https://github.com/LearnBoost/mongoose/issues/1091 - * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ - * @api private - */ - -Query.prototype._castFields = function _castFields (fields) { - var selected - , elemMatchKeys - , keys - , key - , out - , i - - if (fields) { - keys = Object.keys(fields); - elemMatchKeys = []; - i = keys.length; - - // collect $elemMatch args - while (i--) { - key = keys[i]; - if (fields[key].$elemMatch) { - selected || (selected = {}); - selected[key] = fields[key]; - elemMatchKeys.push(key); - } - } - } - - if (selected) { - // they passed $elemMatch, cast em - try { - out = this.cast(this.model, selected); - } catch (err) { - return err; - } - - // apply the casted field args - i = elemMatchKeys.length; - while (i--) { - key = elemMatchKeys[i]; - fields[key] = out[key]; - } - } - - return fields; -} - -/** - * Applies schematype selected options to this query. - * @api private - */ - -Query.prototype._applyPaths = function applyPaths () { - // determine if query is selecting or excluding fields - - var fields = this._fields - , exclude - , keys - , ki - - if (fields) { - keys = Object.keys(fields); - ki = keys.length; - - while (ki--) { - if ('+' == keys[ki][0]) continue; - exclude = 0 === fields[keys[ki]]; - break; - } - } - - // if selecting, apply default schematype select:true fields - // if excluding, apply schematype select:false fields - - var selected = [] - , excluded = [] - , seen = []; - - analyzeSchema(this.model.schema); - - switch (exclude) { - case true: - excluded.length && this.select('-' + excluded.join(' -')); - break; - case false: - selected.length && this.select(selected.join(' ')); - break; - case undefined: - // user didn't specify fields, implies returning all fields. - // only need to apply excluded fields - excluded.length && this.select('-' + excluded.join(' -')); - break; - } - - return seen = excluded = selected = keys = fields = null; - - function analyzeSchema (schema, prefix) { - prefix || (prefix = ''); - - // avoid recursion - if (~seen.indexOf(schema)) return; - seen.push(schema); - - schema.eachPath(function (path, type) { - if (prefix) path = prefix + '.' + path; - - analyzePath(path, type); - - // array of subdocs? - if (type.schema) { - analyzeSchema(type.schema, path); - } - - }); - } - - function analyzePath (path, type) { - if ('boolean' != typeof type.selected) return; - - var plusPath = '+' + path; - if (fields && plusPath in fields) { - // forced inclusion - delete fields[plusPath]; - - // if there are other fields being included, add this one - // if no other included fields, leave this out (implied inclusion) - if (false === exclude && keys.length > 1 && !~keys.indexOf(path)) { - fields[path] = 1; - } - - return - }; - - // check for parent exclusions - var root = path.split('.')[0]; - if (~excluded.indexOf(root)) return; - - ;(type.selected ? selected : excluded).push(path); - } -} - -/** - * Casts selected field arguments for field selection with mongo 2.2 - * - * query.select({ ids: { $elemMatch: { $in: [hexString] }}) - * - * @param {Object} fields - * @see https://github.com/LearnBoost/mongoose/issues/1091 - * @see http://docs.mongodb.org/manual/reference/projection/elemMatch/ - * @api private - */ - -Query.prototype._castFields = function _castFields (fields) { - var selected - , elemMatchKeys - , keys - , key - , out - , i - - if (fields) { - keys = Object.keys(fields); - elemMatchKeys = []; - i = keys.length; - - // collect $elemMatch args - while (i--) { - key = keys[i]; - if (fields[key].$elemMatch) { - selected || (selected = {}); - selected[key] = fields[key]; - elemMatchKeys.push(key); - } - } - } - - if (selected) { - // they passed $elemMatch, cast em - try { - out = this.cast(this.model, selected); - } catch (err) { - return err; - } - - // apply the casted field args - i = elemMatchKeys.length; - while (i--) { - key = elemMatchKeys[i]; - fields[key] = out[key]; - } - } - - return fields; -} - -/** - * Returns a Node.js 0.8 style [read stream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface. - * - * ####Example - * - * // follows the nodejs 0.8 stream api - * Thing.find({ name: /^hello/ }).stream().pipe(res) - * - * // manual streaming - * var stream = Thing.find({ name: /^hello/ }).stream(); - * - * stream.on('data', function (doc) { - * // do something with the mongoose document - * }).on('error', function (err) { - * // handle the error - * }).on('close', function () { - * // the stream is closed - * }); - * - * ####Valid options - * - * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. - * - * ####Example - * - * // JSON.stringify all documents before emitting - * var stream = Thing.find().stream({ transform: JSON.stringify }); - * stream.pipe(writeStream); - * - * @return {QueryStream} - * @param {Object} [options] - * @see QueryStream - * @api public - */ - -Query.prototype.stream = function stream (opts) { - return new QueryStream(this, opts); -} - -// the rest of these are basically to support older Mongoose syntax with mquery - -/** - * _DEPRECATED_ Alias of `maxScan` - * - * @deprecated - * @see maxScan #query_Query-maxScan - * @method maxscan - * @memberOf Query - */ - -Query.prototype.maxscan = Query.base.maxScan; - -/** - * Sets the tailable option (for use with capped collections). - * - * ####Example - * - * query.tailable() // true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} bool defaults to true - * @see tailable http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/ - * @api public - */ - -Query.prototype.tailable = function (val, opts) { - // we need to support the tailable({ awaitdata : true }) as well as the - // tailable(true, {awaitdata :true}) syntax that mquery does not support - if (val && val.constructor.name == 'Object') { - opts = val; - val = true; - } - - if (val === undefined) { - val = true; - } - - if (opts && opts.awaitdata) this.options.awaitdata = true; - return Query.base.tailable.call(this, val); -} - -/** - * Declares an intersects query for `geometry()`. - * - * ####Example - * - * query.where('path').intersects().geometry({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * query.where('path').intersects({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * ####NOTE: - * - * **MUST** be used after `where()`. - * - * ####NOTE: - * - * In Mongoose 3.7, `intersects` changed from a getter to a function. If you need the old syntax, use [this](https://github.com/ebensing/mongoose-within). - * - * @method intersects - * @memberOf Query - * @param {Object} [arg] - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see geoIntersects http://docs.mongodb.org/manual/reference/operator/geoIntersects/ - * @api public - */ - -/** - * Specifies a `$geometry` condition - * - * ####Example - * - * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] - * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - * - * // or - * var polyB = [[ 0, 0 ], [ 1, 1 ]] - * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - * - * // or - * var polyC = [ 0, 0 ] - * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - * - * // or - * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - * - * The argument is assigned to the most recent path passed to `where()`. - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * @method geometry - * @memberOf Query - * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. - * @return {Query} this - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * Specifies a `$near` or `$nearSphere` condition - * - * These operators return documents sorted by distance. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10] }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); - * query.near('loc', { center: [10, 10], maxDistance: 5 }); - * - * @method near - * @memberOf Query - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/*! - * Overwriting mquery is needed to support a couple different near() forms found in older - * versions of mongoose - * near([1,1]) - * near(1,1) - * near(field, [1,2]) - * near(field, 1, 2) - * In addition to all of the normal forms supported by mquery - */ - -Query.prototype.near = function () { - var params = []; - var sphere = this._mongooseOptions.nearSphere; - - // TODO refactor - - if (arguments.length === 1) { - if (Array.isArray(arguments[0])) { - params.push({ center: arguments[0], spherical: sphere }); - } else if ('string' == typeof arguments[0]) { - // just passing a path - params.push(arguments[0]); - } else if (utils.isObject(arguments[0])) { - if ('boolean' != typeof arguments[0].spherical) { - arguments[0].spherical = sphere; - } - params.push(arguments[0]); - } else { - throw new TypeError('invalid argument'); - } - } else if (arguments.length === 2) { - if ('number' == typeof arguments[0] && 'number' == typeof arguments[1]) { - params.push({ center: [arguments[0], arguments[1]], spherical: sphere}); - } else if ('string' == typeof arguments[0] && Array.isArray(arguments[1])) { - params.push(arguments[0]); - params.push({ center: arguments[1], spherical: sphere }); - } else if ('string' == typeof arguments[0] && utils.isObject(arguments[1])) { - params.push(arguments[0]); - if ('boolean' != typeof arguments[1].spherical) { - arguments[1].spherical = sphere; - } - params.push(arguments[1]); - } else { - throw new TypeError('invalid argument'); - } - } else if (arguments.length === 3) { - if ('string' == typeof arguments[0] && 'number' == typeof arguments[1] - && 'number' == typeof arguments[2]) { - params.push(arguments[0]); - params.push({ center: [arguments[1], arguments[2]], spherical: sphere }); - } else { - throw new TypeError('invalid argument'); - } - } else { - throw new TypeError('invalid argument'); - } - - return Query.base.near.apply(this, params); -} - -/** - * _DEPRECATED_ Specifies a `$nearSphere` condition - * - * ####Example - * - * query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); - * - * **Deprecated.** Use `query.near()` instead with the `spherical` option set to `true`. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10], spherical: true }); - * - * @deprecated - * @see near() #query_Query-near - * @see $near http://docs.mongodb.org/manual/reference/operator/near/ - * @see $nearSphere http://docs.mongodb.org/manual/reference/operator/nearSphere/ - * @see $maxDistance http://docs.mongodb.org/manual/reference/operator/maxDistance/ - */ - -Query.prototype.nearSphere = function () { - this._mongooseOptions.nearSphere = true; - this.near.apply(this, arguments); - return this; -} - -/** - * Specifies a $polygon condition - * - * ####Example - * - * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) - * query.polygon('loc', [10,20], [13, 25], [7,15]) - * - * @method polygon - * @memberOf Query - * @param {String|Array} [path] - * @param {Array|Object} [coordinatePairs...] - * @return {Query} this - * @see $polygon http://docs.mongodb.org/manual/reference/operator/polygon/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * Specifies a $box condition - * - * ####Example - * - * var lowerLeft = [40.73083, -73.99756] - * var upperRight= [40.741404, -73.988135] - * - * query.where('loc').within().box(lowerLeft, upperRight) - * query.box({ ll : lowerLeft, ur : upperRight }) - * - * @method box - * @memberOf Query - * @see $box http://docs.mongodb.org/manual/reference/operator/box/ - * @see within() Query#within #query_Query-within - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @param {Object} val - * @param [Array] Upper Right Coords - * @return {Query} this - * @api public - */ - -/*! - * this is needed to support the mongoose syntax of: - * box(field, { ll : [x,y], ur : [x2,y2] }) - * box({ ll : [x,y], ur : [x2,y2] }) - */ - -Query.prototype.box = function (ll, ur) { - if (!Array.isArray(ll) && utils.isObject(ll)) { - ur = ll.ur; - ll = ll.ll; - } - return Query.base.box.call(this, ll, ur); -} - -/** - * Specifies a $center or $centerSphere condition. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * // spherical calculations - * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * // alternatively - * query.circle('loc', area); - * - * New in 3.7.0 - * - * @method circle - * @memberOf Query - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see $center http://docs.mongodb.org/manual/reference/operator/center/ - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @see $geoWithin http://docs.mongodb.org/manual/reference/operator/within/ - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -/** - * _DEPRECATED_ Alias for [circle](#query_Query-circle) - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * @deprecated - * @method center - * @memberOf Query - * @api public - */ - -Query.prototype.center = Query.base.circle; - -/** - * _DEPRECATED_ Specifies a $centerSphere condition - * - * **Deprecated.** Use [circle](#query_Query-circle) instead. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10 }; - * query.where('loc').within().centerSphere(area); - * - * @deprecated - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $centerSphere http://docs.mongodb.org/manual/reference/operator/centerSphere/ - * @api public - */ - -Query.prototype.centerSphere = function () { - if (arguments[0] && arguments[0].constructor.name == 'Object') { - arguments[0].spherical = true; - } - - if (arguments[1] && arguments[1].constructor.name == 'Object') { - arguments[1].spherical = true; - } - - Query.base.circle.apply(this, arguments); -} - -/** - * Determines if query fields are inclusive - * - * @return {Boolean} bool defaults to true - * @api private - */ - -Query.prototype._selectedInclusively = Query.prototype.selectedInclusively; - -/*! - * Remove from public api for 3.8 - */ - -Query.prototype.selected = -Query.prototype.selectedInclusively = -Query.prototype.selectedExclusively = undefined; - -/*! - * Export - */ - -module.exports = Query; diff --git a/node_modules/mongoose/lib/queryhelpers.js b/node_modules/mongoose/lib/queryhelpers.js deleted file mode 100644 index d382dd6bc..000000000 --- a/node_modules/mongoose/lib/queryhelpers.js +++ /dev/null @@ -1,79 +0,0 @@ - -/*! - * Module dependencies - */ - -var utils = require('./utils') - -/*! - * Prepare a set of path options for query population. - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - -exports.preparePopulationOptions = function preparePopulationOptions (query, options) { - var pop = utils.object.vals(query.options.populate); - - // lean options should trickle through all queries - if (options.lean) pop.forEach(makeLean); - - return pop; -} - -/*! - * Prepare a set of path options for query population. This is the MongooseQuery - * version - * - * @param {Query} query - * @param {Object} options - * @return {Array} - */ - -exports.preparePopulationOptionsMQ = function preparePopulationOptionsMQ (query, options) { - var pop = utils.object.vals(query._mongooseOptions.populate); - - // lean options should trickle through all queries - if (options.lean) pop.forEach(makeLean); - - return pop; -} - -/*! - * If the document is a mapped discriminator type, it returns a model instance for that type, otherwise, - * it returns an instance of the given model. - * - * @param {Model} model - * @param {Object} doc - * @param {Object} fields - * - * @return {Model} - */ -exports.createModel = function createModel(model, doc, fields) { - var discriminatorMapping = model.schema - ? model.schema.discriminatorMapping - : null; - - var key = discriminatorMapping && discriminatorMapping.isRoot - ? discriminatorMapping.key - : null; - - if (key && doc[key] && model.discriminators && model.discriminators[doc[key]]) { - return new model.discriminators[doc[key]](undefined, fields, true); - } - - return new model(undefined, fields, true); -} - -/*! - * Set each path query option to lean - * - * @param {Object} option - */ - -function makeLean (option) { - option.options || (option.options = {}); - option.options.lean = true; -} - diff --git a/node_modules/mongoose/lib/querystream.js b/node_modules/mongoose/lib/querystream.js deleted file mode 100644 index f828d1c52..000000000 --- a/node_modules/mongoose/lib/querystream.js +++ /dev/null @@ -1,337 +0,0 @@ - -/*! - * Module dependencies. - */ - -var Stream = require('stream').Stream -var utils = require('./utils') -var helpers = require('./queryhelpers') -var K = function(k){ return k } - -/** - * Provides a Node.js 0.8 style [ReadStream](http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream) interface for Queries. - * - * var stream = Model.find().stream(); - * - * stream.on('data', function (doc) { - * // do something with the mongoose document - * }).on('error', function (err) { - * // handle the error - * }).on('close', function () { - * // the stream is closed - * }); - * - * - * The stream interface allows us to simply "plug-in" to other _Node.js 0.8_ style write streams. - * - * Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream); - * - * ####Valid options - * - * - `transform`: optional function which accepts a mongoose document. The return value of the function will be emitted on `data`. - * - * ####Example - * - * // JSON.stringify all documents before emitting - * var stream = Thing.find().stream({ transform: JSON.stringify }); - * stream.pipe(writeStream); - * - * _NOTE: plugging into an HTTP response will *not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary._ - * - * _NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work._ - * - * @param {Query} query - * @param {Object} [options] - * @inherits NodeJS Stream http://nodejs.org/docs/v0.8.21/api/stream.html#stream_readable_stream - * @event `data`: emits a single Mongoose document - * @event `error`: emits when an error occurs during streaming. This will emit _before_ the `close` event. - * @event `close`: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually `destroy`ed. After this event, no more events are emitted. - * @api public - */ - -function QueryStream (query, options) { - Stream.call(this); - - this.query = query; - this.readable = true; - this.paused = false; - this._cursor = null; - this._destroyed = null; - this._fields = null; - this._buffer = null; - this._inline = T_INIT; - this._running = false; - this._transform = options && 'function' == typeof options.transform - ? options.transform - : K; - - // give time to hook up events - var self = this; - process.nextTick(function () { - self._init(); - }); -} - -/*! - * Inherit from Stream - */ - -QueryStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - * - * @property readable - * @api public - */ - -QueryStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - * - * @property paused - * @api public - */ - -QueryStream.prototype.paused; - -// trampoline flags -var T_INIT = 0; -var T_IDLE = 1; -var T_CONT = 2; - -/** - * Initializes the query. - * - * @api private - */ - -QueryStream.prototype._init = function () { - if (this._destroyed) return; - - var query = this.query - , model = query.model - , options = query._optionsForExec(model) - , self = this - - try { - query.cast(model); - } catch (err) { - return self.destroy(err); - } - - self._fields = utils.clone(query._fields); - options.fields = query._castFields(self._fields); - - model.collection.find(query._conditions, options, function (err, cursor) { - if (err) return self.destroy(err); - self._cursor = cursor; - self._next(); - }); -} - -/** - * Trampoline for pulling the next doc from cursor. - * - * @see QueryStream#__next #querystream_QueryStream-__next - * @api private - */ - -QueryStream.prototype._next = function _next () { - if (this.paused || this._destroyed) { - return this._running = false; - } - - this._running = true; - - if (this._buffer && this._buffer.length) { - var arg; - while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) { - this._onNextObject.apply(this, arg); - } - } - - // avoid stack overflows with large result sets. - // trampoline instead of recursion. - while (this.__next()) {} -} - -/** - * Pulls the next doc from the cursor. - * - * @see QueryStream#_next #querystream_QueryStream-_next - * @api private - */ - -QueryStream.prototype.__next = function () { - if (this.paused || this._destroyed) - return this._running = false; - - var self = this; - self._inline = T_INIT; - - self._cursor.nextObject(function cursorcb (err, doc) { - self._onNextObject(err, doc); - }); - - // if onNextObject() was already called in this tick - // return ourselves to the trampoline. - if (T_CONT === this._inline) { - return true; - } else { - // onNextObject() hasn't fired yet. tell onNextObject - // that its ok to call _next b/c we are not within - // the trampoline anymore. - this._inline = T_IDLE; - } -} - -/** - * Transforms raw `doc`s returned from the cursor into a model instance. - * - * @param {Error|null} err - * @param {Object} doc - * @api private - */ - -QueryStream.prototype._onNextObject = function _onNextObject (err, doc) { - if (this._destroyed) return; - - if (this.paused) { - this._buffer || (this._buffer = []); - this._buffer.push([err, doc]); - return this._running = false; - } - - if (err) return this.destroy(err); - - // when doc is null we hit the end of the cursor - if (!doc) { - this.emit('end'); - return this.destroy(); - } - - var opts = this.query._mongooseOptions; - - if (!opts.populate) { - return true === opts.lean - ? emit(this, doc) - : createAndEmit(this, doc); - } - - var self = this; - var pop = helpers.preparePopulationOptionsMQ(self.query, self.query._mongooseOptions); - - self.query.model.populate(doc, pop, function (err, doc) { - if (err) return self.destroy(err); - return true === opts.lean - ? emit(self, doc) - : createAndEmit(self, doc); - }) -} - -function createAndEmit (self, doc) { - var instance = helpers.createModel(self.query.model, doc, self._fields); - - instance.init(doc, function (err) { - if (err) return self.destroy(err); - emit(self, instance); - }); -} - -/*! - * Emit a data event and manage the trampoline state - */ - -function emit (self, doc) { - self.emit('data', self._transform(doc)); - - // trampoline management - if (T_IDLE === self._inline) { - // no longer in trampoline. restart it. - self._next(); - } else { - // in a trampoline. tell __next that its - // ok to continue jumping. - self._inline = T_CONT; - } -} - -/** - * Pauses this stream. - * - * @api public - */ - -QueryStream.prototype.pause = function () { - this.paused = true; -} - -/** - * Resumes this stream. - * - * @api public - */ - -QueryStream.prototype.resume = function () { - this.paused = false; - - if (!this._cursor) { - // cannot start if not initialized - return; - } - - // are we within the trampoline? - if (T_INIT === this._inline) { - return; - } - - if (!this._running) { - // outside QueryStream control, need manual restart - return this._next(); - } -} - -/** - * Destroys the stream, closing the underlying cursor. No more events will be emitted. - * - * @param {Error} [err] - * @api public - */ - -QueryStream.prototype.destroy = function (err) { - if (this._destroyed) return; - this._destroyed = true; - this._running = false; - this.readable = false; - - if (this._cursor) { - this._cursor.close(); - } - - if (err) { - this.emit('error', err); - } - - this.emit('close'); -} - -/** - * Pipes this query stream into another stream. This method is inherited from NodeJS Streams. - * - * ####Example: - * - * query.stream().pipe(writeStream [, options]) - * - * @method pipe - * @memberOf QueryStream - * @see NodeJS http://nodejs.org/api/stream.html - * @api public - */ - -/*! - * Module exports - */ - -module.exports = exports = QueryStream; diff --git a/node_modules/mongoose/lib/schema.js b/node_modules/mongoose/lib/schema.js deleted file mode 100644 index 67c5f7cb2..000000000 --- a/node_modules/mongoose/lib/schema.js +++ /dev/null @@ -1,896 +0,0 @@ -/*! - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , VirtualType = require('./virtualtype') - , utils = require('./utils') - , mquery = require('mquery') - , Query - , Types - -/** - * Schema constructor. - * - * ####Example: - * - * var child = new Schema({ name: String }); - * var schema = new Schema({ name: String, age: Number, children: [child] }); - * var Tree = mongoose.model('Tree', schema); - * - * // setting schema options - * new Schema({ name: String }, { _id: false, autoIndex: false }) - * - * ####Options: - * - * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to true - * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true - * - [capped](/docs/guide.html#capped): bool - defaults to false - * - [collection](/docs/guide.html#collection): string - no default - * - [id](/docs/guide.html#id): bool - defaults to true - * - [_id](/docs/guide.html#_id): bool - defaults to true - * - `minimize`: bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true - * - [read](/docs/guide.html#read): string - * - [safe](/docs/guide.html#safe): bool - defaults to true. - * - [shardKey](/docs/guide.html#shardKey): bool - defaults to `null` - * - [strict](/docs/guide.html#strict): bool - defaults to true - * - [toJSON](/docs/guide.html#toJSON) - object - no default - * - [toObject](/docs/guide.html#toObject) - object - no default - * - [versionKey](/docs/guide.html#versionKey): bool - defaults to "__v" - * - * ####Note: - * - * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into is parent._ - * - * @param {Object} definition - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `init`: Emitted after the schema is compiled into a `Model`. - * @api public - */ - -function Schema (obj, options) { - if (!(this instanceof Schema)) - return new Schema(obj, options); - - this.paths = {}; - this.subpaths = {}; - this.virtuals = {}; - this.nested = {}; - this.inherits = {}; - this.callQueue = []; - this._indexes = []; - this.methods = {}; - this.statics = {}; - this.tree = {}; - this._requiredpaths = undefined; - this.discriminatorMapping = undefined; - this._indexedpaths = undefined; - - this.options = this.defaultOptions(options); - - // build paths - if (obj) { - this.add(obj); - } - - // ensure the documents get an auto _id unless disabled - var auto_id = !this.paths['_id'] && (!this.options.noId && this.options._id); - if (auto_id) { - this.add({ _id: {type: Schema.ObjectId, auto: true} }); - } - - // ensure the documents receive an id getter unless disabled - var autoid = !this.paths['id'] && (!this.options.noVirtualId && this.options.id); - if (autoid) { - this.virtual('id').get(idGetter); - } -} - -/*! - * Returns this documents _id cast to a string. - */ - -function idGetter () { - if (this.$__._id) { - return this.$__._id; - } - - return this.$__._id = null == this._id - ? null - : String(this._id); -} - -/*! - * Inherit from EventEmitter. - */ - -Schema.prototype.__proto__ = EventEmitter.prototype; - -/** - * Schema as flat paths - * - * ####Example: - * { - * '_id' : SchemaType, - * , 'nested.key' : SchemaType, - * } - * - * @api private - * @property paths - */ - -Schema.prototype.paths; - -/** - * Schema as a tree - * - * ####Example: - * { - * '_id' : ObjectId - * , 'nested' : { - * 'key' : String - * } - * } - * - * @api private - * @property tree - */ - -Schema.prototype.tree; - -/** - * Returns default options for this schema, merged with `options`. - * - * @param {Object} options - * @return {Object} - * @api private - */ - -Schema.prototype.defaultOptions = function (options) { - if (options && false === options.safe) { - options.safe = { w: 0 }; - } - - if (options && options.safe && 0 === options.safe.w) { - // if you turn off safe writes, then versioning goes off as well - options.versionKey = false; - } - - options = utils.options({ - strict: true - , bufferCommands: true - , capped: false // { size, max, autoIndexId } - , versionKey: '__v' - , discriminatorKey: '__t' - , minimize: true - , autoIndex: true - , shardKey: null - , read: null - // the following are only applied at construction time - , noId: false // deprecated, use { _id: false } - , _id: true - , noVirtualId: false // deprecated, use { id: false } - , id: true -// , pluralization: true // only set this to override the global option - }, options); - - if (options.read) { - options.read = mquery.utils.readPref(options.read); - } - - return options; -} - -/** - * Adds key path / schema type pairs to this schema. - * - * ####Example: - * - * var ToySchema = new Schema; - * ToySchema.add({ name: 'string', color: 'string', price: 'number' }); - * - * @param {Object} obj - * @param {String} prefix - * @api public - */ - -Schema.prototype.add = function add (obj, prefix) { - prefix = prefix || ''; - var keys = Object.keys(obj); - - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - - if (null == obj[key]) { - throw new TypeError('Invalid value for schema path `'+ prefix + key +'`'); - } - - if (utils.isObject(obj[key]) && (!obj[key].constructor || 'Object' == obj[key].constructor.name) && (!obj[key].type || obj[key].type.type)) { - if (Object.keys(obj[key]).length) { - // nested object { last: { name: String }} - this.nested[prefix + key] = true; - this.add(obj[key], prefix + key + '.'); - } else { - this.path(prefix + key, obj[key]); // mixed type - } - } else { - this.path(prefix + key, obj[key]); - } - } -}; - -/** - * Reserved document keys. - * - * Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error. - * - * on, emit, _events, db, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject - * - * _NOTE:_ Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on. - * - * var schema = new Schema(..); - * schema.methods.init = function () {} // potentially breaking - */ - -Schema.reserved = Object.create(null); -var reserved = Schema.reserved; -reserved.on = -reserved.db = -reserved.init = -reserved.isNew = -reserved.errors = -reserved.schema = -reserved.options = -reserved.modelName = -reserved.collection = -reserved.toObject = -reserved.emit = // EventEmitter -reserved._events = // EventEmitter -reserved._pres = reserved._posts = 1 // hooks.js - -/** - * Gets/sets schema paths. - * - * Sets a path (if arity 2) - * Gets a path (if arity 1) - * - * ####Example - * - * schema.path('name') // returns a SchemaType - * schema.path('name', Number) // changes the schemaType of `name` to Number - * - * @param {String} path - * @param {Object} constructor - * @api public - */ - -Schema.prototype.path = function (path, obj) { - if (obj == undefined) { - if (this.paths[path]) return this.paths[path]; - if (this.subpaths[path]) return this.subpaths[path]; - - // subpaths? - return /\.\d+\.?.*$/.test(path) - ? getPositionalPath(this, path) - : undefined; - } - - // some path names conflict with document methods - if (reserved[path]) { - throw new Error("`" + path + "` may not be used as a schema pathname"); - } - - // update the tree - var subpaths = path.split(/\./) - , last = subpaths.pop() - , branch = this.tree; - - subpaths.forEach(function(sub, i) { - if (!branch[sub]) branch[sub] = {}; - if ('object' != typeof branch[sub]) { - var msg = 'Cannot set nested path `' + path + '`. ' - + 'Parent path `' - + subpaths.slice(0, i).concat([sub]).join('.') - + '` already set to type ' + branch[sub].name - + '.'; - throw new Error(msg); - } - branch = branch[sub]; - }); - - branch[last] = utils.clone(obj); - - this.paths[path] = Schema.interpretAsType(path, obj); - return this; -}; - -/** - * Converts type arguments into Mongoose Types. - * - * @param {String} path - * @param {Object} obj constructor - * @api private - */ - -Schema.interpretAsType = function (path, obj) { - if (obj.constructor && obj.constructor.name != 'Object') - obj = { type: obj }; - - // Get the type making sure to allow keys named "type" - // and default to mixed if not specified. - // { type: { type: String, default: 'freshcut' } } - var type = obj.type && !obj.type.type - ? obj.type - : {}; - - if ('Object' == type.constructor.name || 'mixed' == type) { - return new Types.Mixed(path, obj); - } - - if (Array.isArray(type) || Array == type || 'array' == type) { - // if it was specified through { type } look for `cast` - var cast = (Array == type || 'array' == type) - ? obj.cast - : type[0]; - - if (cast instanceof Schema) { - return new Types.DocumentArray(path, cast, obj); - } - - if ('string' == typeof cast) { - cast = Types[cast.charAt(0).toUpperCase() + cast.substring(1)]; - } else if (cast && (!cast.type || cast.type.type) - && 'Object' == cast.constructor.name - && Object.keys(cast).length) { - return new Types.DocumentArray(path, new Schema(cast), obj); - } - - return new Types.Array(path, cast || Types.Mixed, obj); - } - - var name = 'string' == typeof type - ? type - : type.name; - - if (name) { - name = name.charAt(0).toUpperCase() + name.substring(1); - } - - if (undefined == Types[name]) { - throw new TypeError('Undefined type at `' + path + - '`\n Did you try nesting Schemas? ' + - 'You can only nest using refs or arrays.'); - } - - return new Types[name](path, obj); -}; - -/** - * Iterates the schemas paths similar to Array#forEach. - * - * The callback is passed the pathname and schemaType as arguments on each iteration. - * - * @param {Function} fn callback function - * @return {Schema} this - * @api public - */ - -Schema.prototype.eachPath = function (fn) { - var keys = Object.keys(this.paths) - , len = keys.length; - - for (var i = 0; i < len; ++i) { - fn(keys[i], this.paths[keys[i]]); - } - - return this; -}; - -/** - * Returns an Array of path strings that are required by this schema. - * - * @api public - * @return {Array} - */ - -Schema.prototype.requiredPaths = function requiredPaths () { - if (this._requiredpaths) return this._requiredpaths; - - var paths = Object.keys(this.paths) - , i = paths.length - , ret = []; - - while (i--) { - var path = paths[i]; - if (this.paths[path].isRequired) ret.push(path); - } - - return this._requiredpaths = ret; -} - -/** - * Returns indexes from fields and schema-level indexes (cached). - * - * @api private - * @return {Array} - */ - -Schema.prototype.indexedPaths = function indexedPaths () { - if (this._indexedpaths) return this._indexedpaths; - - return this._indexedpaths = this.indexes(); -} - -/** - * Returns the pathType of `path` for this schema. - * - * Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path. - * - * @param {String} path - * @return {String} - * @api public - */ - -Schema.prototype.pathType = function (path) { - if (path in this.paths) return 'real'; - if (path in this.virtuals) return 'virtual'; - if (path in this.nested) return 'nested'; - if (path in this.subpaths) return 'real'; - - if (/\.\d+\.|\.\d+$/.test(path) && getPositionalPath(this, path)) { - return 'real'; - } else { - return 'adhocOrUndefined' - } -}; - -/*! - * ignore - */ - -function getPositionalPath (self, path) { - var subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean); - if (subpaths.length < 2) { - return self.paths[subpaths[0]]; - } - - var val = self.path(subpaths[0]); - if (!val) return val; - - var last = subpaths.length - 1 - , subpath - , i = 1; - - for (; i < subpaths.length; ++i) { - subpath = subpaths[i]; - - if (i === last && val && !val.schema && !/\D/.test(subpath)) { - if (val instanceof Types.Array) { - // StringSchema, NumberSchema, etc - val = val.caster; - } else { - val = undefined; - } - break; - } - - // ignore if its just a position segment: path.0.subpath - if (!/\D/.test(subpath)) continue; - - if (!(val && val.schema)) { - val = undefined; - break; - } - - val = val.schema.path(subpath); - } - - return self.subpaths[path] = val; -} - -/** - * Adds a method call to the queue. - * - * @param {String} name name of the document method to call later - * @param {Array} args arguments to pass to the method - * @api private - */ - -Schema.prototype.queue = function(name, args){ - this.callQueue.push([name, args]); - return this; -}; - -/** - * Defines a pre hook for the document. - * - * ####Example - * - * var toySchema = new Schema(..); - * - * toySchema.pre('save', function (next) { - * if (!this.created) this.created = new Date; - * next(); - * }) - * - * toySchema.pre('validate', function (next) { - * if (this.name != 'Woody') this.name = 'Woody'; - * next(); - * }) - * - * @param {String} method - * @param {Function} callback - * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 - * @api public - */ - -Schema.prototype.pre = function(){ - return this.queue('pre', arguments); -}; - -/** - * Defines a post for the document - * - * Post hooks fire `on` the event emitted from document instances of Models compiled from this schema. - * - * var schema = new Schema(..); - * schema.post('save', function (doc) { - * console.log('this fired after a document was saved'); - * }); - * - * var Model = mongoose.model('Model', schema); - * - * var m = new Model(..); - * m.save(function (err) { - * console.log('this fires after the `post` hook'); - * }); - * - * @param {String} method name of the method to hook - * @param {Function} fn callback - * @see hooks.js https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3 - * @api public - */ - -Schema.prototype.post = function(method, fn){ - return this.queue('on', arguments); -}; - -/** - * Registers a plugin for this schema. - * - * @param {Function} plugin callback - * @param {Object} opts - * @see plugins - * @api public - */ - -Schema.prototype.plugin = function (fn, opts) { - fn(this, opts); - return this; -}; - -/** - * Adds an instance method to documents constructed from Models compiled from this schema. - * - * ####Example - * - * var schema = kittySchema = new Schema(..); - * - * schema.method('meow', function () { - * console.log('meeeeeoooooooooooow'); - * }) - * - * var Kitty = mongoose.model('Kitty', schema); - * - * var fizz = new Kitty; - * fizz.meow(); // meeeeeooooooooooooow - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. - * - * schema.method({ - * purr: function () {} - * , scratch: function () {} - * }); - * - * // later - * fizz.purr(); - * fizz.scratch(); - * - * @param {String|Object} method name - * @param {Function} [fn] - * @api public - */ - -Schema.prototype.method = function (name, fn) { - if ('string' != typeof name) - for (var i in name) - this.methods[i] = name[i]; - else - this.methods[name] = fn; - return this; -}; - -/** - * Adds static "class" methods to Models compiled from this schema. - * - * ####Example - * - * var schema = new Schema(..); - * schema.static('findByName', function (name, callback) { - * return this.find({ name: name }, callback); - * }); - * - * var Drink = mongoose.model('Drink', schema); - * Drink.findByName('sanpellegrino', function (err, drinks) { - * // - * }); - * - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics. - * - * @param {String} name - * @param {Function} fn - * @api public - */ - -Schema.prototype.static = function(name, fn) { - if ('string' != typeof name) - for (var i in name) - this.statics[i] = name[i]; - else - this.statics[name] = fn; - return this; -}; - -/** - * Defines an index (most likely compound) for this schema. - * - * ####Example - * - * schema.index({ first: 1, last: -1 }) - * - * @param {Object} fields - * @param {Object} [options] - * @api public - */ - -Schema.prototype.index = function (fields, options) { - options || (options = {}); - - if (options.expires) - utils.expires(options); - - this._indexes.push([fields, options]); - return this; -}; - -/** - * Sets/gets a schema option. - * - * @param {String} key option name - * @param {Object} [value] if not passed, the current option value is returned - * @api public - */ - -Schema.prototype.set = function (key, value, _tags) { - if (1 === arguments.length) { - return this.options[key]; - } - - switch (key) { - case 'read': - this.options[key] = mquery.utils.readPref(value, _tags) - break; - case 'safe': - this.options[key] = false === value - ? { w: 0 } - : value - break; - default: - this.options[key] = value; - } - - return this; -} - -/** - * Gets a schema option. - * - * @param {String} key option name - * @api public - */ - -Schema.prototype.get = function (key) { - return this.options[key]; -} - -/** - * The allowed index types - * - * @static indexTypes - * @receiver Schema - * @api public - */ - -var indexTypes = '2d 2dsphere hashed text'.split(' '); - -Object.defineProperty(Schema, 'indexTypes', { - get: function () { return indexTypes } - , set: function () { throw new Error('Cannot overwrite Schema.indexTypes') } -}) - -/** - * Compiles indexes from fields and schema-level indexes - * - * @api public - */ - -Schema.prototype.indexes = function () { - 'use strict'; - - var indexes = [] - , seenSchemas = [] - collectIndexes(this); - return indexes; - - function collectIndexes (schema, prefix) { - if (~seenSchemas.indexOf(schema)) return; - seenSchemas.push(schema); - - prefix = prefix || ''; - - var key, path, index, field, isObject, options, type; - var keys = Object.keys(schema.paths); - - for (var i = 0; i < keys.length; ++i) { - key = keys[i]; - path = schema.paths[key]; - - if (path instanceof Types.DocumentArray) { - collectIndexes(path.schema, key + '.'); - } else { - index = path._index; - - if (false !== index && null != index) { - field = {}; - isObject = utils.isObject(index); - options = isObject ? index : {}; - type = 'string' == typeof index ? index : - isObject ? index.type : - false; - - if (type && ~Schema.indexTypes.indexOf(type)) { - field[prefix + key] = type; - } else { - field[prefix + key] = 1; - } - - delete options.type; - if (!('background' in options)) { - options.background = true; - } - - indexes.push([field, options]); - } - } - } - - if (prefix) { - fixSubIndexPaths(schema, prefix); - } else { - schema._indexes.forEach(function (index) { - if (!('background' in index[1])) index[1].background = true; - }); - indexes = indexes.concat(schema._indexes); - } - } - - /*! - * Checks for indexes added to subdocs using Schema.index(). - * These indexes need their paths prefixed properly. - * - * schema._indexes = [ [indexObj, options], [indexObj, options] ..] - */ - - function fixSubIndexPaths (schema, prefix) { - var subindexes = schema._indexes - , len = subindexes.length - , indexObj - , newindex - , klen - , keys - , key - , i = 0 - , j - - for (i = 0; i < len; ++i) { - indexObj = subindexes[i][0]; - keys = Object.keys(indexObj); - klen = keys.length; - newindex = {}; - - // use forward iteration, order matters - for (j = 0; j < klen; ++j) { - key = keys[j]; - newindex[prefix + key] = indexObj[key]; - } - - indexes.push([newindex, subindexes[i][1]]); - } - } -} - -/** - * Creates a virtual type with the given name. - * - * @param {String} name - * @param {Object} [options] - * @return {VirtualType} - */ - -Schema.prototype.virtual = function (name, options) { - var virtuals = this.virtuals; - var parts = name.split('.'); - return virtuals[name] = parts.reduce(function (mem, part, i) { - mem[part] || (mem[part] = (i === parts.length-1) - ? new VirtualType(options, name) - : {}); - return mem[part]; - }, this.tree); -}; - -/** - * Returns the virtual type with the given `name`. - * - * @param {String} name - * @return {VirtualType} - */ - -Schema.prototype.virtualpath = function (name) { - return this.virtuals[name]; -}; - -/*! - * Module exports. - */ - -module.exports = exports = Schema; - -// require down here because of reference issues - -/** - * The various built-in Mongoose Schema Types. - * - * ####Example: - * - * var mongoose = require('mongoose'); - * var ObjectId = mongoose.Schema.Types.ObjectId; - * - * ####Types: - * - * - [String](#schema-string-js) - * - [Number](#schema-number-js) - * - [Boolean](#schema-boolean-js) | Bool - * - [Array](#schema-array-js) - * - [Buffer](#schema-buffer-js) - * - [Date](#schema-date-js) - * - [ObjectId](#schema-objectid-js) | Oid - * - [Mixed](#schema-mixed-js) - * - * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema. - * - * var Mixed = mongoose.Schema.Types.Mixed; - * new mongoose.Schema({ _user: Mixed }) - * - * @api public - */ - -Schema.Types = require('./schema/index'); - -/*! - * ignore - */ - -Types = Schema.Types; -Query = require('./query'); -var ObjectId = exports.ObjectId = Types.ObjectId; - diff --git a/node_modules/mongoose/lib/schema/array.js b/node_modules/mongoose/lib/schema/array.js deleted file mode 100644 index ffed6c6b7..000000000 --- a/node_modules/mongoose/lib/schema/array.js +++ /dev/null @@ -1,363 +0,0 @@ -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , NumberSchema = require('./number') - , Types = { - Boolean: require('./boolean') - , Date: require('./date') - , Number: require('./number') - , String: require('./string') - , ObjectId: require('./objectid') - , Buffer: require('./buffer') - } - , MongooseArray = require('../types').Array - , EmbeddedDoc = require('../types').Embedded - , Mixed = require('./mixed') - , Query = require('../query') - , utils = require('../utils') - , isMongooseObject = utils.isMongooseObject - -/** - * Array SchemaType constructor - * - * @param {String} key - * @param {SchemaType} cast - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaArray (key, cast, options) { - if (cast) { - var castOptions = {}; - - if ('Object' === cast.constructor.name) { - if (cast.type) { - // support { type: Woot } - castOptions = utils.clone(cast); // do not alter user arguments - delete castOptions.type; - cast = cast.type; - } else { - cast = Mixed; - } - } - - // support { type: 'String' } - var name = 'string' == typeof cast - ? cast - : cast.name; - - var caster = name in Types - ? Types[name] - : cast; - - this.casterConstructor = caster; - this.caster = new caster(null, castOptions); - if (!(this.caster instanceof EmbeddedDoc)) { - this.caster.path = key; - } - } - - SchemaType.call(this, key, options); - - var self = this - , defaultArr - , fn; - - if (this.defaultValue) { - defaultArr = this.defaultValue; - fn = 'function' == typeof defaultArr; - } - - this.default(function(){ - var arr = fn ? defaultArr() : defaultArr || []; - return new MongooseArray(arr, self.path, this); - }); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaArray.prototype.__proto__ = SchemaType.prototype; - -/** - * Check required - * - * @param {Array} value - * @api private - */ - -SchemaArray.prototype.checkRequired = function (value) { - return !!(value && value.length); -}; - -/** - * Overrides the getters application for the population special-case - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - -SchemaArray.prototype.applyGetters = function (value, scope) { - if (this.caster.options && this.caster.options.ref) { - // means the object id was populated - return value; - } - - return SchemaType.prototype.applyGetters.call(this, value, scope); -}; - -/** - * Casts values for set(). - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -SchemaArray.prototype.cast = function (value, doc, init) { - if (Array.isArray(value)) { - - if (!value.length && doc) { - var indexes = doc.schema.indexedPaths(); - - for (var i = 0, l = indexes.length; i < l; ++i) { - var pathIndex = indexes[i][0][this.path]; - if ('2dsphere' === pathIndex || '2d' === pathIndex) { - return; - } - } - } - - if (!(value instanceof MongooseArray)) { - value = new MongooseArray(value, this.path, doc); - } - - if (this.caster) { - try { - for (var i = 0, l = value.length; i < l; i++) { - value[i] = this.caster.cast(value[i], doc, init); - } - } catch (e) { - // rethrow - throw new CastError(e.type, value, this.path); - } - } - - return value; - } else { - return this.cast([value], doc, init); - } -}; - -/** - * Casts values for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaArray.prototype.castForQuery = function ($conditional, value) { - var handler - , val; - - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - - if (!handler) { - throw new Error("Can't use " + $conditional + " with Array."); - } - - val = handler.call(this, value); - - } else { - - val = $conditional; - var proto = this.casterConstructor.prototype; - var method = proto.castForQuery || proto.cast; - var caster = this.caster; - - if (Array.isArray(val)) { - val = val.map(function (v) { - if (method) v = method.call(caster, v); - return isMongooseObject(v) - ? v.toObject() - : v; - }); - - } else if (method) { - val = method.call(caster, val); - } - } - - return val && isMongooseObject(val) - ? val.toObject() - : val; -}; - -/*! - * @ignore - * - * $atomic cast helpers - */ - -function castToNumber (val) { - return Types.Number.prototype.cast.call(this, val); -} - -function castArraysOfNumbers (arr, self) { - self || (self = this); - - arr.forEach(function (v, i) { - if (Array.isArray(v)) { - castArraysOfNumbers(v, self); - } else { - arr[i] = castToNumber.call(self, v); - } - }); -} - -function cast$near (val) { - if (Array.isArray(val)) { - castArraysOfNumbers(val, this); - return val; - } - - if (val && val.$geometry) { - return cast$geometry(val, this); - } - - return SchemaArray.prototype.castForQuery.call(this, val); -} - -function cast$geometry (val, self) { - switch (val.$geometry.type) { - case 'Polygon': - case 'LineString': - case 'Point': - castArraysOfNumbers(val.$geometry.coordinates, self); - break; - default: - // ignore unknowns - break; - } - - if (val.$maxDistance) { - val.$maxDistance = castToNumber.call(self, val.$maxDistance); - } - - return val; -} - -function cast$within (val) { - var self = this; - - if (val.$maxDistance) { - val.$maxDistance = castToNumber.call(self, val.$maxDistance); - } - - if (val.$box || val.$polygon) { - var type = val.$box ? '$box' : '$polygon'; - val[type].forEach(function (arr) { - if (!Array.isArray(arr)) { - var msg = 'Invalid $within $box argument. ' - + 'Expected an array, received ' + arr; - throw new TypeError(msg); - } - arr.forEach(function (v, i) { - arr[i] = castToNumber.call(this, v); - }); - }) - } else if (val.$center || val.$centerSphere) { - var type = val.$center ? '$center' : '$centerSphere'; - val[type].forEach(function (item, i) { - if (Array.isArray(item)) { - item.forEach(function (v, j) { - item[j] = castToNumber.call(this, v); - }); - } else { - val[type][i] = castToNumber.call(this, item); - } - }) - } else if (val.$geometry) { - cast$geometry(val, this); - } - - return val; -} - -function cast$all (val) { - if (!Array.isArray(val)) { - val = [val]; - } - - val = val.map(function (v) { - if (utils.isObject(v)) { - var o = {}; - o[this.path] = v; - var query = new Query(o); - query.cast(this.casterConstructor); - return query._conditions[this.path]; - } - return v; - }, this); - - return this.castForQuery(val); -} - -function cast$elemMatch (val) { - if (val.$in) { - val.$in = this.castForQuery('$in', val.$in); - return val; - } - - var query = new Query(val); - query.cast(this.casterConstructor); - return query._conditions; -} - -function cast$geoIntersects (val) { - var geo = val.$geometry; - if (!geo) return; - - cast$geometry(val, this); - return val; -} - -var handle = SchemaArray.prototype.$conditionalHandlers = {}; - -handle.$all = cast$all; -handle.$options = String; -handle.$elemMatch = cast$elemMatch; -handle.$geoIntersects = cast$geoIntersects; - -handle.$near = -handle.$nearSphere = cast$near; - -handle.$within = -handle.$geoWithin = cast$within; - -handle.$size = -handle.$maxDistance = castToNumber; - -handle.$regex = -handle.$ne = -handle.$in = -handle.$nin = -handle.$gt = -handle.$gte = -handle.$lt = -handle.$lte = SchemaArray.prototype.castForQuery; - -/*! - * Module exports. - */ - -module.exports = SchemaArray; diff --git a/node_modules/mongoose/lib/schema/boolean.js b/node_modules/mongoose/lib/schema/boolean.js deleted file mode 100644 index cc16b7a93..000000000 --- a/node_modules/mongoose/lib/schema/boolean.js +++ /dev/null @@ -1,92 +0,0 @@ -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype'); - -/** - * Boolean SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaBoolean (path, options) { - SchemaType.call(this, path, options); -}; - -/*! - * Inherits from SchemaType. - */ -SchemaBoolean.prototype.__proto__ = SchemaType.prototype; - -/** - * Required validator - * - * @api private - */ - -SchemaBoolean.prototype.checkRequired = function (value) { - return value === true || value === false; -}; - -/** - * Casts to boolean - * - * @param {Object} value - * @api private - */ - -SchemaBoolean.prototype.cast = function (value) { - if (null === value) return value; - if ('0' === value) return false; - if ('true' === value) return true; - if ('false' === value) return false; - return !! value; -} - -/*! - * ignore - */ - -function handleArray (val) { - var self = this; - return val.map(function (m) { - return self.cast(m); - }); -} - -SchemaBoolean.$conditionalHandlers = { - '$in': handleArray -} - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} val - * @api private - */ - -SchemaBoolean.prototype.castForQuery = function ($conditional, val) { - var handler; - if (2 === arguments.length) { - handler = SchemaBoolean.$conditionalHandlers[$conditional]; - - if (handler) { - return handler.call(this, val); - } - - return this.cast(val); - } - - return this.cast($conditional); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaBoolean; diff --git a/node_modules/mongoose/lib/schema/buffer.js b/node_modules/mongoose/lib/schema/buffer.js deleted file mode 100644 index dbaf1939a..000000000 --- a/node_modules/mongoose/lib/schema/buffer.js +++ /dev/null @@ -1,168 +0,0 @@ -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , MongooseBuffer = require('../types').Buffer - , Binary = MongooseBuffer.Binary - , Query = require('../query') - , utils = require('../utils') - , Document - -/** - * Buffer SchemaType constructor - * - * @param {String} key - * @param {SchemaType} cast - * @inherits SchemaType - * @api private - */ - -function SchemaBuffer (key, options) { - SchemaType.call(this, key, options, 'Buffer'); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaBuffer.prototype.__proto__ = SchemaType.prototype; - -/** - * Check required - * - * @api private - */ - -SchemaBuffer.prototype.checkRequired = function (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return null != value; - } else { - return !!(value && value.length); - } -}; - -/** - * Casts contents - * - * @param {Object} value - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - -SchemaBuffer.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (null == value) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (Buffer.isBuffer(value)) { - return value; - } else if (!utils.isObject(value)) { - throw new CastError('buffer', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - var path = doc.$__fullPath(this.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - var pop = owner.populated(path, true); - var ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - // documents - if (value && value._id) { - value = value._id; - } - - if (Buffer.isBuffer(value)) { - if (!(value instanceof MongooseBuffer)) { - value = new MongooseBuffer(value, [this.path, doc]); - } - - return value; - } else if (value instanceof Binary) { - var ret = new MongooseBuffer(value.value(true), [this.path, doc]); - ret.subtype(value.sub_type); - // do not override Binary subtypes. users set this - // to whatever they want. - return ret; - } - - if (null === value) return value; - - var type = typeof value; - if ('string' == type || 'number' == type || Array.isArray(value)) { - var ret = new MongooseBuffer(value, [this.path, doc]); - return ret; - } - - throw new CastError('buffer', value, this.path); -}; - -/*! - * ignore - */ -function handleSingle (val) { - return this.castForQuery(val); -} - -function handleArray (val) { - var self = this; - return val.map( function (m) { - return self.castForQuery(m); - }); -} - -SchemaBuffer.prototype.$conditionalHandlers = { - '$ne' : handleSingle - , '$in' : handleArray - , '$nin': handleArray - , '$gt' : handleSingle - , '$lt' : handleSingle - , '$gte': handleSingle - , '$lte': handleSingle -}; - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaBuffer.prototype.castForQuery = function ($conditional, val) { - var handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) - throw new Error("Can't use " + $conditional + " with Buffer."); - return handler.call(this, val); - } else { - val = $conditional; - return this.cast(val).toObject(); - } -}; - -/*! - * Module exports. - */ - -module.exports = SchemaBuffer; diff --git a/node_modules/mongoose/lib/schema/date.js b/node_modules/mongoose/lib/schema/date.js deleted file mode 100644 index 86e4062e1..000000000 --- a/node_modules/mongoose/lib/schema/date.js +++ /dev/null @@ -1,167 +0,0 @@ -/*! - * Module requirements. - */ - -var SchemaType = require('../schematype'); -var CastError = SchemaType.CastError; -var utils = require('../utils'); - -/** - * Date SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaDate (key, options) { - SchemaType.call(this, key, options); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaDate.prototype.__proto__ = SchemaType.prototype; - -/** - * Declares a TTL index (rounded to the nearest second) for _Date_ types only. - * - * This sets the `expiresAfterSeconds` index option available in MongoDB >= 2.1.2. - * This index type is only compatible with Date types. - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: 60*60*24 }}); - * - * `expires` utilizes the `ms` module from [guille](https://github.com/guille/) allowing us to use a friendlier syntax: - * - * ####Example: - * - * // expire in 24 hours - * new Schema({ createdAt: { type: Date, expires: '24h' }}); - * - * // expire in 1.5 hours - * new Schema({ createdAt: { type: Date, expires: '1.5h' }}); - * - * // expire in 7 days - * var schema = new Schema({ createdAt: Date }); - * schema.path('createdAt').expires('7d'); - * - * @param {Number|String} when - * @added 3.0.0 - * @return {SchemaType} this - * @api public - */ - -SchemaDate.prototype.expires = function (when) { - if (!this._index || 'Object' !== this._index.constructor.name) { - this._index = {}; - } - - this._index.expires = when; - utils.expires(this._index); - return this; -}; - -/** - * Required validator for date - * - * @api private - */ - -SchemaDate.prototype.checkRequired = function (value) { - return value instanceof Date; -}; - -/** - * Casts to date - * - * @param {Object} value to cast - * @api private - */ - -SchemaDate.prototype.cast = function (value) { - if (value === null || value === '') - return null; - - if (value instanceof Date) - return value; - - var date; - - // support for timestamps - if (value instanceof Number || 'number' == typeof value - || String(value) == Number(value)) - date = new Date(Number(value)); - - // support for date strings - else if (value.toString) - date = new Date(value.toString()); - - if (date.toString() != 'Invalid Date') - return date; - - throw new CastError('date', value, this.path); -}; - -/*! - * Date Query casting. - * - * @api private - */ - -function handleSingle (val) { - return this.cast(val); -} - -function handleArray (val) { - var self = this; - return val.map( function (m) { - return self.cast(m); - }); -} - -SchemaDate.prototype.$conditionalHandlers = { - '$lt': handleSingle - , '$lte': handleSingle - , '$gt': handleSingle - , '$gte': handleSingle - , '$ne': handleSingle - , '$in': handleArray - , '$nin': handleArray - , '$all': handleArray -}; - - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaDate.prototype.castForQuery = function ($conditional, val) { - var handler; - - if (2 !== arguments.length) { - return this.cast($conditional); - } - - handler = this.$conditionalHandlers[$conditional]; - - if (!handler) { - throw new Error("Can't use " + $conditional + " with Date."); - } - - return handler.call(this, val); -}; - -/*! - * Module exports. - */ - -module.exports = SchemaDate; diff --git a/node_modules/mongoose/lib/schema/documentarray.js b/node_modules/mongoose/lib/schema/documentarray.js deleted file mode 100644 index 3b0288709..000000000 --- a/node_modules/mongoose/lib/schema/documentarray.js +++ /dev/null @@ -1,189 +0,0 @@ - -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , ArrayType = require('./array') - , MongooseDocumentArray = require('../types/documentarray') - , Subdocument = require('../types/embedded') - , Document = require('../document'); - -/** - * SubdocsArray SchemaType constructor - * - * @param {String} key - * @param {Schema} schema - * @param {Object} options - * @inherits SchemaArray - * @api private - */ - -function DocumentArray (key, schema, options) { - - // compile an embedded document for this schema - function EmbeddedDocument () { - Subdocument.apply(this, arguments); - } - - EmbeddedDocument.prototype.__proto__ = Subdocument.prototype; - EmbeddedDocument.prototype.$__setSchema(schema); - EmbeddedDocument.schema = schema; - - // apply methods - for (var i in schema.methods) { - EmbeddedDocument.prototype[i] = schema.methods[i]; - } - - // apply statics - for (var i in schema.statics) - EmbeddedDocument[i] = schema.statics[i]; - - EmbeddedDocument.options = options; - this.schema = schema; - - ArrayType.call(this, key, EmbeddedDocument, options); - - this.schema = schema; - var path = this.path; - var fn = this.defaultValue; - - this.default(function(){ - var arr = fn.call(this); - if (!Array.isArray(arr)) arr = [arr]; - return new MongooseDocumentArray(arr, path, this); - }); -}; - -/*! - * Inherits from ArrayType. - */ - -DocumentArray.prototype.__proto__ = ArrayType.prototype; - -/** - * Performs local validations first, then validations on each embedded doc - * - * @api private - */ - -DocumentArray.prototype.doValidate = function (array, fn, scope) { - var self = this; - - SchemaType.prototype.doValidate.call(this, array, function (err) { - if (err) return fn(err); - - var count = array && array.length - , error; - - if (!count) return fn(); - - // handle sparse arrays, do not use array.forEach which does not - // iterate over sparse elements yet reports array.length including - // them :( - - for (var i = 0, len = count; i < len; ++i) { - // sidestep sparse entries - var doc = array[i]; - if (!doc) { - --count || fn(); - continue; - } - - ;(function (i) { - doc.validate(function (err) { - if (err && !error) { - // rewrite the key - err.key = self.key + '.' + i + '.' + err.key; - return fn(error = err); - } - --count || fn(); - }); - })(i); - } - }, scope); -}; - -/** - * Casts contents - * - * @param {Object} value - * @param {Document} document that triggers the casting - * @api private - */ - -DocumentArray.prototype.cast = function (value, doc, init, prev) { - var selected - , subdoc - , i - - if (!Array.isArray(value)) { - return this.cast([value], doc, init, prev); - } - - if (!(value instanceof MongooseDocumentArray)) { - value = new MongooseDocumentArray(value, this.path, doc); - } - - i = value.length; - - while (i--) { - if (!(value[i] instanceof Subdocument) && value[i]) { - if (init) { - selected || (selected = scopePaths(this, doc.$__.selected, init)); - subdoc = new this.casterConstructor(null, value, true, selected); - value[i] = subdoc.init(value[i]); - } else { - if (prev && (subdoc = prev.id(value[i]._id))) { - // handle resetting doc with existing id but differing data - // doc.array = [{ doc: 'val' }] - subdoc.set(value[i]); - } else { - subdoc = new this.casterConstructor(value[i], value); - } - - // if set() is hooked it will have no return value - // see gh-746 - value[i] = subdoc; - } - } - } - - return value; -} - -/*! - * Scopes paths selected in a query to this array. - * Necessary for proper default application of subdocument values. - * - * @param {DocumentArray} array - the array to scope `fields` paths - * @param {Object|undefined} fields - the root fields selected in the query - * @param {Boolean|undefined} init - if we are being created part of a query result - */ - -function scopePaths (array, fields, init) { - if (!(init && fields)) return undefined; - - var path = array.path + '.' - , keys = Object.keys(fields) - , i = keys.length - , selected = {} - , hasKeys - , key - - while (i--) { - key = keys[i]; - if (0 === key.indexOf(path)) { - hasKeys || (hasKeys = true); - selected[key.substring(path.length)] = fields[key]; - } - } - - return hasKeys && selected || undefined; -} - -/*! - * Module exports. - */ - -module.exports = DocumentArray; diff --git a/node_modules/mongoose/lib/schema/index.js b/node_modules/mongoose/lib/schema/index.js deleted file mode 100644 index d1347edc1..000000000 --- a/node_modules/mongoose/lib/schema/index.js +++ /dev/null @@ -1,28 +0,0 @@ - -/*! - * Module exports. - */ - -exports.String = require('./string'); - -exports.Number = require('./number'); - -exports.Boolean = require('./boolean'); - -exports.DocumentArray = require('./documentarray'); - -exports.Array = require('./array'); - -exports.Buffer = require('./buffer'); - -exports.Date = require('./date'); - -exports.ObjectId = require('./objectid'); - -exports.Mixed = require('./mixed'); - -// alias - -exports.Oid = exports.ObjectId; -exports.Object = exports.Mixed; -exports.Bool = exports.Boolean; diff --git a/node_modules/mongoose/lib/schema/mixed.js b/node_modules/mongoose/lib/schema/mixed.js deleted file mode 100644 index c34eb398d..000000000 --- a/node_modules/mongoose/lib/schema/mixed.js +++ /dev/null @@ -1,83 +0,0 @@ - -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype'); -var utils = require('../utils'); - -/** - * Mixed SchemaType constructor. - * - * @param {String} path - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function Mixed (path, options) { - if (options && options.default) { - var def = options.default; - if (Array.isArray(def) && 0 === def.length) { - // make sure empty array defaults are handled - options.default = Array; - } else if (!options.shared && - utils.isObject(def) && - 0 === Object.keys(def).length) { - // prevent odd "shared" objects between documents - options.default = function () { - return {} - } - } - } - - SchemaType.call(this, path, options); -}; - -/*! - * Inherits from SchemaType. - */ - -Mixed.prototype.__proto__ = SchemaType.prototype; - -/** - * Required validator - * - * @api private - */ - -Mixed.prototype.checkRequired = function (val) { - return (val !== undefined) && (val !== null); -}; - -/** - * Casts `val` for Mixed. - * - * _this is a no-op_ - * - * @param {Object} value to cast - * @api private - */ - -Mixed.prototype.cast = function (val) { - return val; -}; - -/** - * Casts contents for queries. - * - * @param {String} $cond - * @param {any} [val] - * @api private - */ - -Mixed.prototype.castForQuery = function ($cond, val) { - if (arguments.length === 2) return val; - return $cond; -}; - -/*! - * Module exports. - */ - -module.exports = Mixed; diff --git a/node_modules/mongoose/lib/schema/number.js b/node_modules/mongoose/lib/schema/number.js deleted file mode 100644 index 29a372f4c..000000000 --- a/node_modules/mongoose/lib/schema/number.js +++ /dev/null @@ -1,256 +0,0 @@ -/*! - * Module requirements. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , errorMessages = require('../error').messages - , utils = require('../utils') - , Document - -/** - * Number SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaNumber (key, options) { - SchemaType.call(this, key, options, 'Number'); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaNumber.prototype.__proto__ = SchemaType.prototype; - -/** - * Required validator for number - * - * @api private - */ - -SchemaNumber.prototype.checkRequired = function checkRequired (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return null != value; - } else { - return typeof value == 'number' || value instanceof Number; - } -}; - -/** - * Sets a minimum number validator. - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, min: 10 }) - * var M = db.model('M', s) - * var m = new M({ n: 9 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MIN} token which will be replaced with the invalid value - * var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).']; - * var schema = new Schema({ n: { type: Number, min: min }) - * var M = mongoose.model('Measurement', schema); - * var s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10). - * }) - * - * @param {Number} value minimum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.min = function (value, message) { - if (this.minValidator) { - this.validators = this.validators.filter(function (v) { - return v[0] != this.minValidator; - }, this); - } - - if (null != value) { - var msg = message || errorMessages.Number.min; - msg = msg.replace(/{MIN}/, value); - this.validators.push([this.minValidator = function (v) { - return v === null || v >= value; - }, msg, 'min']); - } - - return this; -}; - -/** - * Sets a maximum number validator. - * - * ####Example: - * - * var s = new Schema({ n: { type: Number, max: 10 }) - * var M = db.model('M', s) - * var m = new M({ n: 11 }) - * m.save(function (err) { - * console.error(err) // validator error - * m.n = 10; - * m.save() // success - * }) - * - * // custom error messages - * // We can also use the special {MAX} token which will be replaced with the invalid value - * var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).']; - * var schema = new Schema({ n: { type: Number, max: max }) - * var M = mongoose.model('Measurement', schema); - * var s= new M({ n: 4 }); - * s.validate(function (err) { - * console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10). - * }) - * - * @param {Number} maximum number - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaNumber.prototype.max = function (value, message) { - if (this.maxValidator) { - this.validators = this.validators.filter(function(v){ - return v[0] != this.maxValidator; - }, this); - } - - if (null != value) { - var msg = message || errorMessages.Number.max; - msg = msg.replace(/{MAX}/, value); - this.validators.push([this.maxValidator = function(v){ - return v === null || v <= value; - }, msg, 'max']); - } - - return this; -}; - -/** - * Casts to number - * - * @param {Object} value value to cast - * @param {Document} doc document that triggers the casting - * @param {Boolean} init - * @api private - */ - -SchemaNumber.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (null == value) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if ('number' == typeof value) { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('number', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - var path = doc.$__fullPath(this.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - var pop = owner.populated(path, true); - var ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - var val = value && value._id - ? value._id // documents - : value; - - if (!isNaN(val)){ - if (null === val) return val; - if ('' === val) return null; - if ('string' == typeof val) val = Number(val); - if (val instanceof Number) return val - if ('number' == typeof val) return val; - if (val.toString && !Array.isArray(val) && - val.toString() == Number(val)) { - return new Number(val) - } - } - - throw new CastError('number', value, this.path); -}; - -/*! - * ignore - */ - -function handleSingle (val) { - return this.cast(val) -} - -function handleArray (val) { - var self = this; - return val.map(function (m) { - return self.cast(m) - }); -} - -SchemaNumber.prototype.$conditionalHandlers = { - '$lt' : handleSingle - , '$lte': handleSingle - , '$gt' : handleSingle - , '$gte': handleSingle - , '$ne' : handleSingle - , '$in' : handleArray - , '$nin': handleArray - , '$mod': handleArray - , '$all': handleArray -}; - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [value] - * @api private - */ - -SchemaNumber.prototype.castForQuery = function ($conditional, val) { - var handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) - throw new Error("Can't use " + $conditional + " with Number."); - return handler.call(this, val); - } else { - val = this.cast($conditional); - return val == null ? val : val - } -}; - -/*! - * Module exports. - */ - -module.exports = SchemaNumber; diff --git a/node_modules/mongoose/lib/schema/objectid.js b/node_modules/mongoose/lib/schema/objectid.js deleted file mode 100644 index 664f68682..000000000 --- a/node_modules/mongoose/lib/schema/objectid.js +++ /dev/null @@ -1,186 +0,0 @@ -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , driver = global.MONGOOSE_DRIVER_PATH || './../drivers/node-mongodb-native' - , oid = require('../types/objectid') - , utils = require('../utils') - , Document - -/** - * ObjectId SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function ObjectId (key, options) { - SchemaType.call(this, key, options, 'ObjectID'); -}; - -/*! - * Inherits from SchemaType. - */ - -ObjectId.prototype.__proto__ = SchemaType.prototype; - -/** - * Adds an auto-generated ObjectId default if turnOn is true. - * @param {Boolean} turnOn auto generated ObjectId defaults - * @api public - * @return {SchemaType} this - */ - -ObjectId.prototype.auto = function (turnOn) { - if (turnOn) { - this.default(defaultId); - this.set(resetId) - } - - return this; -}; - -/** - * Check required - * - * @api private - */ - -ObjectId.prototype.checkRequired = function checkRequired (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return null != value; - } else { - return value instanceof oid; - } -}; - -/** - * Casts to ObjectId - * - * @param {Object} value - * @param {Object} doc - * @param {Boolean} init whether this is an initialization cast - * @api private - */ - -ObjectId.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (null == value) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if (value instanceof oid) { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('ObjectId', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - var path = doc.$__fullPath(this.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - var pop = owner.populated(path, true); - var ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - if (value === null) return value; - - if (value instanceof oid) - return value; - - if (value._id && value._id instanceof oid) - return value._id; - - if (value.toString) { - try { - return oid.createFromHexString(value.toString()); - } catch (err) { - throw new CastError('ObjectId', value, this.path); - } - } - - throw new CastError('ObjectId', value, this.path); -}; - -/*! - * ignore - */ - -function handleSingle (val) { - return this.cast(val); -} - -function handleArray (val) { - var self = this; - return val.map(function (m) { - return self.cast(m); - }); -} - -ObjectId.prototype.$conditionalHandlers = { - '$ne': handleSingle - , '$in': handleArray - , '$nin': handleArray - , '$gt': handleSingle - , '$lt': handleSingle - , '$gte': handleSingle - , '$lte': handleSingle - , '$all': handleArray -}; - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [val] - * @api private - */ - -ObjectId.prototype.castForQuery = function ($conditional, val) { - var handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) - throw new Error("Can't use " + $conditional + " with ObjectId."); - return handler.call(this, val); - } else { - return this.cast($conditional); - } -}; - -/*! - * ignore - */ - -function defaultId () { - return new oid(); -}; - -function resetId (v) { - this.$__._id = null; - return v; -} - -/*! - * Module exports. - */ - -module.exports = ObjectId; diff --git a/node_modules/mongoose/lib/schema/string.js b/node_modules/mongoose/lib/schema/string.js deleted file mode 100644 index edcf19e9c..000000000 --- a/node_modules/mongoose/lib/schema/string.js +++ /dev/null @@ -1,356 +0,0 @@ - -/*! - * Module dependencies. - */ - -var SchemaType = require('../schematype') - , CastError = SchemaType.CastError - , errorMessages = require('../error').messages - , utils = require('../utils') - , Document - -/** - * String SchemaType constructor. - * - * @param {String} key - * @param {Object} options - * @inherits SchemaType - * @api private - */ - -function SchemaString (key, options) { - this.enumValues = []; - this.regExp = null; - SchemaType.call(this, key, options, 'String'); -}; - -/*! - * Inherits from SchemaType. - */ - -SchemaString.prototype.__proto__ = SchemaType.prototype; - -/** - * Adds an enum validator - * - * ####Example: - * - * var states = 'opening open closing closed'.split(' ') - * var s = new Schema({ state: { type: String, enum: states }}) - * var M = db.model('M', s) - * var m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`. - * m.state = 'open' - * m.save(callback) // success - * }) - * - * // or with custom error messages - * var enu = { - * values: 'opening open closing closed'.split(' '), - * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`' - * } - * var s = new Schema({ state: { type: String, enum: enu }) - * var M = db.model('M', s) - * var m = new M({ state: 'invalid' }) - * m.save(function (err) { - * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid` - * m.state = 'open' - * m.save(callback) // success - * }) - * - * @param {String|Object} [args...] enumeration values - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.enum = function () { - if (this.enumValidator) { - this.validators = this.validators.filter(function(v){ - return v[0] != this.enumValidator; - }, this); - this.enumValidator = false; - } - - if (undefined === arguments[0] || false === arguments[0]) { - return this; - } - - var values; - var errorMessage; - - if (utils.isObject(arguments[0])) { - values = arguments[0].values; - errorMessage = arguments[0].message; - } else { - values = arguments; - errorMessage = errorMessages.String.enum; - } - - for (var i = 0; i < values.length; i++) { - if (undefined !== values[i]) { - this.enumValues.push(this.cast(values[i])); - } - } - - var vals = this.enumValues; - this.enumValidator = function (v) { - return undefined === v || ~vals.indexOf(v); - }; - this.validators.push([this.enumValidator, errorMessage, 'enum']); - - return this; -}; - -/** - * Adds a lowercase setter. - * - * ####Example: - * - * var s = new Schema({ email: { type: String, lowercase: true }}) - * var M = db.model('M', s); - * var m = new M({ email: 'SomeEmail@example.COM' }); - * console.log(m.email) // someemail@example.com - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.lowercase = function () { - return this.set(function (v, self) { - if ('string' != typeof v) v = self.cast(v) - if (v) return v.toLowerCase(); - return v; - }); -}; - -/** - * Adds an uppercase setter. - * - * ####Example: - * - * var s = new Schema({ caps: { type: String, uppercase: true }}) - * var M = db.model('M', s); - * var m = new M({ caps: 'an example' }); - * console.log(m.caps) // AN EXAMPLE - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.uppercase = function () { - return this.set(function (v, self) { - if ('string' != typeof v) v = self.cast(v) - if (v) return v.toUpperCase(); - return v; - }); -}; - -/** - * Adds a trim setter. - * - * The string value will be trimmed when set. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, trim: true }}) - * var M = db.model('M', s) - * var string = ' some name ' - * console.log(string.length) // 11 - * var m = new M({ name: string }) - * console.log(m.name.length) // 9 - * - * @api public - * @return {SchemaType} this - */ - -SchemaString.prototype.trim = function () { - return this.set(function (v, self) { - if ('string' != typeof v) v = self.cast(v) - if (v) return v.trim(); - return v; - }); -}; - -/** - * Sets a regexp validator. - * - * Any value that does not pass `regExp`.test(val) will fail validation. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, match: /^a/ }}) - * var M = db.model('M', s) - * var m = new M({ name: 'I am invalid' }) - * m.validate(function (err) { - * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)." - * m.name = 'apples' - * m.validate(function (err) { - * assert.ok(err) // success - * }) - * }) - * - * // using a custom error message - * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ]; - * var s = new Schema({ file: { type: String, match: match }}) - * var M = db.model('M', s); - * var m = new M({ file: 'invalid' }); - * m.validate(function (err) { - * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)" - * }) - * - * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also. - * - * var s = new Schema({ name: { type: String, match: /^a/, required: true }}) - * - * @param {RegExp} regExp regular expression to test against - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaString.prototype.match = function match (regExp, message) { - // yes, we allow multiple match validators - - var msg = message || errorMessages.String.match; - - function matchValidator (v){ - return null != v && '' !== v - ? regExp.test(v) - : true - } - - this.validators.push([matchValidator, msg, 'regexp']); - return this; -}; - -/** - * Check required - * - * @param {String|null|undefined} value - * @api private - */ - -SchemaString.prototype.checkRequired = function checkRequired (value, doc) { - if (SchemaType._isRef(this, value, doc, true)) { - return null != value; - } else { - return (value instanceof String || typeof value == 'string') && value.length; - } -}; - -/** - * Casts to String - * - * @api private - */ - -SchemaString.prototype.cast = function (value, doc, init) { - if (SchemaType._isRef(this, value, doc, init)) { - // wait! we may need to cast this to a document - - if (null == value) { - return value; - } - - // lazy load - Document || (Document = require('./../document')); - - if (value instanceof Document) { - value.$__.wasPopulated = true; - return value; - } - - // setting a populated path - if ('string' == typeof value) { - return value; - } else if (Buffer.isBuffer(value) || !utils.isObject(value)) { - throw new CastError('string', value, this.path); - } - - // Handle the case where user directly sets a populated - // path to a plain object; cast to the Model used in - // the population query. - var path = doc.$__fullPath(this.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - var pop = owner.populated(path, true); - var ret = new pop.options.model(value); - ret.$__.wasPopulated = true; - return ret; - } - - if (value === null) { - return value; - } - - if ('undefined' !== typeof value) { - // handle documents being passed - if (value._id && 'string' == typeof value._id) { - return value._id; - } - if (value.toString) { - return value.toString(); - } - } - - - throw new CastError('string', value, this.path); -}; - -/*! - * ignore - */ - -function handleSingle (val) { - return this.castForQuery(val); -} - -function handleArray (val) { - var self = this; - return val.map(function (m) { - return self.castForQuery(m); - }); -} - -SchemaString.prototype.$conditionalHandlers = { - '$ne' : handleSingle - , '$in' : handleArray - , '$nin': handleArray - , '$gt' : handleSingle - , '$lt' : handleSingle - , '$gte': handleSingle - , '$lte': handleSingle - , '$all': handleArray - , '$regex': handleSingle - , '$options': handleSingle -}; - -/** - * Casts contents for queries. - * - * @param {String} $conditional - * @param {any} [val] - * @api private - */ - -SchemaString.prototype.castForQuery = function ($conditional, val) { - var handler; - if (arguments.length === 2) { - handler = this.$conditionalHandlers[$conditional]; - if (!handler) - throw new Error("Can't use " + $conditional + " with String."); - return handler.call(this, val); - } else { - val = $conditional; - if (val instanceof RegExp) return val; - return this.cast(val); - } -}; - -/*! - * Module exports. - */ - -module.exports = SchemaString; diff --git a/node_modules/mongoose/lib/schemadefault.js b/node_modules/mongoose/lib/schemadefault.js deleted file mode 100644 index aebcff598..000000000 --- a/node_modules/mongoose/lib/schemadefault.js +++ /dev/null @@ -1,34 +0,0 @@ - -/*! - * Module dependencies. - */ - -var Schema = require('./schema') - -/** - * Default model for querying the system.profiles collection. - * - * @property system.profile - * @receiver exports - * @api private - */ - -exports['system.profile'] = new Schema({ - ts: Date - , info: String // deprecated - , millis: Number - , op: String - , ns: String - , query: Schema.Types.Mixed - , updateobj: Schema.Types.Mixed - , ntoreturn: Number - , nreturned: Number - , nscanned: Number - , responseLength: Number - , client: String - , user: String - , idhack: Boolean - , scanAndOrder: Boolean - , keyUpdates: Number - , cursorid: Number -}, { noVirtualId: true, noId: true }); diff --git a/node_modules/mongoose/lib/schematype.js b/node_modules/mongoose/lib/schematype.js deleted file mode 100644 index 503021586..000000000 --- a/node_modules/mongoose/lib/schematype.js +++ /dev/null @@ -1,678 +0,0 @@ -/*! - * Module dependencies. - */ - -var utils = require('./utils'); -var error = require('./error'); -var errorMessages = error.messages; -var CastError = error.CastError; -var ValidatorError = error.ValidatorError; - -/** - * SchemaType constructor - * - * @param {String} path - * @param {Object} [options] - * @param {String} [instance] - * @api public - */ - -function SchemaType (path, options, instance) { - this.path = path; - this.instance = instance; - this.validators = []; - this.setters = []; - this.getters = []; - this.options = options; - this._index = null; - this.selected; - - for (var i in options) if (this[i] && 'function' == typeof this[i]) { - // { unique: true, index: true } - if ('index' == i && this._index) continue; - - var opts = Array.isArray(options[i]) - ? options[i] - : [options[i]]; - - this[i].apply(this, opts); - } -}; - -/** - * Sets a default value for this SchemaType. - * - * ####Example: - * - * var schema = new Schema({ n: { type: Number, default: 10 }) - * var M = db.model('M', schema) - * var m = new M; - * console.log(m.n) // 10 - * - * Defaults can be either `functions` which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation. - * - * ####Example: - * - * // values are cast: - * var schema = new Schema({ aNumber: Number, default: "4.815162342" }) - * var M = db.model('M', schema) - * var m = new M; - * console.log(m.aNumber) // 4.815162342 - * - * // default unique objects for Mixed types: - * var schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default(function () { - * return {}; - * }); - * - * // if we don't use a function to return object literals for Mixed defaults, - * // each document will receive a reference to the same object literal creating - * // a "shared" object instance: - * var schema = new Schema({ mixed: Schema.Types.Mixed }); - * schema.path('mixed').default({}); - * var M = db.model('M', schema); - * var m1 = new M; - * m1.mixed.added = 1; - * console.log(m1.mixed); // { added: 1 } - * var m2 = new M; - * console.log(m2.mixed); // { added: 1 } - * - * @param {Function|any} val the default value - * @return {defaultValue} - * @api public - */ - -SchemaType.prototype.default = function (val) { - if (1 === arguments.length) { - this.defaultValue = typeof val === 'function' - ? val - : this.cast(val); - return this; - } else if (arguments.length > 1) { - this.defaultValue = utils.args(arguments); - } - return this.defaultValue; -}; - -/** - * Declares the index options for this schematype. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, index: true }) - * var s = new Schema({ loc: { type: [Number], index: 'hashed' }) - * var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true }) - * var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }}) - * var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }}) - * Schema.path('my.path').index(true); - * Schema.path('my.date').index({ expires: 60 }); - * Schema.path('my.path').index({ unique: true, sparse: true }); - * - * ####NOTE: - * - * _Indexes are created in the background by default. Specify `background: false` to override._ - * - * [Direction doesn't matter for single key indexes](http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes) - * - * @param {Object|Boolean|String} options - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.index = function (options) { - this._index = options; - utils.expires(this._index); - return this; -}; - -/** - * Declares an unique index. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, unique: true }) - * Schema.path('name').index({ unique: true }); - * - * _NOTE: violating the constraint returns an `E11000` error from MongoDB when saving, not a Mongoose validation error._ - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.unique = function (bool) { - if (null == this._index || 'boolean' == typeof this._index) { - this._index = {}; - } else if ('string' == typeof this._index) { - this._index = { type: this._index }; - } - - this._index.unique = bool; - return this; -}; - -/** - * Declares a sparse index. - * - * ####Example: - * - * var s = new Schema({ name: { type: String, sparse: true }) - * Schema.path('name').index({ sparse: true }); - * - * @param {Boolean} bool - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.sparse = function (bool) { - if (null == this._index || 'boolean' == typeof this._index) { - this._index = {}; - } else if ('string' == typeof this._index) { - this._index = { type: this._index }; - } - - this._index.sparse = bool; - return this; -}; - -/** - * Adds a setter to this schematype. - * - * ####Example: - * - * function capitalize (val) { - * if ('string' != typeof val) val = ''; - * return val.charAt(0).toUpperCase() + val.substring(1); - * } - * - * // defining within the schema - * var s = new Schema({ name: { type: String, set: capitalize }}) - * - * // or by retreiving its SchemaType - * var s = new Schema({ name: String }) - * s.path('name').set(capitalize) - * - * Setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key. - * - * Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM. - * - * You can set up email lower case normalization easily via a Mongoose setter. - * - * function toLower (v) { - * return v.toLowerCase(); - * } - * - * var UserSchema = new Schema({ - * email: { type: String, set: toLower } - * }) - * - * var User = db.model('User', UserSchema) - * - * var user = new User({email: 'AVENUE@Q.COM'}) - * console.log(user.email); // 'avenue@q.com' - * - * // or - * var user = new User - * user.email = 'Avenue@Q.com' - * console.log(user.email) // 'avenue@q.com' - * - * As you can see above, setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key. - * - * _NOTE: we could have also just used the built-in `lowercase: true` SchemaType option instead of defining our own function._ - * - * new Schema({ email: { type: String, lowercase: true }}) - * - * Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return val; - * } - * } - * - * var VirusSchema = new Schema({ - * name: { type: String, required: true, set: inspector }, - * taxonomy: { type: String, set: inspector } - * }) - * - * var Virus = db.model('Virus', VirusSchema); - * var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' }); - * - * console.log(v.name); // name is required - * console.log(v.taxonomy); // Parvovirinae - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.set = function (fn) { - if ('function' != typeof fn) - throw new TypeError('A setter must be a function.'); - this.setters.push(fn); - return this; -}; - -/** - * Adds a getter to this schematype. - * - * ####Example: - * - * function dob (val) { - * if (!val) return val; - * return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear(); - * } - * - * // defining within the schema - * var s = new Schema({ born: { type: Date, get: dob }) - * - * // or by retreiving its SchemaType - * var s = new Schema({ born: Date }) - * s.path('born').get(dob) - * - * Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see. - * - * Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way: - * - * function obfuscate (cc) { - * return '****-****-****-' + cc.slice(cc.length-4, cc.length); - * } - * - * var AccountSchema = new Schema({ - * creditCardNumber: { type: String, get: obfuscate } - * }); - * - * var Account = db.model('Account', AccountSchema); - * - * Account.findById(id, function (err, found) { - * console.log(found.creditCardNumber); // '****-****-****-1234' - * }); - * - * Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema. - * - * function inspector (val, schematype) { - * if (schematype.options.required) { - * return schematype.path + ' is required'; - * } else { - * return schematype.path + ' is not'; - * } - * } - * - * var VirusSchema = new Schema({ - * name: { type: String, required: true, get: inspector }, - * taxonomy: { type: String, get: inspector } - * }) - * - * var Virus = db.model('Virus', VirusSchema); - * - * Virus.findById(id, function (err, virus) { - * console.log(virus.name); // name is required - * console.log(virus.taxonomy); // taxonomy is not - * }) - * - * @param {Function} fn - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.get = function (fn) { - if ('function' != typeof fn) - throw new TypeError('A getter must be a function.'); - this.getters.push(fn); - return this; -}; - -/** - * Adds validator(s) for this document path. - * - * Validators always receive the value to validate as their first argument and must return `Boolean`. Returning `false` means validation failed. - * - * The error message argument is optional. If not passed, the [default generic error message template](#error_messages_MongooseError-messages) will be used. - * - * ####Examples: - * - * // make sure every value is equal to "something" - * function validator (val) { - * return val == 'something'; - * } - * new Schema({ name: { type: String, validate: validator }}); - * - * // with a custom error message - * - * var custom = [validator, 'Uh oh, {PATH} does not equal "something".'] - * new Schema({ name: { type: String, validate: custom }}); - * - * // adding many validators at a time - * - * var many = [ - * { validator: validator, msg: 'uh oh' } - * , { validator: anotherValidator, msg: 'failed' } - * ] - * new Schema({ name: { type: String, validate: many }}); - * - * // or utilizing SchemaType methods directly: - * - * var schema = new Schema({ name: 'string' }); - * schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`'); - * - * ####Error message templates: - * - * From the examples above, you may have noticed that error messages support baseic templating. There are a few other template keywords besides `{PATH}` and `{VALUE}` too. To find out more, details are available [here](#error_messages_MongooseError-messages) - * - * ####Asynchronous validation: - * - * Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first argument passed to the validator function is the value being validated. The second argument is a callback function that must called when you finish validating the value and passed either `true` or `false` to communicate either success or failure respectively. - * - * schema.path('name').validate(function (value, respond) { - * doStuff(value, function () { - * ... - * respond(false); // validation failed - * }) -* }, '{PATH} failed validation.'); -* - * You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs. - * - * Validation occurs `pre('save')` or whenever you manually execute [document#validate](#document_Document-validate). - * - * If validation fails during `pre('save')` and no callback was passed to receive the error, an `error` event will be emitted on your Models associated db [connection](#connection_Connection), passing the validation error object along. - * - * var conn = mongoose.createConnection(..); - * conn.on('error', handleError); - * - * var Product = conn.model('Product', yourSchema); - * var dvd = new Product(..); - * dvd.save(); // emits error on the `conn` above - * - * If you desire handling these errors at the Model level, attach an `error` listener to your Model and the event will instead be emitted there. - * - * // registering an error listener on the Model lets us handle errors more locally - * Product.on('error', handleError); - * - * @param {RegExp|Function|Object} obj validator - * @param {String} [errorMsg] optional error message - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.validate = function (obj, message) { - if ('function' == typeof obj || obj && 'RegExp' === obj.constructor.name) { - if (!message) message = errorMessages.general.default; - this.validators.push([obj, message, 'user defined']); - return this; - } - - var i = arguments.length - , arg - - while (i--) { - arg = arguments[i]; - if (!(arg && 'Object' == arg.constructor.name)) { - var msg = 'Invalid validator. Received (' + typeof arg + ') ' - + arg - + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate'; - - throw new Error(msg); - } - this.validate(arg.validator, arg.msg); - } - - return this; -}; - -/** - * Adds a required validator to this schematype. - * - * ####Example: - * - * var s = new Schema({ born: { type: Date, required: true }) - * - * // or with custom error message - * - * var s = new Schema({ born: { type: Date, required: '{PATH} is required!' }) - * - * // or through the path API - * - * Schema.path('name').required(true); - * - * // with custom error messaging - * - * Schema.path('name').required(true, 'grrr :( '); - * - * - * @param {Boolean} required enable/disable the validator - * @param {String} [message] optional custom error message - * @return {SchemaType} this - * @see Customized Error Messages #error_messages_MongooseError-messages - * @api public - */ - -SchemaType.prototype.required = function (required, message) { - if (false === required) { - this.validators = this.validators.filter(function (v) { - return v[0] != this.requiredValidator; - }, this); - - this.isRequired = false; - return this; - } - - var self = this; - this.isRequired = true; - - this.requiredValidator = function (v) { - // in here, `this` refers to the validating document. - // no validation when this path wasn't selected in the query. - if ('isSelected' in this && - !this.isSelected(self.path) && - !this.isModified(self.path)) return true; - return self.checkRequired(v, this); - } - - if ('string' == typeof required) { - message = required; - required = undefined; - } - - var msg = message || errorMessages.general.required; - this.validators.push([this.requiredValidator, msg, 'required']); - - return this; -}; - -/** - * Gets the default value - * - * @param {Object} scope the scope which callback are executed - * @param {Boolean} init - * @api private - */ - -SchemaType.prototype.getDefault = function (scope, init) { - var ret = 'function' === typeof this.defaultValue - ? this.defaultValue.call(scope) - : this.defaultValue; - - if (null !== ret && undefined !== ret) { - return this.cast(ret, scope, init); - } else { - return ret; - } -}; - -/** - * Applies setters - * - * @param {Object} value - * @param {Object} scope - * @param {Boolean} init - * @api private - */ - -SchemaType.prototype.applySetters = function (value, scope, init, priorVal) { - if (SchemaType._isRef(this, value, scope, init)) { - return init - ? value - : this.cast(value, scope, init, priorVal); - } - - var v = value - , setters = this.setters - , len = setters.length - - if (!len) { - if (null === v || undefined === v) return v; - return this.cast(v, scope, init, priorVal) - } - - while (len--) { - v = setters[len].call(scope, v, this); - } - - if (null === v || undefined === v) return v; - - // do not cast until all setters are applied #665 - v = this.cast(v, scope, init, priorVal); - - return v; -}; - -/** - * Applies getters to a value - * - * @param {Object} value - * @param {Object} scope - * @api private - */ - -SchemaType.prototype.applyGetters = function (value, scope) { - if (SchemaType._isRef(this, value, scope, true)) return value; - - var v = value - , getters = this.getters - , len = getters.length; - - if (!len) { - return v; - } - - while (len--) { - v = getters[len].call(scope, v, this); - } - - return v; -}; - -/** - * Sets default `select()` behavior for this path. - * - * Set to `true` if this path should always be included in the results, `false` if it should be excluded by default. This setting can be overridden at the query level. - * - * ####Example: - * - * T = db.model('T', new Schema({ x: { type: String, select: true }})); - * T.find(..); // field x will always be selected .. - * // .. unless overridden; - * T.find().select('-x').exec(callback); - * - * @param {Boolean} val - * @return {SchemaType} this - * @api public - */ - -SchemaType.prototype.select = function select (val) { - this.selected = !! val; - return this; -} - -/** - * Performs a validation of `value` using the validators declared for this SchemaType. - * - * @param {any} value - * @param {Function} callback - * @param {Object} scope - * @api private - */ - -SchemaType.prototype.doValidate = function (value, fn, scope) { - var err = false - , path = this.path - , count = this.validators.length; - - if (!count) return fn(null); - - function validate (ok, message, type, val) { - if (err) return; - if (ok === undefined || ok) { - --count || fn(null); - } else { - fn(err = new ValidatorError(path, message, type, val)); - } - } - - this.validators.forEach(function (v) { - var validator = v[0] - , message = v[1] - , type = v[2]; - - if (validator instanceof RegExp) { - validate(validator.test(value), message, type, value); - } else if ('function' === typeof validator) { - if (2 === validator.length) { - validator.call(scope, value, function (ok) { - validate(ok, message, type, value); - }); - } else { - validate(validator.call(scope, value), message, type, value); - } - } - }); -}; - -/** - * Determines if value is a valid Reference. - * - * @param {SchemaType} self - * @param {Object} value - * @param {Document} doc - * @param {Boolean} init - * @return {Boolean} - * @api private - */ - -SchemaType._isRef = function (self, value, doc, init) { - // fast path - var ref = init && self.options && self.options.ref; - - if (!ref && doc && doc.$__fullPath) { - // checks for - // - this populated with adhoc model and no ref was set in schema OR - // - setting / pushing values after population - var path = doc.$__fullPath(self.path); - var owner = doc.ownerDocument ? doc.ownerDocument() : doc; - ref = owner.populated(path); - } - - if (ref) { - if (null == value) return true; - if (!Buffer.isBuffer(value) && // buffers are objects too - 'Binary' != value._bsontype // raw binary value from the db - && utils.isObject(value) // might have deselected _id in population query - ) { - return true; - } - } - - return false; -} - -/*! - * Module exports. - */ - -module.exports = exports = SchemaType; - -exports.CastError = CastError; - -exports.ValidatorError = ValidatorError; diff --git a/node_modules/mongoose/lib/statemachine.js b/node_modules/mongoose/lib/statemachine.js deleted file mode 100644 index 76005d8bc..000000000 --- a/node_modules/mongoose/lib/statemachine.js +++ /dev/null @@ -1,179 +0,0 @@ - -/*! - * Module dependencies. - */ - -var utils = require('./utils'); - -/*! - * StateMachine represents a minimal `interface` for the - * constructors it builds via StateMachine.ctor(...). - * - * @api private - */ - -var StateMachine = module.exports = exports = function StateMachine () { - this.paths = {}; - this.states = {}; -} - -/*! - * StateMachine.ctor('state1', 'state2', ...) - * A factory method for subclassing StateMachine. - * The arguments are a list of states. For each state, - * the constructor's prototype gets state transition - * methods named after each state. These transition methods - * place their path argument into the given state. - * - * @param {String} state - * @param {String} [state] - * @return {Function} subclass constructor - * @private - */ - -StateMachine.ctor = function () { - var states = utils.args(arguments); - - var ctor = function () { - StateMachine.apply(this, arguments); - this.stateNames = states; - - var i = states.length - , state; - - while (i--) { - state = states[i]; - this.states[state] = {}; - } - }; - - ctor.prototype.__proto__ = StateMachine.prototype; - - states.forEach(function (state) { - // Changes the `path`'s state to `state`. - ctor.prototype[state] = function (path) { - this._changeState(path, state); - } - }); - - return ctor; -}; - -/*! - * This function is wrapped by the state change functions: - * - * - `require(path)` - * - `modify(path)` - * - `init(path)` - * - * @api private - */ - -StateMachine.prototype._changeState = function _changeState (path, nextState) { - var prevBucket = this.states[this.paths[path]]; - if (prevBucket) delete prevBucket[path]; - - this.paths[path] = nextState; - this.states[nextState][path] = true; -} - -/*! - * ignore - */ - -StateMachine.prototype.clear = function clear (state) { - var keys = Object.keys(this.states[state]) - , i = keys.length - , path - - while (i--) { - path = keys[i]; - delete this.states[state][path]; - delete this.paths[path]; - } -} - -/*! - * Checks to see if at least one path is in the states passed in via `arguments` - * e.g., this.some('required', 'inited') - * - * @param {String} state that we want to check for. - * @private - */ - -StateMachine.prototype.some = function some () { - var self = this; - var what = arguments.length ? arguments : this.stateNames; - return Array.prototype.some.call(what, function (state) { - return Object.keys(self.states[state]).length; - }); -} - -/*! - * This function builds the functions that get assigned to `forEach` and `map`, - * since both of those methods share a lot of the same logic. - * - * @param {String} iterMethod is either 'forEach' or 'map' - * @return {Function} - * @api private - */ - -StateMachine.prototype._iter = function _iter (iterMethod) { - return function () { - var numArgs = arguments.length - , states = utils.args(arguments, 0, numArgs-1) - , callback = arguments[numArgs-1]; - - if (!states.length) states = this.stateNames; - - var self = this; - - var paths = states.reduce(function (paths, state) { - return paths.concat(Object.keys(self.states[state])); - }, []); - - return paths[iterMethod](function (path, i, paths) { - return callback(path, i, paths); - }); - }; -} - -/*! - * Iterates over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @private - */ - -StateMachine.prototype.forEach = function forEach () { - this.forEach = this._iter('forEach'); - return this.forEach.apply(this, arguments); -} - -/*! - * Maps over the paths that belong to one of the parameter states. - * - * The function profile can look like: - * this.forEach(state1, fn); // iterates over all paths in state1 - * this.forEach(state1, state2, fn); // iterates over all paths in state1 or state2 - * this.forEach(fn); // iterates over all paths in all states - * - * @param {String} [state] - * @param {String} [state] - * @param {Function} callback - * @return {Array} - * @private - */ - -StateMachine.prototype.map = function map () { - this.map = this._iter('map'); - return this.map.apply(this, arguments); -} - diff --git a/node_modules/mongoose/lib/types/array.js b/node_modules/mongoose/lib/types/array.js deleted file mode 100644 index e0d770025..000000000 --- a/node_modules/mongoose/lib/types/array.js +++ /dev/null @@ -1,679 +0,0 @@ - -/*! - * Module dependencies. - */ - -var EmbeddedDocument = require('./embedded'); -var Document = require('../document'); -var ObjectId = require('./objectid'); -var utils = require('../utils'); -var isMongooseObject = utils.isMongooseObject; - -/** - * Mongoose Array constructor. - * - * ####NOTE: - * - * _Values always have to be passed to the constructor to initialize, otherwise `MongooseArray#push` will mark the array as modified._ - * - * @param {Array} values - * @param {String} path - * @param {Document} doc parent document - * @api private - * @inherits Array - * @see http://bit.ly/f6CnZU - */ - -function MongooseArray (values, path, doc) { - var arr = []; - arr.push.apply(arr, values); - arr.__proto__ = MongooseArray.prototype; - - arr._atomics = {}; - arr.validators = []; - arr._path = path; - - if (doc) { - arr._parent = doc; - arr._schema = doc.schema.path(path); - } - - return arr; -}; - -/*! - * Inherit from Array - */ - -MongooseArray.prototype = new Array; - -/** - * Stores a queue of atomic operations to perform - * - * @property _atomics - * @api private - */ - -MongooseArray.prototype._atomics; - -/** - * Parent owner document - * - * @property _parent - * @api private - */ - -MongooseArray.prototype._parent; - -/** - * Casts a member based on this arrays schema. - * - * @param {any} value - * @return value the casted value - * @api private - */ - -MongooseArray.prototype._cast = function (value) { - var owner = this._owner; - var populated = false; - var Model; - - if (this._parent) { - // if a populated array, we must cast to the same model - // instance as specified in the original query. - if (!owner) { - owner = this._owner = this._parent.ownerDocument - ? this._parent.ownerDocument() - : this._parent; - } - - populated = owner.populated(this._path, true); - } - - if (populated && null != value) { - // cast to the populated Models schema - var Model = populated.options.model; - - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if (Buffer.isBuffer(value) || - value instanceof ObjectId || !utils.isObject(value)) { - value = { _id: value }; - } - - value = new Model(value); - return this._schema.caster.cast(value, this._parent, true) - } - - return this._schema.caster.cast(value, this._parent, false) -} - -/** - * Marks this array as modified. - * - * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments) - * - * @param {EmbeddedDocument} embeddedDoc the embedded doc that invoked this method on the Array - * @param {String} embeddedPath the path which changed in the embeddedDoc - * @api private - */ - -MongooseArray.prototype._markModified = function (elem, embeddedPath) { - var parent = this._parent - , dirtyPath; - - if (parent) { - dirtyPath = this._path; - - if (arguments.length) { - if (null != embeddedPath) { - // an embedded doc bubbled up the change - dirtyPath = dirtyPath + '.' + this.indexOf(elem) + '.' + embeddedPath; - } else { - // directly set an index - dirtyPath = dirtyPath + '.' + elem; - } - } - parent.markModified(dirtyPath); - } - - return this; -}; - -/** - * Register an atomic operation with the parent. - * - * @param {Array} op operation - * @param {any} val - * @api private - */ - -MongooseArray.prototype._registerAtomic = function (op, val) { - if ('$set' == op) { - // $set takes precedence over all other ops. - // mark entire array modified. - this._atomics = { $set: val }; - return this; - } - - var atomics = this._atomics; - - // reset pop/shift after save - if ('$pop' == op && !('$pop' in atomics)) { - var self = this; - this._parent.once('save', function () { - self._popped = self._shifted = null; - }); - } - - // check for impossible $atomic combos (Mongo denies more than one - // $atomic op on a single path - if (this._atomics.$set || - Object.keys(atomics).length && !(op in atomics)) { - // a different op was previously registered. - // save the entire thing. - this._atomics = { $set: this }; - return this; - } - - if (op === '$pullAll' || op === '$pushAll' || op === '$addToSet') { - atomics[op] || (atomics[op] = []); - atomics[op] = atomics[op].concat(val); - } else if (op === '$pullDocs') { - var pullOp = atomics['$pull'] || (atomics['$pull'] = {}) - , selector = pullOp['_id'] || (pullOp['_id'] = {'$in' : [] }); - selector['$in'] = selector['$in'].concat(val); - } else { - atomics[op] = val; - } - - return this; -}; - -/** - * Depopulates stored atomic operation values as necessary for direct insertion to MongoDB. - * - * If no atomics exist, we return all array values after conversion. - * - * @return {Array} - * @method $__getAtomics - * @memberOf MongooseArray - * @api private - */ - -MongooseArray.prototype.$__getAtomics = function () { - var ret = []; - var keys = Object.keys(this._atomics); - var i = keys.length; - - if (0 === i) { - ret[0] = ['$set', this.toObject({ depopulate: 1 })]; - return ret; - } - - while (i--) { - var op = keys[i]; - var val = this._atomics[op]; - - // the atomic values which are arrays are not MongooseArrays. we - // need to convert their elements as if they were MongooseArrays - // to handle populated arrays versus DocumentArrays properly. - if (isMongooseObject(val)) { - val = val.toObject({ depopulate: 1 }); - } else if (Array.isArray(val)) { - val = this.toObject.call(val, { depopulate: 1 }); - } else if (val.valueOf) { - val = val.valueOf(); - } - - if ('$addToSet' == op) { - val = { $each: val } - } - - ret.push([op, val]); - } - - return ret; -} - -/** - * Returns the number of pending atomic operations to send to the db for this array. - * - * @api private - * @return {Number} - */ - -MongooseArray.prototype.hasAtomics = function hasAtomics () { - if (!(this._atomics && 'Object' === this._atomics.constructor.name)) { - return 0; - } - - return Object.keys(this._atomics).length; -} - -/** - * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking. - * - * @param {Object} [args...] - * @api public - */ - -MongooseArray.prototype.push = function () { - var values = [].map.call(arguments, this._cast, this) - , ret = [].push.apply(this, values); - - // $pushAll might be fibbed (could be $push). But it makes it easier to - // handle what could have been $push, $pushAll combos - this._registerAtomic('$pushAll', values); - this._markModified(); - return ret; -}; - -/** - * Pushes items to the array non-atomically. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @param {any} [args...] - * @api public - */ - -MongooseArray.prototype.nonAtomicPush = function () { - var values = [].map.call(arguments, this._cast, this) - , ret = [].push.apply(this, values); - this._registerAtomic('$set', this); - this._markModified(); - return ret; -}; - -/** - * Pops the array atomically at most one time per document `save()`. - * - * #### NOTE: - * - * _Calling this mulitple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * var popped = doc.array.$pop(); - * console.log(popped); // 3 - * console.log(doc.array); // [1,2] - * - * // no affect - * popped = doc.array.$pop(); - * console.log(doc.array); // [1,2] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $pop works again - * popped = doc.array.$pop(); - * console.log(popped); // 2 - * console.log(doc.array); // [1] - * }) - * - * @api public - * @method $pop - * @memberOf MongooseArray - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - */ - -MongooseArray.prototype.$pop = function () { - this._registerAtomic('$pop', 1); - this._markModified(); - - // only allow popping once - if (this._popped) return; - this._popped = true; - - return [].pop.call(this); -}; - -/** - * Wraps [`Array#pop`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @see MongooseArray#$pop #types_array_MongooseArray-%24pop - * @api public - */ - -MongooseArray.prototype.pop = function () { - var ret = [].pop.call(this); - this._registerAtomic('$set', this); - this._markModified(); - return ret; -}; - -/** - * Atomically shifts the array at most one time per document `save()`. - * - * ####NOTE: - * - * _Calling this mulitple times on an array before saving sends the same command as calling it once._ - * _This update is implemented using the MongoDB [$pop](http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._ - * - * doc.array = [1,2,3]; - * - * var shifted = doc.array.$shift(); - * console.log(shifted); // 1 - * console.log(doc.array); // [2,3] - * - * // no affect - * shifted = doc.array.$shift(); - * console.log(doc.array); // [2,3] - * - * doc.save(function (err) { - * if (err) return handleError(err); - * - * // we saved, now $shift works again - * shifted = doc.array.$shift(); - * console.log(shifted ); // 2 - * console.log(doc.array); // [3] - * }) - * - * @api public - * @memberOf MongooseArray - * @method $shift - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop - */ - -MongooseArray.prototype.$shift = function $shift () { - this._registerAtomic('$pop', -1); - this._markModified(); - - // only allow shifting once - if (this._shifted) return; - this._shifted = true; - - return [].shift.call(this); -}; - -/** - * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Example: - * - * doc.array = [2,3]; - * var res = doc.array.shift(); - * console.log(res) // 2 - * console.log(doc.array) // [3] - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - */ - -MongooseArray.prototype.shift = function () { - var ret = [].shift.call(this); - this._registerAtomic('$set', this); - this._markModified(); - return ret; -}; - -/** - * Pulls items from the array atomically. - * - * ####Examples: - * - * doc.array.pull(ObjectId) - * doc.array.pull({ _id: 'someId' }) - * doc.array.pull(36) - * doc.array.pull('tag 1', 'tag 2') - * - * To remove a document from a subdocument array we may pass an object with a matching `_id`. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull({ _id: 4815162342 }) // removed - * - * Or we may passing the _id directly and let mongoose take care of it. - * - * doc.subdocs.push({ _id: 4815162342 }) - * doc.subdocs.pull(4815162342); // works - * - * @param {any} [args...] - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - */ - -MongooseArray.prototype.pull = function () { - var values = [].map.call(arguments, this._cast, this) - , cur = this._parent.get(this._path) - , i = cur.length - , mem; - - while (i--) { - mem = cur[i]; - if (mem instanceof EmbeddedDocument) { - if (values.some(function (v) { return v.equals(mem); } )) { - [].splice.call(cur, i, 1); - } - } else if (~cur.indexOf.call(values, mem)) { - [].splice.call(cur, i, 1); - } - } - - if (values[0] instanceof EmbeddedDocument) { - this._registerAtomic('$pullDocs', values.map( function (v) { return v._id; } )); - } else { - this._registerAtomic('$pullAll', values); - } - - this._markModified(); - return this; -}; - -/** - * Alias of [pull](#types_array_MongooseArray-pull) - * - * @see MongooseArray#pull #types_array_MongooseArray-pull - * @see mongodb http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull - * @api public - * @memberOf MongooseArray - * @method remove - */ - -MongooseArray.prototype.remove = MongooseArray.prototype.pull; - -/** - * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - */ - -MongooseArray.prototype.splice = function splice () { - var ret, vals, i; - - if (arguments.length) { - vals = []; - for (i = 0; i < arguments.length; ++i) { - vals[i] = i < 2 - ? arguments[i] - : this._cast(arguments[i]); - } - ret = [].splice.apply(this, vals); - this._registerAtomic('$set', this); - this._markModified(); - } - - return ret; -} - -/** - * Wraps [`Array#unshift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking. - * - * ####Note: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - */ - -MongooseArray.prototype.unshift = function () { - var values = [].map.call(arguments, this._cast, this); - [].unshift.apply(this, values); - this._registerAtomic('$set', this); - this._markModified(); - return this.length; -}; - -/** - * Wraps [`Array#sort`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort) with proper change tracking. - * - * ####NOTE: - * - * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._ - * - * @api public - */ - -MongooseArray.prototype.sort = function () { - var ret = [].sort.apply(this, arguments); - this._registerAtomic('$set', this); - this._markModified(); - return ret; -} - -/** - * Adds values to the array if not already present. - * - * ####Example: - * - * console.log(doc.array) // [2,3,4] - * var added = doc.array.addToSet(4,5); - * console.log(doc.array) // [2,3,4,5] - * console.log(added) // [5] - * - * @param {any} [args...] - * @return {Array} the values that were added - * @api public - */ - -MongooseArray.prototype.addToSet = function addToSet () { - var values = [].map.call(arguments, this._cast, this) - , added = [] - , type = values[0] instanceof EmbeddedDocument ? 'doc' : - values[0] instanceof Date ? 'date' : - ''; - - values.forEach(function (v) { - var found; - switch (type) { - case 'doc': - found = this.some(function(doc){ return doc.equals(v) }); - break; - case 'date': - var val = +v; - found = this.some(function(d){ return +d === val }); - break; - default: - found = ~this.indexOf(v); - } - - if (!found) { - [].push.call(this, v); - this._registerAtomic('$addToSet', v); - this._markModified(); - [].push.call(added, v); - } - }, this); - - return added; -}; - -/** - * Sets the casted `val` at index `i` and marks the array modified. - * - * ####Example: - * - * // given documents based on the following - * var Doc = mongoose.model('Doc', new Schema({ array: [Number] })); - * - * var doc = new Doc({ array: [2,3,4] }) - * - * console.log(doc.array) // [2,3,4] - * - * doc.array.set(1,"5"); - * console.log(doc.array); // [2,5,4] // properly cast to number - * doc.save() // the change is saved - * - * // VS not using array#set - * doc.array[1] = "5"; - * console.log(doc.array); // [2,"5",4] // no casting - * doc.save() // change is not saved - * - * @return {Array} this - * @api public - */ - -MongooseArray.prototype.set = function set (i, val) { - this[i] = this._cast(val); - this._markModified(i); - return this; -} - -/** - * Returns a native js Array. - * - * @param {Object} options - * @return {Array} - * @api public - */ - -MongooseArray.prototype.toObject = function (options) { - if (options && options.depopulate) { - return this.map(function (doc) { - return doc instanceof Document - ? doc.toObject(options) - : doc - }); - } - - return this.slice(); -} - -/** - * Helper for console.log - * - * @api public - */ - -MongooseArray.prototype.inspect = function () { - return '[' + this.map(function (doc) { - return ' ' + doc; - }) + ' ]'; -}; - -/** - * Return the index of `obj` or `-1` if not found. - * - * @param {Object} obj the item to look for - * @return {Number} - * @api public - */ - -MongooseArray.prototype.indexOf = function indexOf (obj) { - if (obj instanceof ObjectId) obj = obj.toString(); - for (var i = 0, len = this.length; i < len; ++i) { - if (obj == this[i]) - return i; - } - return -1; -}; - -/*! - * Module exports. - */ - -module.exports = exports = MongooseArray; diff --git a/node_modules/mongoose/lib/types/buffer.js b/node_modules/mongoose/lib/types/buffer.js deleted file mode 100644 index bb41e4ba2..000000000 --- a/node_modules/mongoose/lib/types/buffer.js +++ /dev/null @@ -1,255 +0,0 @@ - -/*! - * Access driver. - */ - -var driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native'; - -/*! - * Module dependencies. - */ - -var Binary = require(driver + '/binary'); - -/** - * Mongoose Buffer constructor. - * - * Values always have to be passed to the constructor to initialize. - * - * @param {Buffer} value - * @param {String} encode - * @param {Number} offset - * @api private - * @inherits Buffer - * @see http://bit.ly/f6CnZU - */ - -function MongooseBuffer (value, encode, offset) { - var length = arguments.length; - var val; - - if (0 === length || null === arguments[0] || undefined === arguments[0]) { - val = 0; - } else { - val = value; - } - - var encoding; - var path; - var doc; - - if (Array.isArray(encode)) { - // internal casting - path = encode[0]; - doc = encode[1]; - } else { - encoding = encode; - } - - var buf = new Buffer(val, encoding, offset); - buf.__proto__ = MongooseBuffer.prototype; - - // make sure these internal props don't show up in Object.keys() - Object.defineProperties(buf, { - validators: { value: [] } - , _path: { value: path } - , _parent: { value: doc } - }); - - if (doc && "string" === typeof path) { - Object.defineProperty(buf, '_schema', { - value: doc.schema.path(path) - }); - } - - buf._subtype = 0; - return buf; -}; - -/*! - * Inherit from Buffer. - */ - -MongooseBuffer.prototype = new Buffer(0); - -/** - * Parent owner document - * - * @api private - * @property _parent - */ - -MongooseBuffer.prototype._parent; - -/** - * Default subtype for the Binary representing this Buffer - * - * @api private - * @property _subtype - */ - -MongooseBuffer.prototype._subtype; - -/** - * Marks this buffer as modified. - * - * @api private - */ - -MongooseBuffer.prototype._markModified = function () { - var parent = this._parent; - - if (parent) { - parent.markModified(this._path); - } - return this; -}; - -/** -* Writes the buffer. -*/ - -MongooseBuffer.prototype.write = function () { - var written = Buffer.prototype.write.apply(this, arguments); - - if (written > 0) { - this._markModified(); - } - - return written; -}; - -/** - * Copies the buffer. - * - * ####Note: - * - * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this. - * - * @return {MongooseBuffer} - * @param {Buffer} target - */ - -MongooseBuffer.prototype.copy = function (target) { - var ret = Buffer.prototype.copy.apply(this, arguments); - - if (target instanceof MongooseBuffer) { - target._markModified(); - } - - return ret; -}; - -/*! - * Compile other Buffer methods marking this buffer as modified. - */ - -;( -// node < 0.5 -'writeUInt8 writeUInt16 writeUInt32 writeInt8 writeInt16 writeInt32 ' + -'writeFloat writeDouble fill ' + -'utf8Write binaryWrite asciiWrite set ' + - -// node >= 0.5 -'writeUInt16LE writeUInt16BE writeUInt32LE writeUInt32BE ' + -'writeInt16LE writeInt16BE writeInt32LE writeInt32BE ' + -'writeFloatLE writeFloatBE writeDoubleLE writeDoubleBE' -).split(' ').forEach(function (method) { - if (!Buffer.prototype[method]) return; - MongooseBuffer.prototype[method] = new Function( - 'var ret = Buffer.prototype.'+method+'.apply(this, arguments);' + - 'this._markModified();' + - 'return ret;' - ) -}); - -/** - * Converts this buffer to its Binary type representation. - * - * ####SubTypes: - * - * var bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} [subtype] - * @return {Binary} - * @api public - */ - -MongooseBuffer.prototype.toObject = function (options) { - var subtype = 'number' == typeof options - ? options - : (this._subtype || 0); - return new Binary(this, subtype); -}; - -/** - * Determines if this buffer is equals to `other` buffer - * - * @param {Buffer} other - * @return {Boolean} - */ - -MongooseBuffer.prototype.equals = function (other) { - if (!Buffer.isBuffer(other)) { - return false; - } - - if (this.length !== other.length) { - return false; - } - - for (var i = 0; i < this.length; ++i) { - if (this[i] !== other[i]) return false; - } - - return true; -} - -/** - * Sets the subtype option and marks the buffer modified. - * - * ####SubTypes: - * - * var bson = require('bson') - * bson.BSON_BINARY_SUBTYPE_DEFAULT - * bson.BSON_BINARY_SUBTYPE_FUNCTION - * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY - * bson.BSON_BINARY_SUBTYPE_UUID - * bson.BSON_BINARY_SUBTYPE_MD5 - * bson.BSON_BINARY_SUBTYPE_USER_DEFINED - * - * doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID); - * - * @see http://bsonspec.org/#/specification - * @param {Hex} subtype - * @api public - */ - -MongooseBuffer.prototype.subtype = function (subtype) { - if ('number' != typeof subtype) { - throw new TypeError('Invalid subtype. Expected a number'); - } - - if (this._subtype != subtype) { - this._markModified(); - } - - this._subtype = subtype; -} - -/*! - * Module exports. - */ - -MongooseBuffer.Binary = Binary; - -module.exports = MongooseBuffer; diff --git a/node_modules/mongoose/lib/types/documentarray.js b/node_modules/mongoose/lib/types/documentarray.js deleted file mode 100644 index af6cec70c..000000000 --- a/node_modules/mongoose/lib/types/documentarray.js +++ /dev/null @@ -1,194 +0,0 @@ - -/*! - * Module dependencies. - */ - -var MongooseArray = require('./array') - , driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native' - , ObjectId = require(driver + '/objectid') - , ObjectIdSchema = require('../schema/objectid') - , utils = require('../utils') - , util = require('util') - , Document = require('../document') - -/** - * DocumentArray constructor - * - * @param {Array} values - * @param {String} path the path to this array - * @param {Document} doc parent document - * @api private - * @return {MongooseDocumentArray} - * @inherits MongooseArray - * @see http://bit.ly/f6CnZU - */ - -function MongooseDocumentArray (values, path, doc) { - var arr = []; - - // Values always have to be passed to the constructor to initialize, since - // otherwise MongooseArray#push will mark the array as modified to the parent. - arr.push.apply(arr, values); - arr.__proto__ = MongooseDocumentArray.prototype; - - arr._atomics = {}; - arr.validators = []; - arr._path = path; - - if (doc) { - arr._parent = doc; - arr._schema = doc.schema.path(path); - doc.on('save', arr.notify('save')); - doc.on('isNew', arr.notify('isNew')); - } - - return arr; -}; - -/*! - * Inherits from MongooseArray - */ - -MongooseDocumentArray.prototype.__proto__ = MongooseArray.prototype; - -/** - * Overrides MongooseArray#cast - * - * @api private - */ - -MongooseDocumentArray.prototype._cast = function (value) { - if (value instanceof this._schema.casterConstructor) { - if (!(value.__parent && value.__parentArray)) { - // value may have been created using array.create() - value.__parent = this._parent; - value.__parentArray = this; - } - return value; - } - - // handle cast('string') or cast(ObjectId) etc. - // only objects are permitted so we can safely assume that - // non-objects are to be interpreted as _id - if (Buffer.isBuffer(value) || - value instanceof ObjectId || !utils.isObject(value)) { - value = { _id: value }; - } - - return new this._schema.casterConstructor(value, this); -}; - -/** - * Searches array items for the first document with a matching _id. - * - * ####Example: - * - * var embeddedDoc = m.array.id(some_id); - * - * @return {EmbeddedDocument|null} the subdocuent or null if not found. - * @param {ObjectId|String|Number|Buffer} id - * @TODO cast to the _id based on schema for proper comparison - * @api public - */ - -MongooseDocumentArray.prototype.id = function (id) { - var casted - , sid - , _id - - try { - var casted_ = ObjectIdSchema.prototype.cast.call({}, id); - if (casted_) casted = String(casted_); - } catch (e) { - casted = null; - } - - for (var i = 0, l = this.length; i < l; i++) { - _id = this[i].get('_id'); - - if (_id instanceof Document) { - sid || (sid = String(id)); - if (sid == _id._id) return this[i]; - } else if (!(_id instanceof ObjectId)) { - sid || (sid = String(id)); - if (sid == _id) return this[i]; - } else if (casted == _id) { - return this[i]; - } - } - - return null; -}; - -/** - * Returns a native js Array of plain js objects - * - * ####NOTE: - * - * _Each sub-document is converted to a plain object by calling its `#toObject` method._ - * - * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion - * @return {Array} - * @api public - */ - -MongooseDocumentArray.prototype.toObject = function (options) { - return this.map(function (doc) { - return doc && doc.toObject(options) || null; - }); -}; - -/** - * Helper for console.log - * - * @api public - */ - -MongooseDocumentArray.prototype.inspect = function () { - return '[' + this.map(function (doc) { - if (doc) { - return doc.inspect - ? doc.inspect() - : util.inspect(doc) - } - return 'null' - }).join('\n') + ']'; -}; - -/** - * Creates a subdocument casted to this schema. - * - * This is the same subdocument constructor used for casting. - * - * @param {Object} obj the value to cast to this arrays SubDocument schema - * @api public - */ - -MongooseDocumentArray.prototype.create = function (obj) { - return new this._schema.casterConstructor(obj); -} - -/** - * Creates a fn that notifies all child docs of `event`. - * - * @param {String} event - * @return {Function} - * @api private - */ - -MongooseDocumentArray.prototype.notify = function notify (event) { - var self = this; - return function notify (val) { - var i = self.length; - while (i--) { - if (!self[i]) continue; - self[i].emit(event, val); - } - } -} - -/*! - * Module exports. - */ - -module.exports = MongooseDocumentArray; diff --git a/node_modules/mongoose/lib/types/embedded.js b/node_modules/mongoose/lib/types/embedded.js deleted file mode 100644 index a1eca2f53..000000000 --- a/node_modules/mongoose/lib/types/embedded.js +++ /dev/null @@ -1,267 +0,0 @@ -/*! - * Module dependencies. - */ - -var Document = require('../document') - , inspect = require('util').inspect; - -/** - * EmbeddedDocument constructor. - * - * @param {Object} obj js object returned from the db - * @param {MongooseDocumentArray} parentArr the parent array of this document - * @param {Boolean} skipId - * @inherits Document - * @api private - */ - -function EmbeddedDocument (obj, parentArr, skipId, fields) { - if (parentArr) { - this.__parentArray = parentArr; - this.__parent = parentArr._parent; - } else { - this.__parentArray = undefined; - this.__parent = undefined; - } - - Document.call(this, obj, fields, skipId); - - var self = this; - this.on('isNew', function (val) { - self.isNew = val; - }); -}; - -/*! - * Inherit from Document - */ - -EmbeddedDocument.prototype.__proto__ = Document.prototype; - -/** - * Marks the embedded doc modified. - * - * ####Example: - * - * var doc = blogpost.comments.id(hexstring); - * doc.mixed.type = 'changed'; - * doc.markModified('mixed.type'); - * - * @param {String} path the path which changed - * @api public - */ - -EmbeddedDocument.prototype.markModified = function (path) { - if (!this.__parentArray) return; - - this.$__.activePaths.modify(path); - - if (this.isNew) { - // Mark the WHOLE parent array as modified - // if this is a new document (i.e., we are initializing - // a document), - this.__parentArray._markModified(); - } else - this.__parentArray._markModified(this, path); -}; - -/** - * Used as a stub for [hooks.js](https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3) - * - * ####NOTE: - * - * _This is a no-op. Does not actually save the doc to the db._ - * - * @param {Function} [fn] - * @return {EmbeddedDocument} this - * @api private - */ - -EmbeddedDocument.prototype.save = function(fn) { - if (fn) - fn(null); - return this; -}; - -/** - * Removes the subdocument from its parent array. - * - * @param {Function} [fn] - * @api public - */ - -EmbeddedDocument.prototype.remove = function (fn) { - if (!this.__parentArray) return this; - - var _id; - if (!this.willRemove) { - _id = this._doc._id; - if (!_id) { - throw new Error('For your own good, Mongoose does not know ' + - 'how to remove an EmbeddedDocument that has no _id'); - } - this.__parentArray.pull({ _id: _id }); - this.willRemove = true; - registerRemoveListener(this); - } - - if (fn) - fn(null); - - return this; -}; - -/*! - * Registers remove event listeners for triggering - * on subdocuments. - * - * @param {EmbeddedDocument} sub - * @api private - */ - -function registerRemoveListener (sub) { - var owner = sub.ownerDocument(); - - owner.on('save', emitRemove); - owner.on('remove', emitRemove); - - function emitRemove () { - owner.removeListener('save', emitRemove); - owner.removeListener('remove', emitRemove); - sub.emit('remove', sub); - owner = sub = emitRemove = null; - }; -}; - -/** - * Override #update method of parent documents. - * @api private - */ - -EmbeddedDocument.prototype.update = function () { - throw new Error('The #update method is not available on EmbeddedDocuments'); -} - -/** - * Helper for console.log - * - * @api public - */ - -EmbeddedDocument.prototype.inspect = function () { - return inspect(this.toObject()); -}; - -/** - * Marks a path as invalid, causing validation to fail. - * - * @param {String} path the field to invalidate - * @param {String|Error} err error which states the reason `path` was invalid - * @return {Boolean} - * @api public - */ - -EmbeddedDocument.prototype.invalidate = function (path, err, val, first) { - if (!this.__parent) { - var msg = 'Unable to invalidate a subdocument that has not been added to an array.' - throw new Error(msg); - } - - var index = this.__parentArray.indexOf(this); - var parentPath = this.__parentArray._path; - var fullPath = [parentPath, index, path].join('.'); - - // sniffing arguments: - // need to check if user passed a value to keep - // our error message clean. - if (2 < arguments.length) { - this.__parent.invalidate(fullPath, err, val); - } else { - this.__parent.invalidate(fullPath, err); - } - - if (first) - this.$__.validationError = this.ownerDocument().$__.validationError; - return true; -} - -/** - * Returns the top level document of this sub-document. - * - * @return {Document} - */ - -EmbeddedDocument.prototype.ownerDocument = function () { - if (this.$__.ownerDocument) { - return this.$__.ownerDocument; - } - - var parent = this.__parent; - if (!parent) return this; - - while (parent.__parent) { - parent = parent.__parent; - } - - return this.$__.ownerDocument = parent; -} - -/** - * Returns the full path to this document. If optional `path` is passed, it is appended to the full path. - * - * @param {String} [path] - * @return {String} - * @api private - * @method $__fullPath - * @memberOf EmbeddedDocument - */ - -EmbeddedDocument.prototype.$__fullPath = function (path) { - if (!this.$__.fullPath) { - var parent = this; - if (!parent.__parent) return path; - - var paths = []; - while (parent.__parent) { - paths.unshift(parent.__parentArray._path); - parent = parent.__parent; - } - - this.$__.fullPath = paths.join('.'); - - if (!this.$__.ownerDocument) { - // optimization - this.$__.ownerDocument = parent; - } - } - - return path - ? this.$__.fullPath + '.' + path - : this.$__.fullPath; -} - -/** - * Returns this sub-documents parent document. - * - * @api public - */ - -EmbeddedDocument.prototype.parent = function () { - return this.__parent; -} - -/** - * Returns this sub-documents parent array. - * - * @api public - */ - -EmbeddedDocument.prototype.parentArray = function () { - return this.__parentArray; -} - -/*! - * Module exports. - */ - -module.exports = EmbeddedDocument; diff --git a/node_modules/mongoose/lib/types/index.js b/node_modules/mongoose/lib/types/index.js deleted file mode 100644 index e6a9901e6..000000000 --- a/node_modules/mongoose/lib/types/index.js +++ /dev/null @@ -1,13 +0,0 @@ - -/*! - * Module exports. - */ - -exports.Array = require('./array'); -exports.Buffer = require('./buffer'); - -exports.Document = // @deprecate -exports.Embedded = require('./embedded'); - -exports.DocumentArray = require('./documentarray'); -exports.ObjectId = require('./objectid'); diff --git a/node_modules/mongoose/lib/types/objectid.js b/node_modules/mongoose/lib/types/objectid.js deleted file mode 100644 index 44ad43f49..000000000 --- a/node_modules/mongoose/lib/types/objectid.js +++ /dev/null @@ -1,43 +0,0 @@ - -/*! - * Access driver. - */ - -var driver = global.MONGOOSE_DRIVER_PATH || '../drivers/node-mongodb-native'; - -/** - * ObjectId type constructor - * - * ####Example - * - * var id = new mongoose.Types.ObjectId; - * - * @constructor ObjectId - */ - -var ObjectId = require(driver + '/objectid'); -module.exports = ObjectId; - -/** - * Creates an ObjectId from `str` - * - * @param {ObjectId|HexString} str - * @static fromString - * @receiver ObjectId - * @return {ObjectId} - * @api private - */ - -ObjectId.fromString; - -/** - * Converts `oid` to a string. - * - * @param {ObjectId} oid ObjectId instance - * @static toString - * @receiver ObjectId - * @return {String} - * @api private - */ - -ObjectId.toString; diff --git a/node_modules/mongoose/lib/utils.js b/node_modules/mongoose/lib/utils.js deleted file mode 100644 index 95de06b56..000000000 --- a/node_modules/mongoose/lib/utils.js +++ /dev/null @@ -1,684 +0,0 @@ -/*! - * Module dependencies. - */ - -var ReadPref = require('mongodb').ReadPreference - , ObjectId = require('./types/objectid') - , cloneRegExp = require('regexp-clone') - , sliced = require('sliced') - , mpath = require('mpath') - , ms = require('ms') - , MongooseBuffer - , MongooseArray - , Document - -/*! - * Produces a collection name from model `name`. - * - * @param {String} name a model name - * @return {String} a collection name - * @api private - */ - -exports.toCollectionName = function (name, options) { - options = options || {}; - if ('system.profile' === name) return name; - if ('system.indexes' === name) return name; - if (options.pluralization === false) return name; - return pluralize(name.toLowerCase()); -}; - -/** - * Pluralization rules. - * - * These rules are applied while processing the argument to `toCollectionName`. - * - * @deprecated remove in 4.x gh-1350 - */ - -exports.pluralization = [ - [/(m)an$/gi, '$1en'], - [/(pe)rson$/gi, '$1ople'], - [/(child)$/gi, '$1ren'], - [/^(ox)$/gi, '$1en'], - [/(ax|test)is$/gi, '$1es'], - [/(octop|vir)us$/gi, '$1i'], - [/(alias|status)$/gi, '$1es'], - [/(bu)s$/gi, '$1ses'], - [/(buffal|tomat|potat)o$/gi, '$1oes'], - [/([ti])um$/gi, '$1a'], - [/sis$/gi, 'ses'], - [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], - [/(hive)$/gi, '$1s'], - [/([^aeiouy]|qu)y$/gi, '$1ies'], - [/(x|ch|ss|sh)$/gi, '$1es'], - [/(matr|vert|ind)ix|ex$/gi, '$1ices'], - [/([m|l])ouse$/gi, '$1ice'], - [/(quiz)$/gi, '$1zes'], - [/s$/gi, 's'], - [/([^a-z])$/, '$1'], - [/$/gi, 's'] -]; -var rules = exports.pluralization; - -/** - * Uncountable words. - * - * These words are applied while processing the argument to `toCollectionName`. - * @api public - */ - -exports.uncountables = [ - 'advice', - 'energy', - 'excretion', - 'digestion', - 'cooperation', - 'health', - 'justice', - 'labour', - 'machinery', - 'equipment', - 'information', - 'pollution', - 'sewage', - 'paper', - 'money', - 'species', - 'series', - 'rain', - 'rice', - 'fish', - 'sheep', - 'moose', - 'deer', - 'news', - 'expertise', - 'status', - 'media' -]; -var uncountables = exports.uncountables; - -/*! - * Pluralize function. - * - * @author TJ Holowaychuk (extracted from _ext.js_) - * @param {String} string to pluralize - * @api private - */ - -function pluralize (str) { - var rule, found; - if (!~uncountables.indexOf(str.toLowerCase())){ - found = rules.filter(function(rule){ - return str.match(rule[0]); - }); - if (found[0]) return str.replace(found[0][0], found[0][1]); - } - return str; -}; - -/*! - * Determines if `a` and `b` are deep equal. - * - * Modified from node/lib/assert.js - * - * @param {any} a a value to compare to `b` - * @param {any} b a value to compare to `a` - * @return {Boolean} - * @api private - */ - -exports.deepEqual = function deepEqual (a, b) { - if (a === b) return true; - - if (a instanceof Date && b instanceof Date) - return a.getTime() === b.getTime(); - - if (a instanceof ObjectId && b instanceof ObjectId) { - return a.toString() === b.toString(); - } - - if (a instanceof RegExp && b instanceof RegExp) { - return a.source == b.source && - a.ignoreCase == b.ignoreCase && - a.multiline == b.multiline && - a.global == b.global; - } - - if (typeof a !== 'object' && typeof b !== 'object') - return a == b; - - if (a === null || b === null || a === undefined || b === undefined) - return false - - if (a.prototype !== b.prototype) return false; - - // Handle MongooseNumbers - if (a instanceof Number && b instanceof Number) { - return a.valueOf() === b.valueOf(); - } - - if (Buffer.isBuffer(a)) { - return exports.buffer.areEqual(a, b); - } - - if (isMongooseObject(a)) a = a.toObject(); - if (isMongooseObject(b)) b = b.toObject(); - - try { - var ka = Object.keys(a), - kb = Object.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!deepEqual(a[key], b[key])) return false; - } - - return true; -}; - -/*! - * Object clone with Mongoose natives support. - * - * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. - * - * Functions are never cloned. - * - * @param {Object} obj the object to clone - * @param {Object} options - * @return {Object} the cloned object - * @api private - */ - -exports.clone = function clone (obj, options) { - if (obj === undefined || obj === null) - return obj; - - if (Array.isArray(obj)) - return cloneArray(obj, options); - - if (isMongooseObject(obj)) { - if (options && options.json && 'function' === typeof obj.toJSON) { - return obj.toJSON(options); - } else { - return obj.toObject(options); - } - } - - if (obj.constructor) { - switch (obj.constructor.name) { - case 'Object': - return cloneObject(obj, options); - case 'Date': - return new obj.constructor(+obj); - case 'RegExp': - return cloneRegExp(obj); - default: - // ignore - break; - } - } - - if (obj instanceof ObjectId) - return new ObjectId(obj.id); - - if (!obj.constructor && exports.isObject(obj)) { - // object created with Object.create(null) - return cloneObject(obj, options); - } - - if (obj.valueOf) - return obj.valueOf(); -}; -var clone = exports.clone; - -/*! - * ignore - */ - -function cloneObject (obj, options) { - var retainKeyOrder = options && options.retainKeyOrder - , minimize = options && options.minimize - , ret = {} - , hasKeys - , keys - , val - , k - , i - - if (retainKeyOrder) { - for (k in obj) { - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - } else { - // faster - - keys = Object.keys(obj); - i = keys.length; - - while (i--) { - k = keys[i]; - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - if (!hasKeys) hasKeys = true; - ret[k] = val; - } - } - } - - return minimize - ? hasKeys && ret - : ret; -}; - -function cloneArray (arr, options) { - var ret = []; - for (var i = 0, l = arr.length; i < l; i++) - ret.push(clone(arr[i], options)); - return ret; -}; - -/*! - * Shallow copies defaults into options. - * - * @param {Object} defaults - * @param {Object} options - * @return {Object} the merged object - * @api private - */ - -exports.options = function (defaults, options) { - var keys = Object.keys(defaults) - , i = keys.length - , k ; - - options = options || {}; - - while (i--) { - k = keys[i]; - if (!(k in options)) { - options[k] = defaults[k]; - } - } - - return options; -}; - -/*! - * Generates a random string - * - * @api private - */ - -exports.random = function () { - return Math.random().toString().substr(3); -}; - -/*! - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -exports.merge = function merge (to, from) { - var keys = Object.keys(from) - , i = keys.length - , key; - - while (i--) { - key = keys[i]; - if ('undefined' === typeof to[key]) { - to[key] = from[key]; - } else if (exports.isObject(from[key])) { - merge(to[key], from[key]); - } - } -}; - -/*! - * toString helper - */ - -var toString = Object.prototype.toString; - -/*! - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @api private - * @return {Boolean} - */ - -exports.isObject = function (arg) { - return '[object Object]' == toString.call(arg); -} - -/*! - * A faster Array.prototype.slice.call(arguments) alternative - * @api private - */ - -exports.args = sliced; - -/*! - * process.nextTick helper. - * - * Wraps `callback` in a try/catch + nextTick. - * - * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. - * - * @param {Function} callback - * @api private - */ - -exports.tick = function tick (callback) { - if ('function' !== typeof callback) return; - return function () { - try { - callback.apply(this, arguments); - } catch (err) { - // only nextTick on err to get out of - // the event loop and avoid state corruption. - process.nextTick(function () { - throw err; - }); - } - } -} - -/*! - * Returns if `v` is a mongoose object that has a `toObject()` method we can use. - * - * This is for compatibility with libs like Date.js which do foolish things to Natives. - * - * @param {any} v - * @api private - */ - -exports.isMongooseObject = function (v) { - Document || (Document = require('./document')); - MongooseArray || (MongooseArray = require('./types').Array); - MongooseBuffer || (MongooseBuffer = require('./types').Buffer); - - return v instanceof Document || - v instanceof MongooseArray || - v instanceof MongooseBuffer -} -var isMongooseObject = exports.isMongooseObject; - -/*! - * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. - * - * @param {Object} object - * @api private - */ - -exports.expires = function expires (object) { - if (!(object && 'Object' == object.constructor.name)) return; - if (!('expires' in object)) return; - - var when; - if ('string' != typeof object.expires) { - when = object.expires; - } else { - when = Math.round(ms(object.expires) / 1000); - } - object.expireAfterSeconds = when; - delete object.expires; -} - -/*! - * Converts arguments to ReadPrefs the driver - * can understand. - * - * @TODO move this into the driver layer - * @param {String|Array} pref - * @param {Array} [tags] - */ - -exports.readPref = function readPref (pref, tags) { - if (Array.isArray(pref)) { - tags = pref[1]; - pref = pref[0]; - } - - switch (pref) { - case 'p': - pref = 'primary'; - break; - case 'pp': - pref = 'primaryPreferred'; - break; - case 's': - pref = 'secondary'; - break; - case 'sp': - pref = 'secondaryPreferred'; - break; - case 'n': - pref = 'nearest'; - break; - } - - return new ReadPref(pref, tags); -} - -/*! - * Populate options constructor - */ - -function PopulateOptions (path, select, match, options, model) { - this.path = path; - this.match = match; - this.select = select; - this.options = options; - this.model = model; - this._docs = {}; -} - -// make it compatible with utils.clone -PopulateOptions.prototype.constructor = Object; - -// expose -exports.PopulateOptions = PopulateOptions; - -/*! - * populate helper - */ - -exports.populate = function populate (path, select, model, match, options) { - // The order of select/conditions args is opposite Model.find but - // necessary to keep backward compatibility (select could be - // an array, string, or object literal). - - // might have passed an object specifying all arguments - if (1 === arguments.length) { - if (path instanceof PopulateOptions) { - return [path]; - } - - if (Array.isArray(path)) { - return path.map(function(o){ - return exports.populate(o)[0]; - }); - } - - if (exports.isObject(path)) { - match = path.match; - options = path.options; - select = path.select; - model = path.model; - path = path.path; - } - } else if ('string' !== typeof model) { - options = match; - match = model; - model = undefined; - } - - if ('string' != typeof path) { - throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); - } - - var ret = []; - var paths = path.split(' '); - for (var i = 0; i < paths.length; ++i) { - ret.push(new PopulateOptions(paths[i], select, match, options, model)); - } - - return ret; -} - -/*! - * Return the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Object} obj - */ - -exports.getValue = function (path, obj, map) { - return mpath.get(path, obj, '_doc', map); -} - -/*! - * Sets the value of `obj` at the given `path`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} obj - */ - -exports.setValue = function (path, val, obj, map) { - mpath.set(path, val, obj, '_doc', map); -} - -/*! - * Returns an array of values from object `o`. - * - * @param {Object} o - * @return {Array} - * @private - */ - -exports.object = {}; -exports.object.vals = function vals (o) { - var keys = Object.keys(o) - , i = keys.length - , ret = []; - - while (i--) { - ret.push(o[keys[i]]); - } - - return ret; -} - -/*! - * @see exports.options - */ - -exports.object.shallowCopy = exports.options; - -/*! - * Safer helper for hasOwnProperty checks - * - * @param {Object} obj - * @param {String} prop - */ - -var hop = Object.prototype.hasOwnProperty; -exports.object.hasOwnProperty = function (obj, prop) { - return hop.call(obj, prop); -} - -/*! - * Determine if `val` is null or undefined - * - * @return {Boolean} - */ - -exports.isNullOrUndefined = function (val) { - return null == val -} - -/*! - * ignore - */ - -exports.array = {}; - -/*! - * Flattens an array. - * - * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] - * - * @param {Array} arr - * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results. - * @return {Array} - * @private - */ - -exports.array.flatten = function flatten (arr, filter, ret) { - ret || (ret = []); - - arr.forEach(function (item) { - if (Array.isArray(item)) { - flatten(item, filter, ret); - } else { - if (!filter || filter(item)) { - ret.push(item); - } - } - }); - - return ret; -} - -/*! - * Determines if two buffers are equal. - * - * @param {Buffer} a - * @param {Object} b - */ - -exports.buffer = {}; -exports.buffer.areEqual = function (a, b) { - if (!Buffer.isBuffer(a)) return false; - if (!Buffer.isBuffer(b)) return false; - if (a.length !== b.length) return false; - for (var i = 0, len = a.length; i < len; ++i) { - if (a[i] !== b[i]) return false; - } - return true; -} - diff --git a/node_modules/mongoose/lib/virtualtype.js b/node_modules/mongoose/lib/virtualtype.js deleted file mode 100644 index 819ac10b9..000000000 --- a/node_modules/mongoose/lib/virtualtype.js +++ /dev/null @@ -1,103 +0,0 @@ - -/** - * VirtualType constructor - * - * This is what mongoose uses to define virtual attributes via `Schema.prototype.virtual`. - * - * ####Example: - * - * var fullname = schema.virtual('fullname'); - * fullname instanceof mongoose.VirtualType // true - * - * @parma {Object} options - * @api public - */ - -function VirtualType (options, name) { - this.path = name; - this.getters = []; - this.setters = []; - this.options = options || {}; -} - -/** - * Defines a getter. - * - * ####Example: - * - * var virtual = schema.virtual('fullname'); - * virtual.get(function () { - * return this.name.first + ' ' + this.name.last; - * }); - * - * @param {Function} fn - * @return {VirtualType} this - * @api public - */ - -VirtualType.prototype.get = function (fn) { - this.getters.push(fn); - return this; -}; - -/** - * Defines a setter. - * - * ####Example: - * - * var virtual = schema.virtual('fullname'); - * virtual.set(function (v) { - * var parts = v.split(' '); - * this.name.first = parts[0]; - * this.name.last = parts[1]; - * }); - * - * @param {Function} fn - * @return {VirtualType} this - * @api public - */ - -VirtualType.prototype.set = function (fn) { - this.setters.push(fn); - return this; -}; - -/** - * Applies getters to `value` using optional `scope`. - * - * @param {Object} value - * @param {Object} scope - * @return {any} the value after applying all getters - * @api public - */ - -VirtualType.prototype.applyGetters = function (value, scope) { - var v = value; - for (var l = this.getters.length - 1; l >= 0; l--) { - v = this.getters[l].call(scope, v, this); - } - return v; -}; - -/** - * Applies setters to `value` using optional `scope`. - * - * @param {Object} value - * @param {Object} scope - * @return {any} the value after applying all setters - * @api public - */ - -VirtualType.prototype.applySetters = function (value, scope) { - var v = value; - for (var l = this.setters.length - 1; l >= 0; l--) { - v = this.setters[l].call(scope, v, this); - } - return v; -}; - -/*! - * exports - */ - -module.exports = VirtualType; diff --git a/node_modules/mongoose/node_modules/hooks/.npmignore b/node_modules/mongoose/node_modules/hooks/.npmignore deleted file mode 100644 index 96e29a84c..000000000 --- a/node_modules/mongoose/node_modules/hooks/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -**.swp -node_modules diff --git a/node_modules/mongoose/node_modules/hooks/Makefile b/node_modules/mongoose/node_modules/hooks/Makefile deleted file mode 100644 index 1db5d6538..000000000 --- a/node_modules/mongoose/node_modules/hooks/Makefile +++ /dev/null @@ -1,9 +0,0 @@ -test: - @NODE_ENV=test ./node_modules/expresso/bin/expresso \ - $(TESTFLAGS) \ - ./test.js - -test-cov: - @TESTFLAGS=--cov $(MAKE) test - -.PHONY: test test-cov diff --git a/node_modules/mongoose/node_modules/hooks/README.md b/node_modules/mongoose/node_modules/hooks/README.md deleted file mode 100644 index af90a4859..000000000 --- a/node_modules/mongoose/node_modules/hooks/README.md +++ /dev/null @@ -1,306 +0,0 @@ -hooks -============ - -Add pre and post middleware hooks to your JavaScript methods. - -## Installation - npm install hooks - -## Motivation -Suppose you have a JavaScript object with a `save` method. - -It would be nice to be able to declare code that runs before `save` and after `save`. -For example, you might want to run validation code before every `save`, -and you might want to dispatch a job to a background job queue after `save`. - -One might have an urge to hard code this all into `save`, but that turns out to -couple all these pieces of functionality (validation, save, and job creation) more -tightly than is necessary. For example, what if someone does not want to do background -job creation after the logical save? - -It is nicer to tack on functionality using what we call `pre` and `post` hooks. These -are functions that you define and that you direct to execute before or after particular -methods. - -## Example -We can use `hooks` to add validation and background jobs in the following way: - - var hooks = require('hooks') - , Document = require('./path/to/some/document/constructor'); - - // Add hooks' methods: `hook`, `pre`, and `post` - for (var k in hooks) { - Document[k] = hooks[k]; - } - - // Define a new method that is able to invoke pre and post middleware - Document.hook('save', Document.prototype.save); - - // Define a middleware function to be invoked before 'save' - Document.pre('save', function validate (next) { - // The `this` context inside of `pre` and `post` functions - // is the Document instance - if (this.isValid()) next(); // next() passes control to the next middleware - // or to the target method itself - else next(new Error("Invalid")); // next(error) invokes an error callback - }); - - // Define a middleware function to be invoked after 'save' - Document.post('save', function createJob () { - this.sendToBackgroundQueue(); - }); - -If you already have defined `Document.prototype` methods for which you want pres and posts, -then you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)` -or `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]` -so that it plays well with `hooks`. An equivalent way to implement the previous example is: - -```javascript -var hooks = require('hooks') - , Document = require('./path/to/some/document/constructor'); - -// Add hooks' methods: `hook`, `pre`, and `post` -for (var k in hooks) { - Document[k] = hooks[k]; -} - -Document.prototype.save = function () { - // ... -}; - -// Define a middleware function to be invoked before 'save' -Document.pre('save', function validate (next) { - // The `this` context inside of `pre` and `post` functions - // is the Document instance - if (this.isValid()) next(); // next() passes control to the next middleware - // or to the target method itself - else next(new Error("Invalid")); // next(error) invokes an error callback -}); - -// Define a middleware function to be invoked after 'save' -Document.post('save', function createJob () { - this.sendToBackgroundQueue(); -}); -``` - -## Pres and Posts as Middleware -We structure pres and posts as middleware to give you maximum flexibility: - -1. You can define **multiple** pres (or posts) for a single method. -2. These pres (or posts) are then executed as a chain of methods. -3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid. - -## Defining multiple pres (or posts) -`pre` is chainable, so you can define multiple pres via: - Document.pre('save', function (next, halt) { - console.log("hello"); - }).pre('save', function (next, halt) { - console.log("world"); - }); - -As soon as one pre finishes executing, the next one will be invoked, and so on. - -## Error Handling -You can define a default error handler by passing a 2nd function as the 3rd argument to `hook`: - Document.hook('set', function (path, val) { - this[path] = val; - }, function (err) { - // Handler the error here - console.error(err); - }); - -Then, we can pass errors to this handler from a pre or post middleware function: - Document.pre('set', function (next, path, val) { - next(new Error()); - }); - -If you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`. - -The default error handler can be over-rided on a per method invocation basis. - -If the main method that you are surrounding with pre and post middleware expects its last argument to be a function -with callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default -error handler you may have set up. - -```javascript -Document.hook('save', function (callback) { - // Save logic goes here - ... -}); - -var doc = new Document(); -doc.save( function (err, saved) { - // We can pass err via `next` in any of our pre or post middleware functions - if (err) console.error(err); - - // Rest of callback logic follows ... -}); -``` - -## Mutating Arguments via Middleware -`pre` and `post` middleware can also accept the intended arguments for the method -they augment. This is useful if you want to mutate the arguments before passing -them along to the next middleware and eventually pass a mutated arguments list to -the main method itself. - -As a simple example, let's define a method `set` that just sets a key, value pair. -If we want to namespace the key, we can do so by adding a `pre` middleware hook -that runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`: - - Document.hook('set', function (key, val) { - this[key] = val; - }); - Document.pre('set', function (next, key, val) { - next('namespace-' + key, val); - }); - var doc = new Document(); - doc.set('hello', 'world'); - console.log(doc.hello); // undefined - console.log(doc['namespace-hello']); // 'world' - -As you can see above, we pass arguments via `next`. - -If you are not mutating the arguments, then you can pass zero arguments -to `next`, and the next middleware function will still have access -to the arguments. - - Document.hook('set', function (key, val) { - this[key] = val; - }); - Document.pre('set', function (next, key, val) { - // I have access to key and val here - next(); // We don't need to pass anything to next - }); - Document.pre('set', function (next, key, val) { - // And I still have access to the original key and val here - next(); - }); - -Finally, you can add arguments that downstream middleware can also see: - - // Note that in the definition of `set`, there is no 3rd argument, options - Document.hook('set', function (key, val) { - // But... - var options = arguments[2]; // ...I have access to an options argument - // because of pre function pre2 (defined below) - console.log(options); // '{debug: true}' - this[key] = val; - }); - Document.pre('set', function pre1 (next, key, val) { - // I only have access to key and val arguments - console.log(arguments.length); // 3 - next(key, val, {debug: true}); - }); - Document.pre('set', function pre2 (next, key, val, options) { - console.log(arguments.length); // 4 - console.log(options); // '{ debug: true}' - next(); - }); - Document.pre('set', function pre3 (next, key, val, options) { - // I still have access to key, val, AND the options argument introduced via the preceding middleware - console.log(arguments.length); // 4 - console.log(options); // '{ debug: true}' - next(); - }); - - var doc = new Document() - doc.set('hey', 'there'); - -## Parallel `pre` middleware - -All middleware up to this point has been "serial" middleware -- i.e., middleware whose logic -is executed as a serial chain. - -Some scenarios call for parallel middleware -- i.e., middleware that can wait for several -asynchronous services at once to respond. - -For instance, you may only want to save a Document only after you have checked -that the Document is valid according to two different remote services. - -We accomplish asynchronous middleware by adding a second kind of flow control callback -(the only flow control callback so far has been `next`), called `done`. - -- `next` passes control to the next middleware in the chain -- `done` keeps track of how many parallel middleware have invoked `done` and passes - control to the target method when ALL parallel middleware have invoked `done`. If - you pass an `Error` to `done`, then the error is handled, and the main method that is - wrapped by pres and posts will not get invoked. - -We declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre` -definition method. - -We illustrate via the parallel validation example mentioned above: - - Document.hook('save', function targetFn (callback) { - // Save logic goes here - // ... - // This only gets run once the two `done`s are both invoked via preOne and preTwo. - }); - - // true marks this as parallel middleware - Document.pre('save', true, function preOne (next, doneOne, callback) { - remoteServiceOne.validate(this.serialize(), function (err, isValid) { - // The code in here will probably be run after the `next` below this block - // and could possibly be run after the console.log("Hola") in `preTwo - if (err) return doneOne(err); - if (isValid) doneOne(); - }); - next(); // Pass control to the next middleware - }); - - // We will suppose that we need 2 different remote services to validate our document - Document.pre('save', true, function preTwo (next, doneTwo, callback) { - remoteServiceTwo.validate(this.serialize(), function (err, isValid) { - if (err) return doneTwo(err); - if (isValid) doneTwo(); - }); - next(); - }); - - // While preOne and preTwo are parallel, preThree is a serial pre middleware - Document.pre('save', function preThree (next, callback) { - next(); - }); - - var doc = new Document(); - doc.save( function (err, doc) { - // Do stuff with the saved doc here... - }); - -In the above example, flow control may happen in the following way: - -(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn - -So what's happening is that: - -1. You call `doc.save(...)` -2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware. -3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware. -4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services. -5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo. -6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne. -7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic). - -## Removing Pres - -You can remove a particular pre associated with a hook: - - Document.pre('set', someFn); - Document.removePre('set', someFn); - -And you can also remove all pres associated with a hook: - Document.removePre('set'); // Removes all declared `pre`s on the hook 'set' - -## Tests -To run the tests: - make test - -### Contributors -- [Brian Noguchi](https://github.com/bnoguchi) - -### License -MIT License - ---- -### Author -Brian Noguchi diff --git a/node_modules/mongoose/node_modules/hooks/hooks.alt.js b/node_modules/mongoose/node_modules/hooks/hooks.alt.js deleted file mode 100644 index 6ced35756..000000000 --- a/node_modules/mongoose/node_modules/hooks/hooks.alt.js +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Hooks are useful if we want to add a method that automatically has `pre` and `post` hooks. - * For example, it would be convenient to have `pre` and `post` hooks for `save`. - * _.extend(Model, mixins.hooks); - * Model.hook('save', function () { - * console.log('saving'); - * }); - * Model.pre('save', function (next, done) { - * console.log('about to save'); - * next(); - * }); - * Model.post('save', function (next, done) { - * console.log('saved'); - * next(); - * }); - * - * var m = new Model(); - * m.save(); - * // about to save - * // saving - * // saved - */ - -// TODO Add in pre and post skipping options -module.exports = { - /** - * Declares a new hook to which you can add pres and posts - * @param {String} name of the function - * @param {Function} the method - * @param {Function} the error handler callback - */ - hook: function (name, fn, err) { - if (arguments.length === 1 && typeof name === 'object') { - for (var k in name) { // `name` is a hash of hookName->hookFn - this.hook(k, name[k]); - } - return; - } - - if (!err) err = fn; - - var proto = this.prototype || this - , pres = proto._pres = proto._pres || {} - , posts = proto._posts = proto._posts || {}; - pres[name] = pres[name] || []; - posts[name] = posts[name] || []; - - function noop () {} - - proto[name] = function () { - var self = this - , pres = this._pres[name] - , posts = this._posts[name] - , numAsyncPres = 0 - , hookArgs = [].slice.call(arguments) - , preChain = pres.map( function (pre, i) { - var wrapper = function () { - if (arguments[0] instanceof Error) - return err(arguments[0]); - if (numAsyncPres) { - // arguments[1] === asyncComplete - if (arguments.length) - hookArgs = [].slice.call(arguments, 2); - pre.apply(self, - [ preChain[i+1] || allPresInvoked, - asyncComplete - ].concat(hookArgs) - ); - } else { - if (arguments.length) - hookArgs = [].slice.call(arguments); - pre.apply(self, - [ preChain[i+1] || allPresDone ].concat(hookArgs)); - } - }; // end wrapper = function () {... - if (wrapper.isAsync = pre.isAsync) - numAsyncPres++; - return wrapper; - }); // end posts.map(...) - function allPresInvoked () { - if (arguments[0] instanceof Error) - err(arguments[0]); - } - - function allPresDone () { - if (arguments[0] instanceof Error) - return err(arguments[0]); - if (arguments.length) - hookArgs = [].slice.call(arguments); - fn.apply(self, hookArgs); - var postChain = posts.map( function (post, i) { - var wrapper = function () { - if (arguments[0] instanceof Error) - return err(arguments[0]); - if (arguments.length) - hookArgs = [].slice.call(arguments); - post.apply(self, - [ postChain[i+1] || noop].concat(hookArgs)); - }; // end wrapper = function () {... - return wrapper; - }); // end posts.map(...) - if (postChain.length) postChain[0](); - } - - if (numAsyncPres) { - complete = numAsyncPres; - function asyncComplete () { - if (arguments[0] instanceof Error) - return err(arguments[0]); - --complete || allPresDone.call(this); - } - } - (preChain[0] || allPresDone)(); - }; - - return this; - }, - - pre: function (name, fn, isAsync) { - var proto = this.prototype - , pres = proto._pres = proto._pres || {}; - if (fn.isAsync = isAsync) { - this.prototype[name].numAsyncPres++; - } - (pres[name] = pres[name] || []).push(fn); - return this; - }, - post: function (name, fn, isAsync) { - var proto = this.prototype - , posts = proto._posts = proto._posts || {}; - (posts[name] = posts[name] || []).push(fn); - return this; - } -}; diff --git a/node_modules/mongoose/node_modules/hooks/hooks.js b/node_modules/mongoose/node_modules/hooks/hooks.js deleted file mode 100644 index 9a887c76e..000000000 --- a/node_modules/mongoose/node_modules/hooks/hooks.js +++ /dev/null @@ -1,161 +0,0 @@ -// TODO Add in pre and post skipping options -module.exports = { - /** - * Declares a new hook to which you can add pres and posts - * @param {String} name of the function - * @param {Function} the method - * @param {Function} the error handler callback - */ - hook: function (name, fn, errorCb) { - if (arguments.length === 1 && typeof name === 'object') { - for (var k in name) { // `name` is a hash of hookName->hookFn - this.hook(k, name[k]); - } - return; - } - - var proto = this.prototype || this - , pres = proto._pres = proto._pres || {} - , posts = proto._posts = proto._posts || {}; - pres[name] = pres[name] || []; - posts[name] = posts[name] || []; - - proto[name] = function () { - var self = this - , hookArgs // arguments eventually passed to the hook - are mutable - , lastArg = arguments[arguments.length-1] - , pres = this._pres[name] - , posts = this._posts[name] - , _total = pres.length - , _current = -1 - , _asyncsLeft = proto[name].numAsyncPres - , _next = function () { - if (arguments[0] instanceof Error) { - return handleError(arguments[0]); - } - var _args = Array.prototype.slice.call(arguments) - , currPre - , preArgs; - if (_args.length && !(arguments[0] == null && typeof lastArg === 'function')) - hookArgs = _args; - if (++_current < _total) { - currPre = pres[_current] - if (currPre.isAsync && currPre.length < 2) - throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)"); - if (currPre.length < 1) - throw new Error("Your pre must have a next argument -- e.g., function (next, ...)"); - preArgs = (currPre.isAsync - ? [once(_next), once(_asyncsDone)] - : [once(_next)]).concat(hookArgs); - return currPre.apply(self, preArgs); - } else if (!proto[name].numAsyncPres) { - return _done.apply(self, hookArgs); - } - } - , _done = function () { - var args_ = Array.prototype.slice.call(arguments) - , ret, total_, current_, next_, done_, postArgs; - if (_current === _total) { - ret = fn.apply(self, args_); - total_ = posts.length; - current_ = -1; - next_ = function () { - if (arguments[0] instanceof Error) { - return handleError(arguments[0]); - } - var args_ = Array.prototype.slice.call(arguments, 1) - , currPost - , postArgs; - if (args_.length) hookArgs = args_; - if (++current_ < total_) { - currPost = posts[current_] - if (currPost.length < 1) - throw new Error("Your post must have a next argument -- e.g., function (next, ...)"); - postArgs = [once(next_)].concat(hookArgs); - return currPost.apply(self, postArgs); - } - }; - if (total_) return next_(); - return ret; - } - }; - if (_asyncsLeft) { - function _asyncsDone (err) { - if (err && err instanceof Error) { - return handleError(err); - } - --_asyncsLeft || _done.apply(self, hookArgs); - } - } - function handleError (err) { - if ('function' == typeof lastArg) - return lastArg(err); - if (errorCb) return errorCb.call(self, err); - throw err; - } - return _next.apply(this, arguments); - }; - - proto[name].numAsyncPres = 0; - - return this; - }, - - pre: function (name, isAsync, fn, errorCb) { - if ('boolean' !== typeof arguments[1]) { - errorCb = fn; - fn = isAsync; - isAsync = false; - } - var proto = this.prototype || this - , pres = proto._pres = proto._pres || {}; - - this._lazySetupHooks(proto, name, errorCb); - - if (fn.isAsync = isAsync) { - proto[name].numAsyncPres++; - } - - (pres[name] = pres[name] || []).push(fn); - return this; - }, - post: function (name, isAsync, fn) { - if (arguments.length === 2) { - fn = isAsync; - isAsync = false; - } - var proto = this.prototype || this - , posts = proto._posts = proto._posts || {}; - - this._lazySetupHooks(proto, name); - (posts[name] = posts[name] || []).push(fn); - return this; - }, - removePre: function (name, fnToRemove) { - var proto = this.prototype || this - , pres = proto._pres || (proto._pres || {}); - if (!pres[name]) return this; - if (arguments.length === 1) { - // Remove all pre callbacks for hook `name` - pres[name].length = 0; - } else { - pres[name] = pres[name].filter( function (currFn) { - return currFn !== fnToRemove; - }); - } - return this; - }, - _lazySetupHooks: function (proto, methodName, errorCb) { - if ('undefined' === typeof proto[methodName].numAsyncPres) { - this.hook(methodName, proto[methodName], errorCb); - } - } -}; - -function once (fn, scope) { - return function fnWrapper () { - if (fnWrapper.hookCalled) return; - fnWrapper.hookCalled = true; - fn.apply(scope, arguments); - }; -} diff --git a/node_modules/mongoose/node_modules/hooks/package.json b/node_modules/mongoose/node_modules/hooks/package.json deleted file mode 100644 index 561ccc9fd..000000000 --- a/node_modules/mongoose/node_modules/hooks/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "hooks", - "description": "Adds pre and post hook functionality to your JavaScript methods.", - "version": "0.2.1", - "keywords": [ - "node", - "hooks", - "middleware", - "pre", - "post" - ], - "homepage": "https://github.com/bnoguchi/hooks-js/", - "repository": { - "type": "git", - "url": "git://github.com/bnoguchi/hooks-js.git" - }, - "author": { - "name": "Brian Noguchi", - "email": "brian.noguchi@gmail.com", - "url": "https://github.com/bnoguchi/" - }, - "main": "./hooks.js", - "directories": { - "lib": "." - }, - "scripts": { - "test": "make test" - }, - "dependencies": {}, - "devDependencies": { - "expresso": ">=0.7.6", - "should": ">=0.2.1", - "underscore": ">=1.1.4" - }, - "engines": { - "node": ">=0.4.0" - }, - "licenses": [ - "MIT" - ], - "optionalDependencies": {}, - "readme": "hooks\n============\n\nAdd pre and post middleware hooks to your JavaScript methods.\n\n## Installation\n npm install hooks\n\n## Motivation\nSuppose you have a JavaScript object with a `save` method.\n\nIt would be nice to be able to declare code that runs before `save` and after `save`.\nFor example, you might want to run validation code before every `save`,\nand you might want to dispatch a job to a background job queue after `save`.\n\nOne might have an urge to hard code this all into `save`, but that turns out to\ncouple all these pieces of functionality (validation, save, and job creation) more\ntightly than is necessary. For example, what if someone does not want to do background\njob creation after the logical save? \n\nIt is nicer to tack on functionality using what we call `pre` and `post` hooks. These\nare functions that you define and that you direct to execute before or after particular\nmethods.\n\n## Example\nWe can use `hooks` to add validation and background jobs in the following way:\n\n var hooks = require('hooks')\n , Document = require('./path/to/some/document/constructor');\n\n // Add hooks' methods: `hook`, `pre`, and `post` \n for (var k in hooks) {\n Document[k] = hooks[k];\n }\n\n // Define a new method that is able to invoke pre and post middleware\n Document.hook('save', Document.prototype.save);\n\n // Define a middleware function to be invoked before 'save'\n Document.pre('save', function validate (next) {\n // The `this` context inside of `pre` and `post` functions\n // is the Document instance\n if (this.isValid()) next(); // next() passes control to the next middleware\n // or to the target method itself\n else next(new Error(\"Invalid\")); // next(error) invokes an error callback\n });\n\n // Define a middleware function to be invoked after 'save'\n Document.post('save', function createJob () {\n this.sendToBackgroundQueue();\n });\n\nIf you already have defined `Document.prototype` methods for which you want pres and posts,\nthen you do not need to explicitly invoke `Document.hook(...)`. Invoking `Document.pre(methodName, fn)`\nor `Document.post(methodName, fn)` will automatically and lazily change `Document.prototype[methodName]`\nso that it plays well with `hooks`. An equivalent way to implement the previous example is:\n\n```javascript\nvar hooks = require('hooks')\n , Document = require('./path/to/some/document/constructor');\n\n// Add hooks' methods: `hook`, `pre`, and `post` \nfor (var k in hooks) {\n Document[k] = hooks[k];\n}\n\nDocument.prototype.save = function () {\n // ...\n};\n\n// Define a middleware function to be invoked before 'save'\nDocument.pre('save', function validate (next) {\n // The `this` context inside of `pre` and `post` functions\n // is the Document instance\n if (this.isValid()) next(); // next() passes control to the next middleware\n // or to the target method itself\n else next(new Error(\"Invalid\")); // next(error) invokes an error callback\n});\n\n// Define a middleware function to be invoked after 'save'\nDocument.post('save', function createJob () {\n this.sendToBackgroundQueue();\n});\n```\n\n## Pres and Posts as Middleware\nWe structure pres and posts as middleware to give you maximum flexibility:\n\n1. You can define **multiple** pres (or posts) for a single method.\n2. These pres (or posts) are then executed as a chain of methods.\n3. Any functions in this middleware chain can choose to halt the chain's execution by `next`ing an Error from that middleware function. If this occurs, then none of the other middleware in the chain will execute, and the main method (e.g., `save`) will not execute. This is nice, for example, when we don't want a document to save if it is invalid.\n\n## Defining multiple pres (or posts)\n`pre` is chainable, so you can define multiple pres via:\n Document.pre('save', function (next, halt) {\n console.log(\"hello\");\n }).pre('save', function (next, halt) {\n console.log(\"world\");\n });\n\nAs soon as one pre finishes executing, the next one will be invoked, and so on.\n\n## Error Handling\nYou can define a default error handler by passing a 2nd function as the 3rd argument to `hook`:\n Document.hook('set', function (path, val) {\n this[path] = val;\n }, function (err) {\n // Handler the error here\n console.error(err);\n });\n\nThen, we can pass errors to this handler from a pre or post middleware function:\n Document.pre('set', function (next, path, val) {\n next(new Error());\n });\n\nIf you do not set up a default handler, then `hooks` makes the default handler that just throws the `Error`.\n\nThe default error handler can be over-rided on a per method invocation basis.\n\nIf the main method that you are surrounding with pre and post middleware expects its last argument to be a function\nwith callback signature `function (error, ...)`, then that callback becomes the error handler, over-riding the default\nerror handler you may have set up.\n \n```javascript\nDocument.hook('save', function (callback) {\n // Save logic goes here\n ...\n});\n\nvar doc = new Document();\ndoc.save( function (err, saved) {\n // We can pass err via `next` in any of our pre or post middleware functions\n if (err) console.error(err);\n \n // Rest of callback logic follows ...\n});\n```\n\n## Mutating Arguments via Middleware\n`pre` and `post` middleware can also accept the intended arguments for the method\nthey augment. This is useful if you want to mutate the arguments before passing\nthem along to the next middleware and eventually pass a mutated arguments list to\nthe main method itself.\n\nAs a simple example, let's define a method `set` that just sets a key, value pair.\nIf we want to namespace the key, we can do so by adding a `pre` middleware hook\nthat runs before `set`, alters the arguments by namespacing the `key` argument, and passes them onto `set`:\n\n Document.hook('set', function (key, val) {\n this[key] = val;\n });\n Document.pre('set', function (next, key, val) {\n next('namespace-' + key, val);\n });\n var doc = new Document();\n doc.set('hello', 'world');\n console.log(doc.hello); // undefined\n console.log(doc['namespace-hello']); // 'world'\n\nAs you can see above, we pass arguments via `next`.\n\nIf you are not mutating the arguments, then you can pass zero arguments\nto `next`, and the next middleware function will still have access\nto the arguments.\n\n Document.hook('set', function (key, val) {\n this[key] = val;\n });\n Document.pre('set', function (next, key, val) {\n // I have access to key and val here\n next(); // We don't need to pass anything to next\n });\n Document.pre('set', function (next, key, val) {\n // And I still have access to the original key and val here\n next();\n });\n\nFinally, you can add arguments that downstream middleware can also see:\n\n // Note that in the definition of `set`, there is no 3rd argument, options\n Document.hook('set', function (key, val) {\n // But...\n var options = arguments[2]; // ...I have access to an options argument\n // because of pre function pre2 (defined below)\n console.log(options); // '{debug: true}'\n this[key] = val;\n });\n Document.pre('set', function pre1 (next, key, val) {\n // I only have access to key and val arguments\n console.log(arguments.length); // 3\n next(key, val, {debug: true});\n });\n Document.pre('set', function pre2 (next, key, val, options) {\n console.log(arguments.length); // 4\n console.log(options); // '{ debug: true}'\n next();\n });\n Document.pre('set', function pre3 (next, key, val, options) {\n // I still have access to key, val, AND the options argument introduced via the preceding middleware\n console.log(arguments.length); // 4\n console.log(options); // '{ debug: true}'\n next();\n });\n \n var doc = new Document()\n doc.set('hey', 'there');\n\n## Parallel `pre` middleware\n\nAll middleware up to this point has been \"serial\" middleware -- i.e., middleware whose logic\nis executed as a serial chain.\n\nSome scenarios call for parallel middleware -- i.e., middleware that can wait for several\nasynchronous services at once to respond.\n\nFor instance, you may only want to save a Document only after you have checked\nthat the Document is valid according to two different remote services.\n\nWe accomplish asynchronous middleware by adding a second kind of flow control callback\n(the only flow control callback so far has been `next`), called `done`.\n\n- `next` passes control to the next middleware in the chain\n- `done` keeps track of how many parallel middleware have invoked `done` and passes\n control to the target method when ALL parallel middleware have invoked `done`. If\n you pass an `Error` to `done`, then the error is handled, and the main method that is\n wrapped by pres and posts will not get invoked.\n\nWe declare pre middleware that is parallel by passing a 3rd boolean argument to our `pre`\ndefinition method.\n\nWe illustrate via the parallel validation example mentioned above:\n\n Document.hook('save', function targetFn (callback) {\n // Save logic goes here\n // ...\n // This only gets run once the two `done`s are both invoked via preOne and preTwo.\n });\n\n // true marks this as parallel middleware\n Document.pre('save', true, function preOne (next, doneOne, callback) {\n remoteServiceOne.validate(this.serialize(), function (err, isValid) {\n // The code in here will probably be run after the `next` below this block\n // and could possibly be run after the console.log(\"Hola\") in `preTwo\n if (err) return doneOne(err);\n if (isValid) doneOne();\n });\n next(); // Pass control to the next middleware\n });\n \n // We will suppose that we need 2 different remote services to validate our document\n Document.pre('save', true, function preTwo (next, doneTwo, callback) {\n remoteServiceTwo.validate(this.serialize(), function (err, isValid) {\n if (err) return doneTwo(err);\n if (isValid) doneTwo();\n });\n next();\n });\n \n // While preOne and preTwo are parallel, preThree is a serial pre middleware\n Document.pre('save', function preThree (next, callback) {\n next();\n });\n \n var doc = new Document();\n doc.save( function (err, doc) {\n // Do stuff with the saved doc here...\n });\n\nIn the above example, flow control may happen in the following way:\n\n(1) doc.save -> (2) preOne --(next)--> (3) preTwo --(next)--> (4) preThree --(next)--> (wait for dones to invoke) -> (5) doneTwo -> (6) doneOne -> (7) targetFn\n\nSo what's happening is that:\n\n1. You call `doc.save(...)`\n2. First, your preOne middleware gets executed. It makes a remote call to the validation service and `next()`s to the preTwo middleware.\n3. Now, your preTwo middleware gets executed. It makes a remote call to another validation service and `next()`s to the preThree middleware.\n4. Your preThree middleware gets executed. It immediately `next()`s. But nothing else gets executing until both `doneOne` and `doneTwo` are invoked inside the callbacks handling the response from the two valiation services.\n5. We will suppose that validation remoteServiceTwo returns a response to us first. In this case, we call `doneTwo` inside the callback to remoteServiceTwo.\n6. Some fractions of a second later, remoteServiceOne returns a response to us. In this case, we call `doneOne` inside the callback to remoteServiceOne.\n7. `hooks` implementation keeps track of how many parallel middleware has been defined per target function. It detects that both asynchronous pre middlewares (`preOne` and `preTwo`) have finally called their `done` functions (`doneOne` and `doneTwo`), so the implementation finally invokes our `targetFn` (i.e., our core `save` business logic).\n\n## Removing Pres\n\nYou can remove a particular pre associated with a hook:\n\n Document.pre('set', someFn);\n Document.removePre('set', someFn);\n\nAnd you can also remove all pres associated with a hook:\n Document.removePre('set'); // Removes all declared `pre`s on the hook 'set'\n\n## Tests\nTo run the tests:\n make test\n\n### Contributors\n- [Brian Noguchi](https://github.com/bnoguchi)\n\n### License\nMIT License\n\n---\n### Author\nBrian Noguchi\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/bnoguchi/hooks-js/issues" - }, - "_id": "hooks@0.2.1", - "dist": { - "shasum": "3efcc7e0f4917e4ec300f23a737103e5b920eac5" - }, - "_from": "hooks@0.2.1", - "_resolved": "https://registry.npmjs.org/hooks/-/hooks-0.2.1.tgz" -} diff --git a/node_modules/mongoose/node_modules/hooks/test.js b/node_modules/mongoose/node_modules/hooks/test.js deleted file mode 100644 index efe2f3e03..000000000 --- a/node_modules/mongoose/node_modules/hooks/test.js +++ /dev/null @@ -1,691 +0,0 @@ -var hooks = require('./hooks') - , should = require('should') - , assert = require('assert') - , _ = require('underscore'); - -// TODO Add in test for making sure all pres get called if pre is defined directly on an instance. -// TODO Test for calling `done` twice or `next` twice in the same function counts only once -module.exports = { - 'should be able to assign multiple hooks at once': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook({ - hook1: function (a) {}, - hook2: function (b) {} - }); - var a = new A(); - assert.equal(typeof a.hook1, 'function'); - assert.equal(typeof a.hook2, 'function'); - }, - 'should run without pres and posts when not present': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - }, - 'should run with pres when present': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.preValue = 2; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - a.preValue.should.equal(2); - }, - 'should run with posts when present': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.post('save', function (next) { - this.value = 2; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(2); - }, - 'should run pres and posts when present': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.preValue = 2; - next(); - }); - A.post('save', function (next) { - this.value = 3; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(3); - a.preValue.should.equal(2); - }, - 'should run posts after pres': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.override = 100; - next(); - }); - A.post('save', function (next) { - this.override = 200; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - a.override.should.equal(200); - }, - 'should not run a hook if a pre fails': function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function () { - this.value = 1; - }, function (err) { - counter++; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - a.save(); - counter.should.equal(1); - assert.equal(typeof a.value, 'undefined'); - }, - 'should be able to run multiple pres': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.v1 = 1; - next(); - }).pre('save', function (next) { - this.v2 = 2; - next(); - }); - var a = new A(); - a.save(); - a.v1.should.equal(1); - a.v2.should.equal(2); - }, - 'should run multiple pres until a pre fails and not call the hook': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }, function (err) {}); - A.pre('save', function (next) { - this.v1 = 1; - next(); - }).pre('save', function (next) { - next(new Error()); - }).pre('save', function (next) { - this.v3 = 3; - next(); - }); - var a = new A(); - a.save(); - a.v1.should.equal(1); - assert.equal(typeof a.v3, 'undefined'); - assert.equal(typeof a.value, 'undefined'); - }, - 'should be able to run multiple posts': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.post('save', function (next) { - this.value = 2; - next(); - }).post('save', function (next) { - this.value = 3.14; - next(); - }).post('save', function (next) { - this.v3 = 3; - next(); - }); - var a = new A(); - a.save(); - assert.equal(a.value, 3.14); - assert.equal(a.v3, 3); - }, - 'should run only posts up until an error': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }, function (err) {}); - A.post('save', function (next) { - this.value = 2; - next(); - }).post('save', function (next) { - this.value = 3; - next(new Error()); - }).post('save', function (next) { - this.value = 4; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(3); - }, - "should fall back first to the hook method's last argument as the error handler if it is a function of arity 1 or 2": function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function (callback) { - this.value = 1; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - a.save( function (err) { - if (err instanceof Error) counter++; - }); - counter.should.equal(1); - should.deepEqual(undefined, a.value); - }, - 'should fall back second to the default error handler if specified': function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function (callback) { - this.value = 1; - }, function (err) { - if (err instanceof Error) counter++; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - a.save(); - counter.should.equal(1); - should.deepEqual(undefined, a.value); - }, - 'fallback default error handler should scope to the object': function () { - var A = function () { - this.counter = 0; - }; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function (callback) { - this.value = 1; - }, function (err) { - if (err instanceof Error) this.counter++; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - a.save(); - a.counter.should.equal(1); - should.deepEqual(undefined, a.value); - }, - 'should fall back last to throwing the error': function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.hook('save', function (err) { - if (err instanceof Error) return counter++; - this.value = 1; - }); - A.pre('save', true, function (next, done) { - next(new Error()); - }); - var a = new A(); - var didCatch = false; - try { - a.save(); - } catch (e) { - didCatch = true; - e.should.be.an.instanceof(Error); - counter.should.equal(0); - assert.equal(typeof a.value, 'undefined'); - } - didCatch.should.be.true; - }, - "should proceed without mutating arguments if `next(null|undefined)` is called in a serial pre, and the last argument of the target method is a callback with node-like signature function (err, obj) {...} or function (err) {...}": function () { - var A = function () {}; - _.extend(A, hooks); - var counter = 0; - A.prototype.save = function (callback) { - this.value = 1; - callback(); - }; - A.pre('save', function (next) { - next(null); - }); - A.pre('save', function (next) { - next(undefined); - }); - var a = new A(); - a.save( function (err) { - if (err instanceof Error) counter++; - else counter--; - }); - counter.should.equal(-1); - a.value.should.eql(1); - }, - "should proceed with mutating arguments if `next(null|undefined)` is callback in a serial pre, and the last argument of the target method is not a function": function () { - var A = function () {}; - _.extend(A, hooks); - A.prototype.set = function (v) { - this.value = v; - }; - A.pre('set', function (next) { - next(undefined); - }); - A.pre('set', function (next) { - next(null); - }); - var a = new A(); - a.set(1); - should.strictEqual(null, a.value); - }, - 'should not run any posts if a pre fails': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 2; - }, function (err) {}); - A.pre('save', function (next) { - this.value = 1; - next(new Error()); - }).post('save', function (next) { - this.value = 3; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - }, - - "can pass the hook's arguments verbatim to pres": function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - }); - A.pre('set', function (next, path, val) { - path.should.equal('hello'); - val.should.equal('world'); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - a.hello.should.equal('world'); - }, -// "can pass the hook's arguments as an array to pres": function () { -// // Great for dynamic arity - e.g., slice(...) -// var A = function () {}; -// _.extend(A, hooks); -// A.hook('set', function (path, val) { -// this[path] = val; -// }); -// A.pre('set', function (next, hello, world) { -// hello.should.equal('hello'); -// world.should.equal('world'); -// next(); -// }); -// var a = new A(); -// a.set('hello', 'world'); -// assert.equal(a.hello, 'world'); -// }, - "can pass the hook's arguments verbatim to posts": function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - }); - A.post('set', function (next, path, val) { - path.should.equal('hello'); - val.should.equal('world'); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - assert.equal(a.hello, 'world'); - }, -// "can pass the hook's arguments as an array to posts": function () { -// var A = function () {}; -// _.extend(A, hooks); -// A.hook('set', function (path, val) { -// this[path] = val; -// }); -// A.post('set', function (next, halt, args) { -// assert.equal(args[0], 'hello'); -// assert.equal(args[1], 'world'); -// next(); -// }); -// var a = new A(); -// a.set('hello', 'world'); -// assert.equal(a.hello, 'world'); -// }, - "pres should be able to modify and pass on a modified version of the hook's arguments": function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - assert.equal(arguments[2], 'optional'); - }); - A.pre('set', function (next, path, val) { - next('foo', 'bar'); - }); - A.pre('set', function (next, path, val) { - assert.equal(path, 'foo'); - assert.equal(val, 'bar'); - next('rock', 'says', 'optional'); - }); - A.pre('set', function (next, path, val, opt) { - assert.equal(path, 'rock'); - assert.equal(val, 'says'); - assert.equal(opt, 'optional'); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - assert.equal(typeof a.hello, 'undefined'); - a.rock.should.equal('says'); - }, - 'posts should see the modified version of arguments if the pres modified them': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - }); - A.pre('set', function (next, path, val) { - next('foo', 'bar'); - }); - A.post('set', function (next, path, val) { - path.should.equal('foo'); - val.should.equal('bar'); - }); - var a = new A(); - a.set('hello', 'world'); - assert.equal(typeof a.hello, 'undefined'); - a.foo.should.equal('bar'); - }, - 'should pad missing arguments (relative to expected arguments of the hook) with null': function () { - // Otherwise, with hookFn = function (a, b, next, ), - // if we use hookFn(a), then because the pre functions are of the form - // preFn = function (a, b, next, ), then it actually gets executed with - // preFn(a, next, ), so when we call next() from within preFn, we are actually - // calling () - - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val, opts) { - this[path] = val; - }); - A.pre('set', function (next, path, val, opts) { - next('foo', 'bar'); - assert.equal(typeof opts, 'undefined'); - }); - var a = new A(); - a.set('hello', 'world'); - }, - - 'should not invoke the target method until all asynchronous middleware have invoked dones': function () { - var counter = 0; - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - counter++; - this[path] = val; - counter.should.equal(7); - }); - A.pre('set', function (next, path, val) { - counter++; - next(); - }); - A.pre('set', true, function (next, done, path, val) { - counter++; - setTimeout(function () { - counter++; - done(); - }, 1000); - next(); - }); - A.pre('set', function (next, path, val) { - counter++; - next(); - }); - A.pre('set', true, function (next, done, path, val) { - counter++; - setTimeout(function () { - counter++; - done(); - }, 500); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - }, - - 'invoking a method twice should run its async middleware twice': function () { - var counter = 0; - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val) { - this[path] = val; - if (path === 'hello') counter.should.equal(1); - if (path === 'foo') counter.should.equal(2); - }); - A.pre('set', true, function (next, done, path, val) { - setTimeout(function () { - counter++; - done(); - }, 1000); - next(); - }); - var a = new A(); - a.set('hello', 'world'); - a.set('foo', 'bar'); - }, - - 'calling the same done multiple times should have the effect of only calling it once': function () { - var A = function () { - this.acked = false; - }; - _.extend(A, hooks); - A.hook('ack', function () { - console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); - this.acked = true; - }); - A.pre('ack', true, function (next, done) { - next(); - done(); - done(); - }); - A.pre('ack', true, function (next, done) { - next(); - // Notice that done() is not invoked here - }); - var a = new A(); - a.ack(); - setTimeout( function () { - a.acked.should.be.false; - }, 1000); - }, - - 'calling the same next multiple times should have the effect of only calling it once': function (beforeExit) { - var A = function () { - this.acked = false; - }; - _.extend(A, hooks); - A.hook('ack', function () { - console.log("UH OH, YOU SHOULD NOT BE SEEING THIS"); - this.acked = true; - }); - A.pre('ack', function (next) { - // force a throw to re-exec next() - try { - next(new Error('bam')); - } catch (err) { - next(); - } - }); - A.pre('ack', function (next) { - next(); - }); - var a = new A(); - a.ack(); - beforeExit( function () { - a.acked.should.be.false; - }); - }, - - 'asynchronous middleware should be able to pass an error via `done`, stopping the middleware chain': function () { - var counter = 0; - var A = function () {}; - _.extend(A, hooks); - A.hook('set', function (path, val, fn) { - counter++; - this[path] = val; - fn(null); - }); - A.pre('set', true, function (next, done, path, val, fn) { - setTimeout(function () { - counter++; - done(new Error); - }, 1000); - next(); - }); - var a = new A(); - a.set('hello', 'world', function (err) { - err.should.be.an.instanceof(Error); - should.strictEqual(undefined, a['hello']); - counter.should.eql(1); - }); - }, - - 'should be able to remove a particular pre': function () { - var A = function () {} - , preTwo; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.preValueOne = 2; - next(); - }); - A.pre('save', preTwo = function (next) { - this.preValueTwo = 4; - next(); - }); - A.removePre('save', preTwo); - var a = new A(); - a.save(); - a.value.should.equal(1); - a.preValueOne.should.equal(2); - should.strictEqual(undefined, a.preValueTwo); - }, - - 'should be able to remove all pres associated with a hook': function () { - var A = function () {}; - _.extend(A, hooks); - A.hook('save', function () { - this.value = 1; - }); - A.pre('save', function (next) { - this.preValueOne = 2; - next(); - }); - A.pre('save', function (next) { - this.preValueTwo = 4; - next(); - }); - A.removePre('save'); - var a = new A(); - a.save(); - a.value.should.equal(1); - should.strictEqual(undefined, a.preValueOne); - should.strictEqual(undefined, a.preValueTwo); - }, - - '#pre should lazily make a method hookable': function () { - var A = function () {}; - _.extend(A, hooks); - A.prototype.save = function () { - this.value = 1; - }; - A.pre('save', function (next) { - this.preValue = 2; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(1); - a.preValue.should.equal(2); - }, - - '#pre lazily making a method hookable should be able to provide a default errorHandler as the last argument': function () { - var A = function () {}; - var preValue = ""; - _.extend(A, hooks); - A.prototype.save = function () { - this.value = 1; - }; - A.pre('save', function (next) { - next(new Error); - }, function (err) { - preValue = 'ERROR'; - }); - var a = new A(); - a.save(); - should.strictEqual(undefined, a.value); - preValue.should.equal('ERROR'); - }, - - '#post should lazily make a method hookable': function () { - var A = function () {}; - _.extend(A, hooks); - A.prototype.save = function () { - this.value = 1; - }; - A.post('save', function (next) { - this.value = 2; - next(); - }); - var a = new A(); - a.save(); - a.value.should.equal(2); - }, - - "a lazy hooks setup should handle errors via a method's last argument, if it's a callback": function () { - var A = function () {}; - _.extend(A, hooks); - A.prototype.save = function (fn) {}; - A.pre('save', function (next) { - next(new Error("hi there")); - }); - var a = new A(); - a.save( function (err) { - err.should.be.an.instanceof(Error); - }); - } -}; diff --git a/node_modules/mongoose/node_modules/mpath/.npmignore b/node_modules/mongoose/node_modules/mpath/.npmignore deleted file mode 100644 index be106cacd..000000000 --- a/node_modules/mongoose/node_modules/mpath/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.sw* -node_modules/ diff --git a/node_modules/mongoose/node_modules/mpath/.travis.yml b/node_modules/mongoose/node_modules/mpath/.travis.yml deleted file mode 100644 index 09c230f0c..000000000 --- a/node_modules/mongoose/node_modules/mpath/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 diff --git a/node_modules/mongoose/node_modules/mpath/History.md b/node_modules/mongoose/node_modules/mpath/History.md deleted file mode 100644 index 4fbf33851..000000000 --- a/node_modules/mongoose/node_modules/mpath/History.md +++ /dev/null @@ -1,16 +0,0 @@ - -0.1.1 / 2012-12-21 -================== - - * added; map support - -0.1.0 / 2012-12-13 -================== - - * added; set('array.property', val, object) support - * added; get('array.property', object) support - -0.0.1 / 2012-11-03 -================== - - * initial release diff --git a/node_modules/mongoose/node_modules/mpath/LICENSE b/node_modules/mongoose/node_modules/mpath/LICENSE deleted file mode 100644 index 38c529daa..000000000 --- a/node_modules/mongoose/node_modules/mpath/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/mpath/Makefile b/node_modules/mongoose/node_modules/mpath/Makefile deleted file mode 100644 index b0bb0819b..000000000 --- a/node_modules/mongoose/node_modules/mpath/Makefile +++ /dev/null @@ -1,5 +0,0 @@ - -test: - @node_modules/mocha/bin/mocha -A $(T) - -.PHONY: test diff --git a/node_modules/mongoose/node_modules/mpath/README.md b/node_modules/mongoose/node_modules/mpath/README.md deleted file mode 100644 index 9831dd066..000000000 --- a/node_modules/mongoose/node_modules/mpath/README.md +++ /dev/null @@ -1,278 +0,0 @@ -#mpath - -{G,S}et javascript object values using MongoDB-like path notation. - -###Getting - -```js -var mpath = require('mpath'); - -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.1.title', obj) // 'exciting!' -``` - -`mpath.get` supports array property notation as well. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.title', obj) // ['funny', 'exciting!'] -``` - -Array property and indexing syntax, when used together, are very powerful. - -```js -var obj = { - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} - -var found = mpath.get('array.o.array.x.b.1', obj); - -console.log(found); // prints.. - - [ [6, undefined] - , [2, undefined, undefined] - , [null, 1] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - -``` - -#####Field selection rules: - -The following rules are iteratively applied to each `segment` in the passed `path`. For example: - -```js -var path = 'one.two.14'; // path -'one' // segment 0 -'two' // segment 1 -14 // segment 2 -``` - -- 1) when value of the segment parent is not an array, return the value of `parent.segment` -- 2) when value of the segment parent is an array - - a) if the segment is an integer, replace the parent array with the value at `parent[segment]` - - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey. - -#####Maps - -`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.get('comments.title', obj, function (val) { - return 'funny' == val - ? 'amusing' - : val; -}); -// ['amusing', 'exciting!'] -``` - -###Setting - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.1.title', 'hilarious', obj) -console.log(obj.comments[1].title) // 'hilarious' -``` - -`mpath.set` supports the same array property notation as `mpath.get`. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: 'hilarious' }, - { title: 'fruity' } - ]} -``` - -Array property and indexing syntax can be used together also when setting. - -```js -var obj = { - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ] -} - -mpath.set('array.1.o', 'this was changed', obj); - -console.log(require('util').inspect(obj, false, 1000)); // prints.. - -{ - array: [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: 'this was changed' } - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} - -mpath.set('array.o.array.x', 'this was changed too', obj); - -console.log(require('util').inspect(obj, false, 1000)); // prints.. - -{ - array: [ - { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }} - , { o: 'this was changed' } - , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }} - , { o: { array: [{x: 'this was changed too'}] }} - , { o: { array: [{x: 'this was changed too', y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; -} -``` - -####Setting arrays - -By default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: 'hilarious' }, - { title: 'fruity' } - ]} -``` - -If we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.$.title', ['hilarious', 'fruity'], obj); - -console.log(obj); // prints.. - - { comments: [ - { title: ['hilarious', 'fruity'] }, - { title: ['hilarious', 'fruity'] } - ]} -``` - -####Field assignment rules - -The rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples. - -#####Maps - -`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place. - -```js -var obj = { - comments: [ - { title: 'funny' }, - { title: 'exciting!' } - ] -} - -mpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) { - return val.length; -}); - -console.log(obj); // prints.. - - { comments: [ - { title: 9 }, - { title: 6 } - ]} -``` - -### Custom object types - -Sometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead: - -```js -var mpath = require('mpath'); - -var obj = { - comments: [ - { title: 'exciting!', _doc: { title: 'great!' }} - ] -} - -mpath.get('comments.0.title', obj, '_doc') // 'great!' -mpath.set('comments.0.title', 'nov 3rd', obj, '_doc') -mpath.get('comments.0.title', obj, '_doc') // 'nov 3rd' -mpath.get('comments.0.title', obj) // 'exciting' -``` - -When used with a `map`, the `map` argument comes last. - -```js -mpath.get(path, obj, '_doc', map); -mpath.set(path, val, obj, '_doc', map); -``` - -[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE) - diff --git a/node_modules/mongoose/node_modules/mpath/index.js b/node_modules/mongoose/node_modules/mpath/index.js deleted file mode 100644 index f7b65dd59..000000000 --- a/node_modules/mongoose/node_modules/mpath/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib'); diff --git a/node_modules/mongoose/node_modules/mpath/lib/index.js b/node_modules/mongoose/node_modules/mpath/lib/index.js deleted file mode 100644 index 24e1e8321..000000000 --- a/node_modules/mongoose/node_modules/mpath/lib/index.js +++ /dev/null @@ -1,183 +0,0 @@ - -/** - * Returns the value of object `o` at the given `path`. - * - * ####Example: - * - * var obj = { - * comments: [ - * { title: 'exciting!', _doc: { title: 'great!' }} - * , { title: 'number dos' } - * ] - * } - * - * mpath.get('comments.0.title', o) // 'exciting!' - * mpath.get('comments.0.title', o, '_doc') // 'great!' - * mpath.get('comments.title', o) // ['exciting!', 'number dos'] - * - * // summary - * mpath.get(path, o) - * mpath.get(path, o, special) - * mpath.get(path, o, map) - * mpath.get(path, o, special, map) - * - * @param {String} path - * @param {Object} o - * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. - * @param {Function} [map] Optional function which receives each individual found value. The value returned from `map` is used in the original values place. - */ - -exports.get = function (path, o, special, map) { - if ('function' == typeof special) { - map = special; - special = undefined; - } - - map || (map = K); - - var parts = 'string' == typeof path - ? path.split('.') - : path - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - var obj = o - , part; - - for (var i = 0; i < parts.length; ++i) { - part = parts[i]; - - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - // reading a property from the array items - var paths = parts.slice(i); - - return obj.map(function (item) { - return item - ? exports.get(paths, item, special, map) - : map(undefined); - }); - } - - obj = special && obj[special] - ? obj[special][part] - : obj[part]; - - if (!obj) return map(obj); - } - - return map(obj); -} - -/** - * Sets the `val` at the given `path` of object `o`. - * - * @param {String} path - * @param {Anything} val - * @param {Object} o - * @param {String} [special] When this property name is present on any object in the path, walking will continue on the value of this property. - * @param {Function} [map] Optional function which is passed each individual value before setting it. The value returned from `map` is used in the original values place. - - */ - -exports.set = function (path, val, o, special, map, _copying) { - if ('function' == typeof special) { - map = special; - special = undefined; - } - - map || (map = K); - - var parts = 'string' == typeof path - ? path.split('.') - : path - - if (!Array.isArray(parts)) { - throw new TypeError('Invalid `path`. Must be either string or array'); - } - - if (null == o) return; - - // the existance of $ in a path tells us if the user desires - // the copying of an array instead of setting each value of - // the array to the one by one to matching positions of the - // current array. - var copy = _copying || /\$/.test(path) - , obj = o - , part - - for (var i = 0, len = parts.length - 1; i < len; ++i) { - part = parts[i]; - - if ('$' == part) { - if (i == len - 1) { - break; - } else { - continue; - } - } - - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - var paths = parts.slice(i); - if (!copy && Array.isArray(val)) { - for (var j = 0; j < obj.length && j < val.length; ++j) { - // assignment of single values of array - exports.set(paths, val[j], obj[j], special, map, copy); - } - } else { - for (var j = 0; j < obj.length; ++j) { - // assignment of entire value - exports.set(paths, val, obj[j], special, map, copy); - } - } - return; - } - - obj = special && obj[special] - ? obj[special][part] - : obj[part]; - - if (!obj) return; - } - - // process the last property of the path - - part = parts[len]; - - // use the special property if exists - if (special && obj[special]) { - obj = obj[special]; - } - - // set the value on the last branch - if (Array.isArray(obj) && !/^\d+$/.test(part)) { - if (!copy && Array.isArray(val)) { - for (var item, j = 0; j < obj.length && j < val.length; ++j) { - item = obj[j]; - if (item) { - if (item[special]) item = item[special]; - item[part] = map(val[j]); - } - } - } else { - for (var j = 0; j < obj.length; ++j) { - item = obj[j]; - if (item) { - if (item[special]) item = item[special]; - item[part] = map(val); - } - } - } - } else { - obj[part] = map(val); - } -} - -/*! - * Returns the value passed to it. - */ - -function K (v) { - return v; -} diff --git a/node_modules/mongoose/node_modules/mpath/package.json b/node_modules/mongoose/node_modules/mpath/package.json deleted file mode 100644 index 02649ae7f..000000000 --- a/node_modules/mongoose/node_modules/mpath/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "mpath", - "version": "0.1.1", - "description": "{G,S}et object values using MongoDB path notation", - "main": "index.js", - "scripts": { - "test": "make test" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpath.git" - }, - "keywords": [ - "mongodb", - "path", - "get", - "set" - ], - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "devDependencies": { - "mocha": "1.6.0" - }, - "readme": "#mpath\n\n{G,S}et javascript object values using MongoDB-like path notation.\n\n###Getting\n\n```js\nvar mpath = require('mpath');\n\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.get('comments.1.title', obj) // 'exciting!'\n```\n\n`mpath.get` supports array property notation as well.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.get('comments.title', obj) // ['funny', 'exciting!']\n```\n\nArray property and indexing syntax, when used together, are very powerful.\n\n```js\nvar obj = {\n array: [\n { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }}\n , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }}\n , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }}\n , { o: { array: [{x: null }] }}\n , { o: { array: [{y: 3 }] }}\n , { o: { array: [3, 0, null] }}\n , { o: { name: 'ha' }}\n ];\n}\n\nvar found = mpath.get('array.o.array.x.b.1', obj);\n\nconsole.log(found); // prints..\n\n [ [6, undefined]\n , [2, undefined, undefined]\n , [null, 1]\n , [null]\n , [undefined]\n , [undefined, undefined, undefined]\n , undefined\n ]\n\n```\n\n#####Field selection rules:\n\nThe following rules are iteratively applied to each `segment` in the passed `path`. For example:\n\n```js\nvar path = 'one.two.14'; // path\n'one' // segment 0\n'two' // segment 1\n14 // segment 2\n```\n\n- 1) when value of the segment parent is not an array, return the value of `parent.segment`\n- 2) when value of the segment parent is an array\n - a) if the segment is an integer, replace the parent array with the value at `parent[segment]`\n - b) if not an integer, keep the array but replace each array `item` with the value returned from calling `get(remainingSegments, item)` or undefined if falsey.\n\n#####Maps\n\n`mpath.get` also accepts an optional `map` argument which receives each individual found value. The value returned from the `map` function will be used in the original found values place.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.get('comments.title', obj, function (val) {\n return 'funny' == val\n ? 'amusing'\n : val;\n});\n// ['amusing', 'exciting!']\n```\n\n###Setting\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.1.title', 'hilarious', obj)\nconsole.log(obj.comments[1].title) // 'hilarious'\n```\n\n`mpath.set` supports the same array property notation as `mpath.get`.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.title', ['hilarious', 'fruity'], obj);\n\nconsole.log(obj); // prints..\n\n { comments: [\n { title: 'hilarious' },\n { title: 'fruity' }\n ]}\n```\n\nArray property and indexing syntax can be used together also when setting.\n\n```js\nvar obj = {\n array: [\n { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }}\n , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: 'Turkey Day' }] }}\n , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }}\n , { o: { array: [{x: null }] }}\n , { o: { array: [{y: 3 }] }}\n , { o: { array: [3, 0, null] }}\n , { o: { name: 'ha' }}\n ]\n}\n\nmpath.set('array.1.o', 'this was changed', obj);\n\nconsole.log(require('util').inspect(obj, false, 1000)); // prints..\n\n{\n array: [\n { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }}\n , { o: 'this was changed' }\n , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }}\n , { o: { array: [{x: null }] }}\n , { o: { array: [{y: 3 }] }}\n , { o: { array: [3, 0, null] }}\n , { o: { name: 'ha' }}\n ];\n}\n\nmpath.set('array.o.array.x', 'this was changed too', obj);\n\nconsole.log(require('util').inspect(obj, false, 1000)); // prints..\n\n{\n array: [\n { o: { array: [{x: 'this was changed too'}, { y: 10, x: 'this was changed too'} ] }}\n , { o: 'this was changed' }\n , { o: { array: [{x: 'this was changed too'}, { x: 'this was changed too'}] }}\n , { o: { array: [{x: 'this was changed too'}] }}\n , { o: { array: [{x: 'this was changed too', y: 3 }] }}\n , { o: { array: [3, 0, null] }}\n , { o: { name: 'ha' }}\n ];\n}\n```\n\n####Setting arrays\n\nBy default, setting a property within an array to another array results in each element of the new array being set to the item in the destination array at the matching index. An example is helpful.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.title', ['hilarious', 'fruity'], obj);\n\nconsole.log(obj); // prints..\n\n { comments: [\n { title: 'hilarious' },\n { title: 'fruity' }\n ]}\n```\n\nIf we do not desire this destructuring-like assignment behavior we may instead specify the `$` operator in the path being set to force the array to be copied directly.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.$.title', ['hilarious', 'fruity'], obj);\n\nconsole.log(obj); // prints..\n\n { comments: [\n { title: ['hilarious', 'fruity'] },\n { title: ['hilarious', 'fruity'] }\n ]}\n```\n\n####Field assignment rules\n\nThe rules utilized mirror those used on `mpath.get`, meaning we can take values returned from `mpath.get`, update them, and reassign them using `mpath.set`. Note that setting nested arrays of arrays can get unweildy quickly. Check out the [tests](https://github.com/aheckmann/mpath/blob/master/test/index.js) for more extreme examples.\n\n#####Maps\n\n`mpath.set` also accepts an optional `map` argument which receives each individual value being set. The value returned from the `map` function will be used in the original values place.\n\n```js\nvar obj = {\n comments: [\n { title: 'funny' },\n { title: 'exciting!' }\n ]\n}\n\nmpath.set('comments.title', ['hilarious', 'fruity'], obj, function (val) {\n return val.length;\n});\n\nconsole.log(obj); // prints..\n\n { comments: [\n { title: 9 },\n { title: 6 }\n ]}\n```\n\n### Custom object types\n\nSometimes you may want to enact the same functionality on custom object types that store all their real data internally, say for an ODM type object. No fear, `mpath` has you covered. Simply pass the name of the property being used to store the internal data and it will be traversed instead:\n\n```js\nvar mpath = require('mpath');\n\nvar obj = {\n comments: [\n { title: 'exciting!', _doc: { title: 'great!' }}\n ]\n}\n\nmpath.get('comments.0.title', obj, '_doc') // 'great!'\nmpath.set('comments.0.title', 'nov 3rd', obj, '_doc')\nmpath.get('comments.0.title', obj, '_doc') // 'nov 3rd'\nmpath.get('comments.0.title', obj) // 'exciting'\n```\n\nWhen used with a `map`, the `map` argument comes last.\n\n```js\nmpath.get(path, obj, '_doc', map);\nmpath.set(path, val, obj, '_doc', map);\n```\n\n[LICENSE](https://github.com/aheckmann/mpath/blob/master/LICENSE)\n\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/aheckmann/mpath/issues" - }, - "homepage": "https://github.com/aheckmann/mpath", - "_id": "mpath@0.1.1", - "dist": { - "shasum": "697ddfc722affc287acce8a6eb3202a6bc9e7c28" - }, - "_from": "mpath@0.1.1", - "_resolved": "https://registry.npmjs.org/mpath/-/mpath-0.1.1.tgz" -} diff --git a/node_modules/mongoose/node_modules/mpath/test/index.js b/node_modules/mongoose/node_modules/mpath/test/index.js deleted file mode 100644 index 98e119a7f..000000000 --- a/node_modules/mongoose/node_modules/mpath/test/index.js +++ /dev/null @@ -1,1630 +0,0 @@ - -/** - * Test dependencies. - */ - -var mpath = require('../') -var assert = require('assert') - -/** - * logging helper - */ - -function log (o) { - console.log(); - console.log(require('util').inspect(o, false, 1000)); -} - -/** - * special path for override tests - */ - -var special = '_doc'; - -/** - * Tests - */ - -describe('mpath', function(){ - - /** - * test doc creator - */ - - function doc () { - var o = { first: { second: { third: [3,{ name: 'aaron' }, 9] }}}; - o.comments = [ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ]; - o.name = 'jiro'; - o.array = [ - { o: { array: [{x: {b: [4,6,8]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] }} - , { o: { array: [{x: {b: null }}, { x: { b: [null, 1]}}] }} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; - o.arr = [ - { arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true } - ] - return o; - } - - describe('get', function(){ - var o = doc(); - - it('`path` must be a string or array', function(done){ - assert.throws(function () { - mpath.get({}, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(4, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(function(){}, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(/asdf/, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(Math, o); - }, /Must be either string or array/); - assert.throws(function () { - mpath.get(Buffer, o); - }, /Must be either string or array/); - assert.doesNotThrow(function () { - mpath.get('string', o); - }); - assert.doesNotThrow(function () { - mpath.get([], o); - }); - done(); - }) - - describe('without `special`', function(){ - it('works', function(done){ - assert.equal('jiro', mpath.get('name', o)); - - assert.deepEqual( - { second: { third: [3,{ name: 'aaron' }, 9] }} - , mpath.get('first', o) - ); - - assert.deepEqual( - { third: [3,{ name: 'aaron' }, 9] } - , mpath.get('first.second', o) - ); - - assert.deepEqual( - [3,{ name: 'aaron' }, 9] - , mpath.get('first.second.third', o) - ); - - assert.deepEqual( - 3 - , mpath.get('first.second.third.0', o) - ); - - assert.deepEqual( - 9 - , mpath.get('first.second.third.2', o) - ); - - assert.deepEqual( - { name: 'aaron' } - , mpath.get('first.second.third.1', o) - ); - - assert.deepEqual( - 'aaron' - , mpath.get('first.second.third.1.name', o) - ); - - assert.deepEqual([ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], - mpath.get('comments', o)); - - assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o)); - assert.deepEqual('one', mpath.get('comments.0.name', o)); - assert.deepEqual('two', mpath.get('comments.1.name', o)); - assert.deepEqual('three', mpath.get('comments.2.name', o)); - - assert.deepEqual([{},{ comments: [{val: 'twoo'}]}] - , mpath.get('comments.2.comments', o)); - - assert.deepEqual({ comments: [{val: 'twoo'}]} - , mpath.get('comments.2.comments.1', o)); - - assert.deepEqual('twoo', mpath.get('comments.2.comments.1.comments.0.val', o)); - - done(); - }) - - it('handles array.property dot-notation', function(done){ - assert.deepEqual( - ['one', 'two', 'three'] - , mpath.get('comments.name', o) - ); - done(); - }) - - it('handles array.array notation', function(done){ - assert.deepEqual( - [undefined, undefined, [{}, {comments:[{val:'twoo'}]}]] - , mpath.get('comments.comments', o) - ); - done(); - }) - - it('handles prop.prop.prop.arrayProperty notation', function(done){ - assert.deepEqual( - [undefined, 'aaron', undefined] - , mpath.get('first.second.third.name', o) - ); - assert.deepEqual( - [1, 'aaron', 1] - , mpath.get('first.second.third.name', o, function (v) { - return undefined === v ? 1 : v; - }) - ); - done(); - }) - - it('handles array.prop.array', function(done){ - assert.deepEqual( - [ [{x: {b: [4,6,8]}}, { y: 10} ] - , [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] - , [{x: {b: null }}, { x: { b: [null, 1]}}] - , [{x: null }] - , [{y: 3 }] - , [3, 0, null] - , undefined - ] - , mpath.get('array.o.array', o) - ); - done(); - }) - - it('handles array.prop.array.index', function(done){ - assert.deepEqual( - [ {x: {b: [4,6,8]}} - , {x: {b: [1,2,3]}} - , {x: {b: null }} - , {x: null } - , {y: 3 } - , 3 - , undefined - ] - , mpath.get('array.o.array.0', o) - ); - done(); - }) - - it('handles array.prop.array.index.prop', function(done){ - assert.deepEqual( - [ {b: [4,6,8]} - , {b: [1,2,3]} - , {b: null } - , null - , undefined - , undefined - , undefined - ] - , mpath.get('array.o.array.0.x', o) - ); - done(); - }) - - it('handles array.prop.array.prop', function(done){ - assert.deepEqual( - [ [undefined, 10 ] - , [undefined, undefined, undefined] - , [undefined, undefined] - , [undefined] - , [3] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.y', o) - ); - assert.deepEqual( - [ [{b: [4,6,8]}, undefined] - , [{b: [1,2,3]}, {z: 10 }, {b: 'hi'}] - , [{b: null }, { b: [null, 1]}] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x', o) - ); - done(); - }) - - it('handles array.prop.array.prop.prop', function(done){ - assert.deepEqual( - [ [[4,6,8], undefined] - , [[1,2,3], undefined, 'hi'] - , [null, [null, 1]] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x.b', o) - ); - done(); - }) - - it('handles array.prop.array.prop.prop.index', function(done){ - assert.deepEqual( - [ [6, undefined] - , [2, undefined, 'i'] // undocumented feature (string indexing) - , [null, 1] - , [null] - , [undefined] - , [undefined, undefined, undefined] - , undefined - ] - , mpath.get('array.o.array.x.b.1', o) - ); - assert.deepEqual( - [ [6, 0] - , [2, 0, 'i'] // undocumented feature (string indexing) - , [null, 1] - , [null] - , [0] - , [0, 0, 0] - , 0 - ] - , mpath.get('array.o.array.x.b.1', o, function (v) { - return undefined === v ? 0 : v; - }) - ); - done(); - }) - - it('handles array.index.prop.prop', function(done){ - assert.deepEqual( - [{x: {b: [1,2,3]}}, { x: {z: 10 }}, { x: {b: 'hi'}}] - , mpath.get('array.1.o.array', o) - ); - assert.deepEqual( - ['hi','hi','hi'] - , mpath.get('array.1.o.array', o, function (v) { - if (Array.isArray(v)) { - return v.map(function (val) { - return 'hi'; - }) - } - return v; - }) - ); - done(); - }) - - it('handles array.array.index', function(done){ - assert.deepEqual( - [{ a: { c: 48 }}, undefined] - , mpath.get('arr.arr.1', o) - ); - assert.deepEqual( - ['woot', undefined] - , mpath.get('arr.arr.1', o, function (v) { - if (v && v.a && v.a.c) return 'woot'; - return v; - }) - ); - done(); - }) - - it('handles array.array.index.prop', function(done){ - assert.deepEqual( - [{ c: 48 }, 'woot'] - , mpath.get('arr.arr.1.a', o, function (v) { - if (undefined === v) return 'woot'; - return v; - }) - ); - assert.deepEqual( - [{ c: 48 }, undefined] - , mpath.get('arr.arr.1.a', o) - ); - mpath.set('arr.arr.1.a', [{c:49},undefined], o) - assert.deepEqual( - [{ c: 49 }, undefined] - , mpath.get('arr.arr.1.a', o) - ); - mpath.set('arr.arr.1.a', [{c:48},undefined], o) - done(); - }) - - it('handles array.array.index.prop.prop', function(done){ - assert.deepEqual( - [48, undefined] - , mpath.get('arr.arr.1.a.c', o) - ); - assert.deepEqual( - [48, 'woot'] - , mpath.get('arr.arr.1.a.c', o, function (v) { - if (undefined === v) return 'woot'; - return v; - }) - ); - done(); - }) - - }) - - describe('with `special`', function(){ - it('works', function(done){ - assert.equal('jiro', mpath.get('name', o, special)); - - assert.deepEqual( - { second: { third: [3,{ name: 'aaron' }, 9] }} - , mpath.get('first', o, special) - ); - - assert.deepEqual( - { third: [3,{ name: 'aaron' }, 9] } - , mpath.get('first.second', o, special) - ); - - assert.deepEqual( - [3,{ name: 'aaron' }, 9] - , mpath.get('first.second.third', o, special) - ); - - assert.deepEqual( - 3 - , mpath.get('first.second.third.0', o, special) - ); - - assert.deepEqual( - 4 - , mpath.get('first.second.third.0', o, special, function (v) { - return 3 === v ? 4 : v; - }) - ); - - assert.deepEqual( - 9 - , mpath.get('first.second.third.2', o, special) - ); - - assert.deepEqual( - { name: 'aaron' } - , mpath.get('first.second.third.1', o, special) - ); - - assert.deepEqual( - 'aaron' - , mpath.get('first.second.third.1.name', o, special) - ); - - assert.deepEqual([ - { name: 'one' } - , { name: 'two', _doc: { name: '2' }} - , { name: 'three' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}]}}], - mpath.get('comments', o, special)); - - assert.deepEqual({ name: 'one' }, mpath.get('comments.0', o, special)); - assert.deepEqual('one', mpath.get('comments.0.name', o, special)); - assert.deepEqual('2', mpath.get('comments.1.name', o, special)); - assert.deepEqual('3', mpath.get('comments.2.name', o, special)); - assert.deepEqual('nice', mpath.get('comments.2.name', o, special, function (v) { - return '3' === v ? 'nice' : v; - })); - - assert.deepEqual([{},{ _doc: { comments: [{ val: 2 }] }}] - , mpath.get('comments.2.comments', o, special)); - - assert.deepEqual({ _doc: { comments: [{val: 2}]}} - , mpath.get('comments.2.comments.1', o, special)); - - assert.deepEqual(2, mpath.get('comments.2.comments.1.comments.0.val', o, special)); - done(); - }) - - it('handles array.property dot-notation', function(done){ - assert.deepEqual( - ['one', '2', '3'] - , mpath.get('comments.name', o, special) - ); - assert.deepEqual( - ['one', 2, '3'] - , mpath.get('comments.name', o, special, function (v) { - return '2' === v ? 2 : v - }) - ); - done(); - }) - - it('handles array.array notation', function(done){ - assert.deepEqual( - [undefined, undefined, [{}, {_doc: { comments:[{val:2}]}}]] - , mpath.get('comments.comments', o, special) - ); - done(); - }) - - it('handles array.array.index.array', function(done){ - assert.deepEqual( - [undefined, undefined, [{val:2}]] - , mpath.get('comments.comments.1.comments', o, special) - ); - done(); - }) - - it('handles array.array.index.array.prop', function(done){ - assert.deepEqual( - [undefined, undefined, [2]] - , mpath.get('comments.comments.1.comments.val', o, special) - ); - assert.deepEqual( - ['nil', 'nil', [2]] - , mpath.get('comments.comments.1.comments.val', o, special, function (v) { - return undefined === v ? 'nil' : v; - }) - ); - done(); - }) - }) - - }) - - describe('set', function(){ - describe('without `special`', function(){ - var o = doc(); - - it('works', function(done){ - mpath.set('name', 'a new val', o, function (v) { - return 'a new val' === v ? 'changed' : v; - }); - assert.deepEqual('changed', o.name); - - mpath.set('name', 'changed', o); - assert.deepEqual('changed', o.name); - - mpath.set('first.second.third', [1,{name:'x'},9], o); - assert.deepEqual([1,{name:'x'},9], o.first.second.third); - - mpath.set('first.second.third.1.name', 'y', o) - assert.deepEqual([1,{name:'y'},9], o.first.second.third); - - mpath.set('comments.1.name', 'ttwwoo', o); - assert.deepEqual({ name: 'ttwwoo', _doc: { name: '2' }}, o.comments[1]); - - mpath.set('comments.2.comments.1.comments.0.expand', 'added', o); - assert.deepEqual( - { val: 'twoo', expand: 'added'} - , o.comments[2].comments[1].comments[0]); - - mpath.set('comments.2.comments.1.comments.2', 'added', o); - assert.equal(3, o.comments[2].comments[1].comments.length); - assert.deepEqual( - { val: 'twoo', expand: 'added'} - , o.comments[2].comments[1].comments[0]); - assert.deepEqual( - undefined - , o.comments[2].comments[1].comments[1]); - assert.deepEqual( - 'added' - , o.comments[2].comments[1].comments[2]); - - done(); - }) - - describe('array.path', function(){ - describe('with single non-array value', function(){ - it('works', function(done){ - mpath.set('arr.yep', false, o, function (v) { - return false === v ? true: v; - }); - assert.deepEqual([ - { yep: true, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true } - ], o.arr); - - mpath.set('arr.yep', false, o); - - assert.deepEqual([ - { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: false } - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('that are equal in length', function(done){ - mpath.set('arr.yep', ['one',2], o, function (v) { - return 'one' === v ? 1 : v; - }); - assert.deepEqual([ - { yep: 1, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - mpath.set('arr.yep', ['one',2], o); - - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - done(); - }) - - it('that is less than length', function(done){ - mpath.set('arr.yep', [47], o, function (v) { - return 47 === v ? 4 : v; - }); - assert.deepEqual([ - { yep: 4, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - mpath.set('arr.yep', [47], o); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 2 } - ], o.arr); - - done(); - }) - - it('that is greater than length', function(done){ - mpath.set('arr.yep', [5,6,7], o, function (v) { - return 5 === v ? 'five' : v; - }); - assert.deepEqual([ - { yep: 'five', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 6 } - ], o.arr); - - mpath.set('arr.yep', [5,6,7], o); - assert.deepEqual([ - { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 6 } - ], o.arr); - - done(); - }) - }) - }) - - describe('array.$.path', function(){ - describe('with single non-array value', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', {xtra: 'double good'}, o, function (v) { - return v && v.xtra ? 'hi' : v; - }); - assert.deepEqual([ - { yep: 'hi', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 'hi'} - ], o.arr); - - mpath.set('arr.$.yep', {xtra: 'double good'}, o); - assert.deepEqual([ - { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: {xtra:'double good'}} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', [15], o, function (v) { - return v.length === 1 ? [] : v; - }); - assert.deepEqual([ - { yep: [], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: []} - ], o.arr); - - mpath.set('arr.$.yep', [15], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: [15]} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.index.path', function(){ - it('works', function(done){ - mpath.set('arr.1.yep', 0, o, function (v) { - return 0 === v ? 'zero' : v; - }); - assert.deepEqual([ - { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 'zero' } - ], o.arr); - - mpath.set('arr.1.yep', 0, o); - assert.deepEqual([ - { yep: [15] , arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.e', 35, o, function (v) { - return 35 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 3}, { a: { c: 48 }, e: 3}, { d: 'yep', e: 3 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.e', 35, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.e', ['a','b'], o, function (v) { - return 'a' === v ? 'x' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 'x'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.e', ['a','b'], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.a.b', 36, o, function (v) { - return 36 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 3 }, e: 'a'}, { a: { c: 48, b: 3 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.a.b', 36, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, function (v) { - return 2 === v ? 'two' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 'two' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.a.b', [1,2,3,4], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.$.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.$.a.b', '$', o, function (v) { - return '$' === v ? 'dolla billz' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: 'dolla billz' }, e: 'a'}, { a: { c: 48, b: 'dolla billz' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', '$', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.$.a.b', [1], o, function (v) { - return Array.isArray(v) ? {} : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', [1], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - }) - - describe('array.array.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.0.a', 'single', o, function (v) { - return 'single' === v ? 'double' : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'double', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.arr.0.a', 'single', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, function (v) { - return 4 === v ? 3 : v; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 3, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: false } - ], o.arr); - - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: false } - ], o.arr); - - done(); - }) - }) - - describe('array.array.$.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.$.0.a', 'singles', o, function (v) { - return 0; - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 0, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('arr.arr.$.0.a', 'singles', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - mpath.set('$.arr.arr.0.a', 'single', o); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0 } - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, function (v) { - return 'nope' - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: 'nope', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - done(); - }) - }) - - describe('array.array.path.index', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.a.7', 47, o, function (v) { - return 1 - }); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,1], e: 'a'}, { a: { c: 48, b: [1], '7': 1 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - mpath.set('arr.arr.a.7', 47, o); - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0} - ], o.arr); - - done(); - }) - it('with array', function(done){ - o.arr[1].arr = [{ a: [] }, { a: [] }, { a: null }]; - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o); - - var a1 = []; - var a2 = []; - a1[7] = undefined; - a2[7] = 'woot'; - - assert.deepEqual([ - { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } - , { yep: 0, arr: [{a:a1},{a:a2},{a:null}] } - ], o.arr); - - done(); - }) - }) - - describe('handles array.array.path', function(){ - it('with single', function(done){ - o.arr[1].arr = [{},{}]; - assert.deepEqual([{},{}], o.arr[1].arr); - o.arr.push({ arr: 'something else' }); - o.arr.push({ arr: ['something else'] }); - o.arr.push({ arr: [[]] }); - o.arr.push({ arr: [5] }); - - var weird = []; - weird.e = 'xmas'; - - // test - mpath.set('arr.arr.e', 47, o, function (v) { - return 'xmas' - }); - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 'xmas'} - , { a: { c: 48, b: [1], '7': 46 }, e: 'xmas'} - , { d: 'yep', e: 'xmas' } - ] - } - , { yep: 0, arr: [{e: 'xmas'}, {e:'xmas'}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - weird.e = 47; - - mpath.set('arr.arr.e', 47, o); - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 47} - , { a: { c: 48, b: [1], '7': 46 }, e: 47} - , { d: 'yep', e: 47 } - ] - } - , { yep: 0, arr: [{e: 47}, {e:47}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - done(); - }) - it('with arrays', function(done){ - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, function (v) { - return 10; - }); - - var weird = []; - weird.e = 10; - - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 10} - , { a: { c: 48, b: [1], '7': 46 }, e: 10} - , { d: 'yep', e: 10 } - ] - } - , { yep: 0, arr: [{e: 10}, {e:10}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o); - - weird.e = 6; - - assert.deepEqual([ - { yep: [15], arr: [ - { a: [4,8,15,16,23,42,108,null], e: 1} - , { a: { c: 48, b: [1], '7': 46 }, e: 2} - , { d: 'yep', e: 3 } - ] - } - , { yep: 0, arr: [{e: 4}, {e:5}] } - , { arr: 'something else' } - , { arr: ['something else'] } - , { arr: [weird] } - , { arr: [5] } - ] - , o.arr); - - done(); - }) - }) - }) - - describe('with `special`', function(){ - var o = doc(); - - it('works', function(done){ - mpath.set('name', 'chan', o, special, function (v) { - return 'hi'; - }); - assert.deepEqual('hi', o.name); - - mpath.set('name', 'changer', o, special); - assert.deepEqual('changer', o.name); - - mpath.set('first.second.third', [1,{name:'y'},9], o, special); - assert.deepEqual([1,{name:'y'},9], o.first.second.third); - - mpath.set('first.second.third.1.name', 'z', o, special) - assert.deepEqual([1,{name:'z'},9], o.first.second.third); - - mpath.set('comments.1.name', 'ttwwoo', o, special); - assert.deepEqual({ name: 'two', _doc: { name: 'ttwwoo' }}, o.comments[1]); - - mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special, function (v) { - return 'super' - }); - assert.deepEqual( - { val: 2, expander: 'super'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - - mpath.set('comments.2.comments.1.comments.0.expander', 'adder', o, special); - assert.deepEqual( - { val: 2, expander: 'adder'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - - mpath.set('comments.2.comments.1.comments.2', 'set', o, special); - assert.equal(3, o.comments[2]._doc.comments[1]._doc.comments.length); - assert.deepEqual( - { val: 2, expander: 'adder'} - , o.comments[2]._doc.comments[1]._doc.comments[0]); - assert.deepEqual( - undefined - , o.comments[2]._doc.comments[1]._doc.comments[1]); - assert.deepEqual( - 'set' - , o.comments[2]._doc.comments[1]._doc.comments[2]); - done(); - }) - - describe('array.path', function(){ - describe('with single non-array value', function(){ - it('works', function(done){ - o.arr[1]._doc = { special: true } - - mpath.set('arr.yep', false, o, special, function (v) { - return 'yes'; - }); - assert.deepEqual([ - { yep: 'yes', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 'yes'}} - ], o.arr); - - mpath.set('arr.yep', false, o, special); - assert.deepEqual([ - { yep: false, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: false }} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('that are equal in length', function(done){ - mpath.set('arr.yep', ['one',2], o, special, function (v) { - return 2 === v ? 20 : v; - }); - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 20}} - ], o.arr); - - mpath.set('arr.yep', ['one',2], o, special); - assert.deepEqual([ - { yep: 'one', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - done(); - }) - - it('that is less than length', function(done){ - mpath.set('arr.yep', [47], o, special, function (v) { - return 80; - }); - assert.deepEqual([ - { yep: 80, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - mpath.set('arr.yep', [47], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - // add _doc to first element - o.arr[0]._doc = { yep: 46, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } - - mpath.set('arr.yep', [20], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 20, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 2}} - ], o.arr); - - done(); - }) - - it('that is greater than length', function(done){ - mpath.set('arr.yep', [5,6,7], o, special, function () { - return 'x'; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 'x', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 'x'}} - ], o.arr); - - mpath.set('arr.yep', [5,6,7], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }], _doc: { yep: 5, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 6}} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.$.path', function(){ - describe('with single non-array value', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', {xtra: 'double good'}, o, special, function (v) { - return 9; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: 9, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 9}} - ], o.arr); - - mpath.set('arr.$.yep', {xtra: 'double good'}, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: {xtra:'double good'}, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: {xtra:'double good'}}} - ], o.arr); - - done(); - }) - }) - describe('with array of values', function(){ - it('copies the value to each item in array', function(done){ - mpath.set('arr.$.yep', [15], o, special, function (v) { - return 'array' - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: 'array', arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 'array'}} - ], o.arr); - - mpath.set('arr.$.yep', [15], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: [15]}} - ], o.arr); - - done(); - }) - }) - }) - - describe('array.index.path', function(){ - it('works', function(done){ - mpath.set('arr.1.yep', 0, o, special, function (v) { - return 1; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 1}} - ], o.arr); - - mpath.set('arr.1.yep', 0, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.e', 35, o, special, function (v) { - return 30 - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 30}, { a: { c: 48 }, e: 30}, { d: 'yep', e: 30 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.e', 35, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 35}, { a: { c: 48 }, e: 35}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.e', ['a','b'], o, special, function (v) { - return 'a' === v ? 'A' : v; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'A'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.e', ['a','b'], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 47 }, e: 'a'}, { a: { c: 48 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.a.b', 36, o, special, function (v) { - return 20 - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 20 }, e: 'a'}, { a: { c: 48, b: 20 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.a.b', 36, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 36 }, e: 'a'}, { a: { c: 48, b: 36 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special, function (v) { - return v*2; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 2 }, e: 'a'}, { a: { c: 48, b: 4 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.a.b', [1,2,3,4], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 1 }, e: 'a'}, { a: { c: 48, b: 2 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.index.array.$.path.path', function(){ - it('with single value', function(done){ - mpath.set('arr.0.arr.$.a.b', '$', o, special, function (v) { - return 'dollaz' - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: 'dollaz' }, e: 'a'}, { a: { c: 48, b: 'dollaz' }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', '$', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: '$' }, e: 'a'}, { a: { c: 48, b: '$' }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.0.arr.$.a.b', [1], o, special, function (v) { - return {}; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: {} }, e: 'a'}, { a: { c: 48, b: {} }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.0.arr.$.a.b', [1], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: { b: [1] }, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.0.a', 'single', o, special, function (v) { - return 88; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 88, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.0.a', 'single', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special, function (v) { - return v*2; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 8, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.0.a', [4,8,15,16,23,42], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 4, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.$.index.path', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.$.0.a', 'singles', o, special, function (v) { - return v.toUpperCase(); - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'SINGLES', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.$.0.a', 'singles', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'singles', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('$.arr.arr.0.a', 'single', o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: 'single', e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special, function (v) { - return Array - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: Array, e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.$.0.a', [4,8,15,16,23,42], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.$.arr.0.a', [4,8,15,16,23,42,108], o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108], e: 'a'}, { a: { c: 48, b: [1] }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('array.array.path.index', function(){ - it('with single value', function(done){ - mpath.set('arr.arr.a.7', 47, o, special, function (v) { - return Object; - }); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,Object], e: 'a'}, { a: { c: 48, b: [1], '7': Object }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.a.7', 47, o, special); - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,47], e: 'a'}, { a: { c: 48, b: [1], '7': 47 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { special: true, yep: 0}} - ], o.arr); - - done(); - }) - it('with array', function(done){ - o.arr[1]._doc.arr = [{ a: [] }, { a: [] }, { a: null }]; - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special, function (v) { - return undefined === v ? 'nope' : v; - }); - - var a1 = []; - var a2 = []; - a1[7] = 'nope'; - a2[7] = 'woot'; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} - ], o.arr); - - mpath.set('arr.arr.a.7', [[null,46], [undefined, 'woot']], o, special); - - a1[7] = undefined; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { yep: [15], arr: [{ a: [4,8,15,16,23,42,108,null], e: 'a'}, { a: { c: 48, b: [1], '7': 46 }, e: 'b'}, { d: 'yep', e: 35 }] } } - , { yep: true, _doc: { arr: [{a:a1},{a:a2},{a:null}], special: true, yep: 0}} - ], o.arr); - - done(); - }) - }) - - describe('handles array.array.path', function(){ - it('with single', function(done){ - o.arr[1]._doc.arr = [{},{}]; - assert.deepEqual([{},{}], o.arr[1]._doc.arr); - o.arr.push({ _doc: { arr: 'something else' }}); - o.arr.push({ _doc: { arr: ['something else'] }}); - o.arr.push({ _doc: { arr: [[]] }}); - o.arr.push({ _doc: { arr: [5] }}); - - // test - mpath.set('arr.arr.e', 47, o, special); - - var weird = []; - weird.e = 47; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { - yep: [15] - , arr: [ - { a: [4,8,15,16,23,42,108,null], e: 47} - , { a: { c: 48, b: [1], '7': 46 }, e: 47} - , { d: 'yep', e: 47 } - ] - } - } - , { yep: true - , _doc: { - arr: [ - {e:47} - , {e:47} - ] - , special: true - , yep: 0 - } - } - , { _doc: { arr: 'something else' }} - , { _doc: { arr: ['something else'] }} - , { _doc: { arr: [weird] }} - , { _doc: { arr: [5] }} - ] - , o.arr); - - done(); - }) - it('with arrays', function(done){ - mpath.set('arr.arr.e', [[1,2,3],[4,5],null,[],[6], [7,8,9]], o, special); - - var weird = []; - weird.e = 6; - - assert.deepEqual([ - { yep: 47, arr: [{ a: { b: 47 }}, { a: { c: 48 }}, { d: 'yep' }] - , _doc: { - yep: [15] - , arr: [ - { a: [4,8,15,16,23,42,108,null], e: 1} - , { a: { c: 48, b: [1], '7': 46 }, e: 2} - , { d: 'yep', e: 3 } - ] - } - } - , { yep: true - , _doc: { - arr: [ - {e:4} - , {e:5} - ] - , special: true - , yep: 0 - } - } - , { _doc: { arr: 'something else' }} - , { _doc: { arr: ['something else'] }} - , { _doc: { arr: [weird] }} - , { _doc: { arr: [5] }} - ] - , o.arr); - - done(); - }) - }) - - }) - - describe('get/set integration', function(){ - var o = doc(); - - it('works', function(done){ - var vals = mpath.get('array.o.array.x.b', o); - - vals[0][0][2] = 10; - vals[1][0][1] = 0; - vals[1][1] = 'Rambaldi'; - vals[1][2] = [12,14]; - vals[2] = [{changed:true}, [null, ['changed','to','array']]]; - - mpath.set('array.o.array.x.b', vals, o); - - var t = [ - { o: { array: [{x: {b: [4,6,10]}}, { y: 10} ] }} - , { o: { array: [{x: {b: [1,0,3]}}, { x: {b:'Rambaldi',z: 10 }}, { x: {b: [12,14]}}] }} - , { o: { array: [{x: {b: {changed:true}}}, { x: { b: [null, ['changed','to','array']]}}]}} - , { o: { array: [{x: null }] }} - , { o: { array: [{y: 3 }] }} - , { o: { array: [3, 0, null] }} - , { o: { name: 'ha' }} - ]; - assert.deepEqual(t, o.array); - done(); - }) - - it('array.prop', function(done){ - mpath.set('comments.name', ['this', 'was', 'changed'], o); - - assert.deepEqual([ - { name: 'this' } - , { name: 'was', _doc: { name: '2' }} - , { name: 'changed' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: '3', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ], o.comments); - - mpath.set('comments.name', ['also', 'changed', 'this'], o, special); - - assert.deepEqual([ - { name: 'also' } - , { name: 'was', _doc: { name: 'changed' }} - , { name: 'changed' - , comments: [{},{ comments: [{val: 'twoo'}]}] - , _doc: { name: 'this', comments: [{},{ _doc: { comments: [{ val: 2 }] }}] }} - ], o.comments); - - done(); - }) - - }) - - describe('multiple $ use', function(){ - var o = doc(); - it('is ok', function(done){ - assert.doesNotThrow(function () { - mpath.set('arr.$.arr.$.a', 35, o); - }); - done(); - }) - }) - - it('ignores setting a nested path that doesnt exist', function(done){ - var o = doc(); - assert.doesNotThrow(function(){ - mpath.set('thing.that.is.new', 10, o); - }) - done(); - }) - }) - -}) diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/.name b/node_modules/mongoose/node_modules/mpromise/.idea/.name deleted file mode 100644 index f1198f33f..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -mpromise \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/codeStyleSettings.xml b/node_modules/mongoose/node_modules/mpromise/.idea/codeStyleSettings.xml deleted file mode 100644 index b543f7797..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/codeStyleSettings.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/encodings.xml b/node_modules/mongoose/node_modules/mpromise/.idea/encodings.xml deleted file mode 100644 index 7c62b52a1..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/encodings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/Project_Default.xml b/node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index f14638f03..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/profiles_settings.xml b/node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 6933c1eaf..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/jsLibraryMappings.xml b/node_modules/mongoose/node_modules/mpromise/.idea/jsLibraryMappings.xml deleted file mode 100644 index 0a66fda70..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/jsLibraryMappings.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/libraries/Node_js_Dependencies_for_mpromise.xml b/node_modules/mongoose/node_modules/mpromise/.idea/libraries/Node_js_Dependencies_for_mpromise.xml deleted file mode 100644 index bd5563574..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/libraries/Node_js_Dependencies_for_mpromise.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/misc.xml b/node_modules/mongoose/node_modules/mpromise/.idea/misc.xml deleted file mode 100644 index bad1ff1bc..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/misc.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/modules.xml b/node_modules/mongoose/node_modules/mpromise/.idea/modules.xml deleted file mode 100644 index ff5992df3..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/modules.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/mpromise.iml b/node_modules/mongoose/node_modules/mpromise/.idea/mpromise.iml deleted file mode 100644 index a076124fe..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/mpromise.iml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/other.xml b/node_modules/mongoose/node_modules/mpromise/.idea/other.xml deleted file mode 100644 index 82f7abedc..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/other.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/scopes/scope_settings.xml b/node_modules/mongoose/node_modules/mpromise/.idea/scopes/scope_settings.xml deleted file mode 100644 index 0d5175ca0..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/scopes/scope_settings.xml +++ /dev/null @@ -1,5 +0,0 @@ - - - - \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/vcs.xml b/node_modules/mongoose/node_modules/mpromise/.idea/vcs.xml deleted file mode 100644 index ab55cf163..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/vcs.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.idea/workspace.xml b/node_modules/mongoose/node_modules/mpromise/.idea/workspace.xml deleted file mode 100644 index 1335fab06..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.idea/workspace.xml +++ /dev/null @@ -1,626 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - C:\empeeric\mpromise\node_modules\mocha - - - - - - - - - - - - JavaScript - - - JavaScript validity issuesJavaScript - - - - - FunctionWithInconsistentReturnsJS - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $PROJECT_DIR$ - - true - - BDD - - false - - - - - - - - $PROJECT_DIR$/ - $PROJECT_DIR$/test - true - - BDD - - false - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - file://$USER_HOME$/.WebStorm7/system/extLibs/nodejs-v0.8.26-src/core-modules-sources/lib/events.js - 54 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Source - - - - - - - - - - - - diff --git a/node_modules/mongoose/node_modules/mpromise/.npmignore b/node_modules/mongoose/node_modules/mpromise/.npmignore deleted file mode 100644 index 186bb73b6..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -*.sw* -node_modules/ -.DS_Store diff --git a/node_modules/mongoose/node_modules/mpromise/.travis.yml b/node_modules/mongoose/node_modules/mpromise/.travis.yml deleted file mode 100644 index d63ba0956..000000000 --- a/node_modules/mongoose/node_modules/mpromise/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.8 - - 0.10 - - 0.11 diff --git a/node_modules/mongoose/node_modules/mpromise/History.md b/node_modules/mongoose/node_modules/mpromise/History.md deleted file mode 100644 index 1fb14083a..000000000 --- a/node_modules/mongoose/node_modules/mpromise/History.md +++ /dev/null @@ -1,59 +0,0 @@ - -0.4.3 / 2013-12-17 -================== - - * fixed; non-A+ behavior on fulfill and reject [lbeschastny](https://github.com/lbeschastny) - * tests; simplified harness + compatible with travis + compatible with windows - -0.4.2 / 2013-11-26 -================== - - * fixed; enter the domain only if not the present domain - * added; `end` returns the promise - -0.4.1 / 2013-10-26 -================== - - * Add `all` - * Longjohn for easier debugging - * can end a promise chain with an error handler - * Add ```chain``` - -0.4.0 / 2013-10-24 -================== - - * fixed; now plays nice with domains #3 [refack](https://github.com/refack) - * updated; compatibility for Promises A+ 2.0.0 [refack](https://github.com/refack) - * updated; guard against invalid arguments [refack](https://github.com/refack) - -0.3.0 / 2013-07-25 -================== - - * updated; sliced to 0.0.5 - * fixed; then is passed all fulfillment values - * use setImmediate if available - * conform to Promises A+ 1.1 - -0.2.1 / 2013-02-09 -================== - - * fixed; conformancy with A+ 1.2 - -0.2.0 / 2013-01-09 -================== - - * added; .end() - * fixed; only catch handler executions - -0.1.0 / 2013-01-08 -================== - - * cleaned up API - * customizable event names - * docs - -0.0.1 / 2013-01-07 -================== - - * original release - diff --git a/node_modules/mongoose/node_modules/mpromise/LICENSE b/node_modules/mongoose/node_modules/mpromise/LICENSE deleted file mode 100644 index 38c529daa..000000000 --- a/node_modules/mongoose/node_modules/mpromise/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/mpromise/README.md b/node_modules/mongoose/node_modules/mpromise/README.md deleted file mode 100644 index 2906f5630..000000000 --- a/node_modules/mongoose/node_modules/mpromise/README.md +++ /dev/null @@ -1,224 +0,0 @@ -#mpromise -========== - -[![Build Status](https://travis-ci.org/aheckmann/mpromise.png)](https://travis-ci.org/aheckmann/mpromise) - -A [promises/A+](https://github.com/promises-aplus/promises-spec) conformant implementation, written for [mongoose](http://mongoosejs.com). - -## installation - -``` -$ npm install mpromise -``` - -## docs - -An `mpromise` can be in any of three states, pending, fulfilled (success), or rejected (error). Once it is either fulfilled or rejected it's state can no longer be changed. - -The exports object is the Promise constructor. - -```js -var Promise = require('mpromise'); -``` - -The constructor accepts an optional function which is executed when the promise is first resolved (either fulfilled or rejected). - -```js -var promise = new Promise(fn); -``` - -This is the same as passing the `fn` to `onResolve` directly. - -```js -var promise = new Promise; -promise.onResolve(function (err, args..) { - ... -}); -``` - -### Methods - -####fulfill - -Fulfilling a promise with values: - -```js -var promise = new Promise; -promise.fulfill(args...); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####reject - -Rejecting a promise with a reason: - -```js -var promise = new Promise; -promise.reject(reason); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####resolve - -Node.js callback style promise resolution `(err, args...)`: - -```js -var promise = new Promise; -promise.resolve([reason], [arg1, arg2, ...]); -``` - -If the promise has already been fulfilled or rejected, no action is taken. - -####onFulfill - -To register a function for execution when the promise is fulfilled, pass it to `onFulfill`. When executed it will receive the arguments passed to `fulfill()`. - -```js -var promise = new Promise; -promise.onFulfill(function (a, b) { - assert.equal(3, a + b); -}); -promise.fulfill(1, 2); -``` - -The function will only be called once when the promise is fulfilled, never when rejected. - -Registering a function with `onFulfill` after the promise has already been fulfilled results in the immediate execution of the function with the original arguments used to fulfill the promise. - -```js -var promise = new Promise; -promise.fulfill(" :D "); -promise.onFulfill(function (arg) { - console.log(arg); // logs " :D " -}) -``` - -####onReject - -To register a function for execution when the promise is rejected, pass it to `onReject`. When executed it will receive the argument passed to `reject()`. - -```js -var promise = new Promise; -promise.onReject(function (reason) { - assert.equal('sad', reason); -}); -promise.reject('sad'); -``` - -The function will only be called once when the promise is rejected, never when fulfilled. - -Registering a function with `onReject` after the promise has already been rejected results in the immediate execution of the function with the original argument used to reject the promise. - -```js -var promise = new Promise; -promise.reject(" :( "); -promise.onReject(function (reason) { - console.log(reason); // logs " :( " -}) -``` - -####onResolve - -Allows registration of node.js style callbacks `(err, args..)` to handle either promise resolution type (fulfill or reject). - -```js -// fulfillment -var promise = new Promise; -promise.onResolve(function (err, a, b) { - console.log(a + b); // logs 3 -}); -promise.fulfill(1, 2); - -// rejection -var promise = new Promise; -promise.onResolve(function (err) { - if (err) { - console.log(err.message); // logs "failed" - } -}); -promise.reject(new Error('failed')); -``` - -####then - -Creates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick. - -Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification and passes its [tests](https://github.com/promises-aplus/promises-tests). - -```js -// promise.then(onFulfill, onReject); - -var p = new Promise; - -p.then(function (arg) { - return arg + 1; -}).then(function (arg) { - throw new Error(arg + ' is an error!'); -}).then(null, function (err) { - assert.ok(err instanceof Error); - assert.equal('2 is an error', err.message); -}); -p.fullfill(1); -``` - -####end - -Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception be rethrown. -You can pass an OnReject handler to `end` so that exceptions will be handled (like a final catch clause); -This method returns it's promise for easy use with `return`. - -```js -var p = new Promise; -p.then(function(){ throw new Error('shucks') }); -setTimeout(function () { - p.fulfill(); - // error was caught and swallowed by the promise returned from - // p.then(). we either have to always register handlers on - // the returned promises or we can do the following... -}, 10); - -// this time we use .end() which prevents catching thrown errors -var p = new Promise; -setTimeout(function () { - p.fulfill(); // throws "shucks" -}, 10); -return p.then(function(){ throw new Error('shucks') }).end(); // <-- -``` - - -### chain - -Allows direct promise to promise chaining (especially useful by a outside aggregating function). It doesn't use the asynchronous `resolve` algorithm and so excepts only another Promise as it's argument. - -```js -function makeMeAPromise(i) { - var p = new Promise; - p.fulfill(i); - return p; -} - -var returnPromise = initialPromise = new Promise; -for (i=0; i<10; ++i) - returnPromise = returnPromise.chain(makeMeAPromise(i)); - -initialPromise.fulfill(); -return returnPromise; -``` - -###Event names - -If you'd like to alter this implementations event names used to signify success and failure you may do so by setting `Promise.SUCCESS` or `Promise.FAILURE` respectively. - -```js -Promise.SUCCESS = 'complete'; -Promise.FAILURE = 'err'; -``` - -###Luke, use the Source -For more ideas read the [source](https://github.com/aheckmann/mpromise/blob/master/lib), [tests](https://github.com/aheckmann/mpromise/blob/master/test), or the [mongoose implementation](https://github.com/LearnBoost/mongoose/blob/3.6x/lib/promise.js). - -## license - -[MIT](https://github.com/aheckmann/mpromise/blob/master/LICENSE) diff --git a/node_modules/mongoose/node_modules/mpromise/index.js b/node_modules/mongoose/node_modules/mpromise/index.js deleted file mode 100644 index 0b3669d74..000000000 --- a/node_modules/mongoose/node_modules/mpromise/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib/promise'); diff --git a/node_modules/mongoose/node_modules/mpromise/lib/promise.js b/node_modules/mongoose/node_modules/mpromise/lib/promise.js deleted file mode 100644 index ca4e567f4..000000000 --- a/node_modules/mongoose/node_modules/mpromise/lib/promise.js +++ /dev/null @@ -1,338 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var slice = function (arr, start, end) { - return Array.prototype.slice.call(arr, start, end) -}; -var EventEmitter = require('events').EventEmitter; - -/** - * Promise constructor. - * - * _NOTE: The success and failure event names can be overridden by setting `Promise.SUCCESS` and `Promise.FAILURE` respectively._ - * - * @param {Function} back a function that accepts `fn(err, ...){}` as signature - * @inherits NodeJS EventEmitter http://nodejs.org/api/events.html#events_class_events_eventemitter - * @event `reject`: Emits when the promise is rejected (event name may be overridden) - * @event `fulfill`: Emits when the promise is fulfilled (event name may be overridden) - * @api public - */ - -function Promise(back) { - EventEmitter.call(this); - - this.emitted = {}; - this.ended = false; - if ('function' == typeof back) - this.onResolve(back); -} - -/*! - * event names - */ - -Promise.SUCCESS = 'fulfill'; -Promise.FAILURE = 'reject'; - -/*! - * Inherits from EventEmitter. - */ - -Promise.prototype.__proto__ = EventEmitter.prototype; - -/** - * Adds `listener` to the `event`. - * - * If `event` is either the success or failure event and the event has already been emitted, the`listener` is called immediately and passed the results of the original emitted event. - * - * @param {String} event - * @param {Function} callback - * @return {Promise} this - * @api public - */ - -Promise.prototype.on = function (event, callback) { - if (this.emitted[event]) - callback.apply(this, this.emitted[event]); - else - EventEmitter.prototype.on.call(this, event, callback); - - return this; -} - -/** - * Keeps track of emitted events to run them on `on`. - * - * @api private - */ - -Promise.prototype.emit = function (event) { - // ensures a promise can't be fulfill() or reject() more than once - var success = this.constructor.SUCCESS; - var failure = this.constructor.FAILURE; - - if (event == success || event == failure) { - if (this.emitted[success] || this.emitted[failure]) { - return this; - } - this.emitted[event] = slice(arguments, 1); - } - - return EventEmitter.prototype.emit.apply(this, arguments); -} - -/** - * Fulfills this promise with passed arguments. - * - * If this promise has already been fulfilled or rejected, no action is taken. - * - * @api public - */ - -Promise.prototype.fulfill = function () { - var args = slice(arguments); - return this.emit.apply(this, [this.constructor.SUCCESS].concat(args)); -} - -/** - * Rejects this promise with `reason`. - * - * If this promise has already been fulfilled or rejected, no action is taken. - * - * @api public - * @param {Object|String} reason - * @return {Promise} this - */ - -Promise.prototype.reject = function (reason) { - return this.emit(this.constructor.FAILURE, reason); -} - -/** - * Resolves this promise to a rejected state if `err` is passed or - * fulfilled state if no `err` is passed. - * - * @param {Error} [err] error or null - * @param {Object} [val] value to fulfill the promise with - * @api public - */ - -Promise.prototype.resolve = function (err, val) { - if (err) return this.reject(err); - return this.fulfill(val); -} - -/** - * Adds a listener to the SUCCESS event. - * - * @return {Promise} this - * @api public - */ - -Promise.prototype.onFulfill = function (fn) { - if (!fn) return this; - if ('function' != typeof fn) throw new TypeError("fn should be a function"); - return this.on(this.constructor.SUCCESS, fn); -} - -Promise.prototype.hasRejectListeners = function () { - return this.listeners(this.constructor.FAILURE).length > 0; -}; -/** - * Adds a listener to the FAILURE event. - * - * @return {Promise} this - * @api public - */ - -Promise.prototype.onReject = function (fn) { - if (!fn) return this; - if ('function' != typeof fn) throw new TypeError("fn should be a function"); - return this.on(this.constructor.FAILURE, fn); -} - -/** - * Adds a single function as a listener to both SUCCESS and FAILURE. - * - * It will be executed with traditional node.js argument position: - * function (err, args...) {} - * - * @param {Function} fn - * @return {Promise} this - */ - -Promise.prototype.onResolve = function (fn) { - if (!fn) return this; - if ('function' != typeof fn) throw new TypeError("fn should be a function"); - - this.on(this.constructor.FAILURE, function (err) { - fn.apply(this, [err]); - }); - - this.on(this.constructor.SUCCESS, function () { - var args = slice(arguments); - fn.apply(this, [null].concat(args)); - }); - - return this; -} - -/** - * Creates a new promise and returns it. If `onFulfill` or - * `onReject` are passed, they are added as SUCCESS/ERROR callbacks - * to this promise after the next tick. - * - * Conforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification. Read for more detail how to use this method. - * - * ####Example: - * - * var p = new Promise; - * p.then(function (arg) { - * return arg + 1; - * }).then(function (arg) { - * throw new Error(arg + ' is an error!'); - * }).then(null, function (err) { - * assert.ok(err instanceof Error); - * assert.equal('2 is an error', err.message); - * }); - * p.complete(1); - * - * @see promises-A+ https://github.com/promises-aplus/promises-spec - * @param {Function} onFulFill - * @param {Function} [onReject] - * @return {Promise} newPromise - */ - -Promise.prototype.then = function (onFulfill, onReject) { - var self = this - , retPromise = new Promise; - - if ('function' == typeof onReject) { - self.onReject(handler(retPromise, onReject)); - } else { - self.onReject(retPromise.reject.bind(retPromise)); - } - if ('function' == typeof onFulfill) { - self.onFulfill(handler(retPromise, onFulfill)); - } else { - self.onFulfill(retPromise.fulfill.bind(retPromise)); - } - - return retPromise; -}; - - -function handler(retPromise, fn) { - return function handler() { - var args = arguments; - process.nextTick( - function in_the_handler() { - if (retPromise.domain && retPromise.domain !== process.domain) retPromise.domain.enter(); - var x; - - try { - x = fn.apply(undefined, args); - } catch (err) { - if (retPromise.ended && !retPromise.hasRejectListeners()) throw err; - return retPromise.reject(err); - } - - resolve(retPromise, x); - return; - } - ); - } -} - -function resolve(promise, x) { - var then; - var type; - var done; - var reject_; - var resolve_; - - type = typeof x; - if ('undefined' == type) { - return promise.fulfill(x); - } - - if (promise === x) { - return promise.reject(new TypeError("promise and x are the same")); - } - - if (null != x) { - - if ('object' == type || 'function' == type) { - try { - then = x.then; - } catch (err) { - if (promise.ended && !promise.hasRejectListeners()) throw err; - return promise.reject(err); - } - - if ('function' == typeof then) { - try { - resolve_ = function () {var args = slice(arguments); resolve.apply(this, [promise].concat(args));}; - reject_ = promise.reject.bind(promise); - done = false; - return then.call( - x - , function fulfill() { - if (done) return; - done = true; - return resolve_.apply(this, arguments); - } - , function reject() { - if (done) return; - done = true; - return reject_.apply(this, arguments); - }) - } catch (err) { - if (done) return; - done = true; - if (promise.ended) throw err; - return promise.reject(err); - } - } - } - } - - promise.fulfill(x); -} - -/** - * Signifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception will go uncaught. - * - * ####Example: - * - * var p = new Promise; - * p.then(function(){ throw new Error('shucks') }); - * setTimeout(function () { - * p.fulfill(); - * // error was caught and swallowed by the promise returned from - * // p.then(). we either have to always register handlers on - * // the returned promises or we can do the following... - * }, 10); - * - * // this time we use .end() which prevents catching thrown errors - * var p = new Promise; - * var p2 = p.then(function(){ throw new Error('shucks') }).end(); // <-- - * setTimeout(function () { - * p.fulfill(); // throws "shucks" - * }, 10); - * - * @api public - * @param {Function} [onReject] - * @return {Promise} this - */ - -Promise.prototype.end = function (onReject) { - this.onReject(onReject); - this.ended = true; - return this; -}; - -module.exports = Promise; diff --git a/node_modules/mongoose/node_modules/mpromise/package.json b/node_modules/mongoose/node_modules/mpromise/package.json deleted file mode 100644 index 8286951b2..000000000 --- a/node_modules/mongoose/node_modules/mpromise/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "mpromise", - "version": "0.4.3", - "description": "Promises A+ conformant implementation", - "main": "index.js", - "scripts": { - "test": "node node_modules/mocha/bin/_mocha" - }, - "devDependencies": { - "longjohn": "~0.2.1", - "promises-aplus-tests": "~2.0.2", - "mocha": "~1.13.0" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mpromise" - }, - "keywords": [ - "promise", - "mongoose", - "aplus", - "a+", - "plus" - ], - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "readme": "#mpromise\n==========\n\n[![Build Status](https://travis-ci.org/aheckmann/mpromise.png)](https://travis-ci.org/aheckmann/mpromise)\n\nA [promises/A+](https://github.com/promises-aplus/promises-spec) conformant implementation, written for [mongoose](http://mongoosejs.com).\n\n## installation\n\n```\n$ npm install mpromise\n```\n\n## docs\n\nAn `mpromise` can be in any of three states, pending, fulfilled (success), or rejected (error). Once it is either fulfilled or rejected it's state can no longer be changed.\n\nThe exports object is the Promise constructor.\n\n```js\nvar Promise = require('mpromise');\n```\n\nThe constructor accepts an optional function which is executed when the promise is first resolved (either fulfilled or rejected).\n\n```js\nvar promise = new Promise(fn);\n```\n\nThis is the same as passing the `fn` to `onResolve` directly.\n\n```js\nvar promise = new Promise;\npromise.onResolve(function (err, args..) {\n ...\n});\n```\n\n### Methods\n\n####fulfill\n\nFulfilling a promise with values:\n\n```js\nvar promise = new Promise;\npromise.fulfill(args...);\n```\n\nIf the promise has already been fulfilled or rejected, no action is taken.\n\n####reject\n\nRejecting a promise with a reason:\n\n```js\nvar promise = new Promise;\npromise.reject(reason);\n```\n\nIf the promise has already been fulfilled or rejected, no action is taken.\n\n####resolve\n\nNode.js callback style promise resolution `(err, args...)`:\n\n```js\nvar promise = new Promise;\npromise.resolve([reason], [arg1, arg2, ...]);\n```\n\nIf the promise has already been fulfilled or rejected, no action is taken.\n\n####onFulfill\n\nTo register a function for execution when the promise is fulfilled, pass it to `onFulfill`. When executed it will receive the arguments passed to `fulfill()`.\n\n```js\nvar promise = new Promise;\npromise.onFulfill(function (a, b) {\n assert.equal(3, a + b);\n});\npromise.fulfill(1, 2);\n```\n\nThe function will only be called once when the promise is fulfilled, never when rejected.\n\nRegistering a function with `onFulfill` after the promise has already been fulfilled results in the immediate execution of the function with the original arguments used to fulfill the promise.\n\n```js\nvar promise = new Promise;\npromise.fulfill(\" :D \");\npromise.onFulfill(function (arg) {\n console.log(arg); // logs \" :D \"\n})\n```\n\n####onReject\n\nTo register a function for execution when the promise is rejected, pass it to `onReject`. When executed it will receive the argument passed to `reject()`.\n\n```js\nvar promise = new Promise;\npromise.onReject(function (reason) {\n assert.equal('sad', reason);\n});\npromise.reject('sad');\n```\n\nThe function will only be called once when the promise is rejected, never when fulfilled.\n\nRegistering a function with `onReject` after the promise has already been rejected results in the immediate execution of the function with the original argument used to reject the promise.\n\n```js\nvar promise = new Promise;\npromise.reject(\" :( \");\npromise.onReject(function (reason) {\n console.log(reason); // logs \" :( \"\n})\n```\n\n####onResolve\n\nAllows registration of node.js style callbacks `(err, args..)` to handle either promise resolution type (fulfill or reject).\n\n```js\n// fulfillment\nvar promise = new Promise;\npromise.onResolve(function (err, a, b) {\n console.log(a + b); // logs 3\n});\npromise.fulfill(1, 2);\n\n// rejection\nvar promise = new Promise;\npromise.onResolve(function (err) {\n if (err) {\n console.log(err.message); // logs \"failed\"\n }\n});\npromise.reject(new Error('failed'));\n```\n\n####then\n\nCreates a new promise and returns it. If `onFulfill` or `onReject` are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.\n\nConforms to [promises/A+](https://github.com/promises-aplus/promises-spec) specification and passes its [tests](https://github.com/promises-aplus/promises-tests).\n\n```js\n// promise.then(onFulfill, onReject);\n\nvar p = new Promise;\n\np.then(function (arg) {\n return arg + 1;\n}).then(function (arg) {\n throw new Error(arg + ' is an error!');\n}).then(null, function (err) {\n assert.ok(err instanceof Error);\n assert.equal('2 is an error', err.message);\n});\np.fullfill(1);\n```\n\n####end\n\nSignifies that this promise was the last in a chain of `then()s`: if a handler passed to the call to `then` which produced this promise throws, the exception be rethrown.\nYou can pass an OnReject handler to `end` so that exceptions will be handled (like a final catch clause);\nThis method returns it's promise for easy use with `return`.\n\n```js\nvar p = new Promise;\np.then(function(){ throw new Error('shucks') });\nsetTimeout(function () {\n p.fulfill();\n // error was caught and swallowed by the promise returned from\n // p.then(). we either have to always register handlers on\n // the returned promises or we can do the following...\n}, 10);\n\n// this time we use .end() which prevents catching thrown errors\nvar p = new Promise;\nsetTimeout(function () {\n p.fulfill(); // throws \"shucks\"\n}, 10);\nreturn p.then(function(){ throw new Error('shucks') }).end(); // <--\n```\n\n\n### chain\n\nAllows direct promise to promise chaining (especially useful by a outside aggregating function). It doesn't use the asynchronous `resolve` algorithm and so excepts only another Promise as it's argument.\n\n```js\nfunction makeMeAPromise(i) {\n var p = new Promise;\n p.fulfill(i);\n return p;\n}\n\nvar returnPromise = initialPromise = new Promise;\nfor (i=0; i<10; ++i)\n returnPromise = returnPromise.chain(makeMeAPromise(i));\n\ninitialPromise.fulfill();\nreturn returnPromise;\n```\n\n###Event names\n\nIf you'd like to alter this implementations event names used to signify success and failure you may do so by setting `Promise.SUCCESS` or `Promise.FAILURE` respectively.\n\n```js\nPromise.SUCCESS = 'complete';\nPromise.FAILURE = 'err';\n```\n\n###Luke, use the Source\nFor more ideas read the [source](https://github.com/aheckmann/mpromise/blob/master/lib), [tests](https://github.com/aheckmann/mpromise/blob/master/test), or the [mongoose implementation](https://github.com/LearnBoost/mongoose/blob/3.6x/lib/promise.js).\n\n## license\n\n[MIT](https://github.com/aheckmann/mpromise/blob/master/LICENSE)\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/aheckmann/mpromise/issues" - }, - "homepage": "https://github.com/aheckmann/mpromise", - "_id": "mpromise@0.4.3", - "dist": { - "shasum": "a80553d1136d86e775e4624192cdebfaeec57936" - }, - "_from": "mpromise@0.4.3", - "_resolved": "https://registry.npmjs.org/mpromise/-/mpromise-0.4.3.tgz" -} diff --git a/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js b/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js deleted file mode 100644 index 579c462ee..000000000 --- a/node_modules/mongoose/node_modules/mpromise/test/promise.domain.test.js +++ /dev/null @@ -1,32 +0,0 @@ -var Promise = require('../') - , Domain = require('domain') - , assert = require('assert'); - -var next = 'function' == typeof setImmediate - ? setImmediate - : process.nextTick; - -describe("domains", function () { - it("exceptions should not breakout of domain bounderies", function (done) { - if (process.version.indexOf('v0.8') == 0) return done(); - var d = Domain.create(); - d.once('error', function (err) { - assert.equal(err.message, 'gaga'); - done() - }); - - var p = new Promise(); - - d.run(function () { - p.then(function () { - - }).then(function () { - throw new Error('gaga'); - }).end(); - }); - - next(function () { - p.fulfill(); - }) - }); -}); diff --git a/node_modules/mongoose/node_modules/mpromise/test/promise.test.js b/node_modules/mongoose/node_modules/mpromise/test/promise.test.js deleted file mode 100644 index 5611931e7..000000000 --- a/node_modules/mongoose/node_modules/mpromise/test/promise.test.js +++ /dev/null @@ -1,310 +0,0 @@ -/*global describe,it */ -if (process.version.indexOf('v0.11') == -1) require("longjohn"); -/** - * Module dependencies. - */ - -var assert = require('assert'); -var Promise = require('../'); - -/** - * Test. - */ - -describe('promise', function(){ - it('events fire right after fulfill()', function(done){ - var promise = new Promise() - , called = 0; - - promise.on('fulfill', function (a, b) { - assert.equal(a, '1'); - assert.equal(b, '2'); - called++; - }); - - promise.fulfill('1', '2'); - - promise.on('fulfill', function (a, b) { - assert.equal(a, '1'); - assert.equal(b, '2'); - called++; - }); - - assert.equal(2, called); - done(); - }); - - it('events fire right after reject()', function(done){ - var promise = new Promise() - , called = 0; - - promise.on('reject', function (err) { - assert.ok(err instanceof Error); - called++; - }); - - promise.reject(new Error('booyah')); - - promise.on('reject', function (err) { - assert.ok(err instanceof Error); - called++; - }); - - assert.equal(2, called); - done() - }); - - describe('onResolve()', function(){ - it('from constructor works', function(done){ - var called = 0; - - var promise = new Promise(function (err) { - assert.ok(err instanceof Error); - called++; - }) - - promise.reject(new Error('dawg')); - - assert.equal(1, called); - done(); - }); - - it('after fulfill()', function(done){ - var promise = new Promise() - , called = 0; - - promise.fulfill('woot'); - - promise.onResolve(function (err, data){ - assert.equal(data,'woot'); - called++; - }); - - promise.onResolve(function (err, data){ - assert.strictEqual(err, null); - called++; - }); - - assert.equal(2, called); - done(); - }) - }); - - describe('onFulfill shortcut', function(){ - it('works', function(done){ - var promise = new Promise() - , called = 0; - - promise.onFulfill(function (woot) { - assert.strictEqual(woot, undefined); - called++; - }); - - promise.fulfill(); - - assert.equal(1, called); - done(); - }) - }) - - describe('onReject shortcut', function(){ - it('works', function(done){ - var promise = new Promise() - , called = 0; - - promise.onReject(function (err) { - assert.ok(err instanceof Error); - called++; - }); - - promise.reject(new Error); - assert.equal(1, called); - done(); - }) - }); - - describe('return values', function(){ - it('on()', function(done){ - var promise = new Promise() - assert.ok(promise.on('jump', function(){}) instanceof Promise); - done() - }); - - it('onFulfill()', function(done){ - var promise = new Promise() - assert.ok(promise.onFulfill(function(){}) instanceof Promise); - done(); - }) - it('onReject()', function(done){ - var promise = new Promise() - assert.ok(promise.onReject(function(){}) instanceof Promise); - done(); - }) - it('onResolve()', function(done){ - var promise = new Promise() - assert.ok(promise.onResolve(function(){}) instanceof Promise); - done(); - }) - }) - - describe('casting errors', function(){ - describe('reject()', function(){ - it('does not cast arguments to Error', function(done){ - var p = new Promise(function (err, arg) { - assert.equal(3, err); - done(); - }); - - p.reject(3); - }) - }) - }) - - describe('then', function(){ - describe('catching', function(){ - it('should not catch returned promise fulfillments', function(done){ - var errorSentinal - , p = new Promise - , p2 = p.then(function () { throw errorSentinal = new Error("boo!") }); - - p.fulfill(); - done(); - }); - - - it('should not catch returned promise fulfillments even async', function (done) { - var errorSentinal - , p = new Promise - , p2 = p.then(function () { throw errorSentinal = new Error("boo!") }); - - setTimeout(function () { - p.fulfill(); - done(); - }, 10); - }); - - - it('can be disabled using .end()', function(done){ - if (process.version.indexOf('v0.8') == 0) return done(); - var errorSentinal - , overTimeout - , domain = require('domain').create(); - - domain.once('error', function (err) { - assert(err, errorSentinal); - clearTimeout(overTimeout); - done() - }); - - domain.run(function () { - var p = new Promise; - var p2 = p.then(function () { - throw errorSentinal = new Error('shucks') - }); - p2.end(); - - p.fulfill(); - }); - overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 10); - }); - - - it('can be disabled using .end() even when async', function (done) { - if (process.version.indexOf('v0.8') == 0) return done(); - var errorSentinal - , overTimeout - , domain = require('domain').create(); - - domain.on('error', function (err) { - assert(err, errorSentinal); - clearTimeout(overTimeout); - done() - }); - - domain.run(function () { - var p = new Promise; - var p2 = p.then(function () { - throw errorSentinal = new Error("boo!") - }); - p2.end(); - - setTimeout(function () {p.fulfill();}, 10); - }); - overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 20); - }); - - - it('can be handled using .end() so no throwing', function (done) { - var errorSentinal - , overTimeout - , domain = require('domain').create(); - - domain.run(function () { - var p = new Promise; - var p2 = p.then(function () { - throw errorSentinal = new Error("boo!") - }); - p2.end(function (err) { - assert.equal(err, errorSentinal); - clearTimeout(overTimeout); - done() - }); - - setTimeout(function () {p.fulfill();}, 10); - }); - overTimeout = setTimeout(function () { done(new Error('error was swallowed')); }, 20); - }); - - }); - - it('persistent', function(done){ - var p = new Promise - v = null; - - function ensure (val) { - v = v || val; - assert.equal(v, val); - } - - function guard () { - throw new Error('onReject should not be called'); - } - - p.then(ensure, guard).end(); - - p.fulfill('foo'); - p.fulfill('bar'); - p.reject(new Error('baz')); - - p.then(ensure, guard).end(); - - setTimeout(done, 0); - }) - - - it('accepts multiple completion values', function(done){ - var p = new Promise; - - p.then(function (a, b) { - assert.equal(2, arguments.length); - assert.equal('hi', a); - assert.equal(4, b); - done(); - }, done).end(); - - p.fulfill('hi', 4); - }) - }); - - - describe('end', function () { - it("should return the promise", function (done) { - var p = new Promise; - var p1 = p.end(); - assert.equal(p, p1); - done(); - }); - }); - - -}); diff --git a/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js b/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js deleted file mode 100644 index 39f146a37..000000000 --- a/node_modules/mongoose/node_modules/mpromise/test/promises.Aplus.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Module dependencies. - */ - -var Promise = require('../lib/promise'); -var aplus = require('promises-aplus-tests'); - -// tests - -var adapter = {}; -adapter.fulfilled = function (value) { - var p = new Promise; - p.fulfill(value); - return p; -}; -adapter.rejected = function (reason) { - var p = new Promise; - p.reject(reason); - return p; -} -adapter.deferred = function () { - var p = new Promise; - return { - promise: p, reject: p.reject.bind(p), resolve: p.fulfill.bind(p) - } -} - -it("run A+ suite", function (done) { - this.timeout(60000); - aplus(adapter, { - reporter: 'spec', slow: 1 - -// , bail:true -// , grep:'2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError` as the reason. via return from a fulfilled promise' - }, function (err) { - done(err); - }); -}); - diff --git a/node_modules/mongoose/node_modules/mquery/.npmignore b/node_modules/mongoose/node_modules/mquery/.npmignore deleted file mode 100644 index be106cacd..000000000 --- a/node_modules/mongoose/node_modules/mquery/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.sw* -node_modules/ diff --git a/node_modules/mongoose/node_modules/mquery/.travis.yml b/node_modules/mongoose/node_modules/mquery/.travis.yml deleted file mode 100644 index 4dc3a7d47..000000000 --- a/node_modules/mongoose/node_modules/mquery/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js -node_js: - - 0.8 - - 0.10 - - 0.11 -services: - - mongodb diff --git a/node_modules/mongoose/node_modules/mquery/History.md b/node_modules/mongoose/node_modules/mquery/History.md deleted file mode 100644 index 2e1064010..000000000 --- a/node_modules/mongoose/node_modules/mquery/History.md +++ /dev/null @@ -1,119 +0,0 @@ - -0.4.1 / 2014-01-07 -================== - - * fixed; inclusive/exclusive logic - -0.4.0 / 2014-01-06 -================== - - * added; selected() - * added; selectedInclusively() - * added; selectedExclusively() - -0.3.3 / 2013-11-14 -================== - - * Fix Mongo DB Dependency #20 [rschmukler](https://github.com/rschmukler) - -0.3.2 / 2013-09-06 -================== - - * added; geometry support for near() - -0.3.1 / 2013-08-22 -================== - - * fixed; update retains key order #19 - -0.3.0 / 2013-08-22 -================== - - * less hardcoded isNode env detection #18 [vshulyak](https://github.com/vshulyak) - * added; validation of findAndModify varients - * clone update doc before execution - * stricter env checks - -0.2.7 / 2013-08-2 -================== - - * Now support GeoJSON point values for Query#near - -0.2.6 / 2013-07-30 -================== - - * internally, 'asc' and 'desc' for sorts are now converted into 1 and -1, respectively - -0.2.5 / 2013-07-30 -================== - - * updated docs - * changed internal representation of `sort` to use objects instead of arrays - -0.2.4 / 2013-07-25 -================== - - * updated; sliced to 0.0.5 - -0.2.3 / 2013-07-09 -================== - - * now using a callback in collection.find instead of directly calling toArray() on the cursor [ebensing](https://github.com/ebensing) - -0.2.2 / 2013-07-09 -================== - - * now exposing mongodb export to allow for better testing [ebensing](https://github.com/ebensing) - -0.2.1 / 2013-07-08 -================== - - * select no longer accepts arrays as parameters [ebensing](https://github.com/ebensing) - -0.2.0 / 2013-07-05 -================== - - * use $geoWithin by default - -0.1.2 / 2013-07-02 -================== - - * added use$geoWithin flag [ebensing](https://github.com/ebensing) - * fix read preferences typo [ebensing](https://github.com/ebensing) - * fix reference to old param name in exists() [ebensing](https://github.com/ebensing) - -0.1.1 / 2013-06-24 -================== - - * fixed; $intersects -> $geoIntersects #14 [ebensing](https://github.com/ebensing) - * fixed; Retain key order when copying objects #15 [ebensing](https://github.com/ebensing) - * bump mongodb dev dep - -0.1.0 / 2013-05-06 -================== - - * findAndModify; return the query - * move mquery.proto.canMerge to mquery.canMerge - * overwrite option now works with non-empty objects - * use strict mode - * validate count options - * validate distinct options - * add aggregate to base collection methods - * clone merge arguments - * clone merged update arguments - * move subclass to mquery.prototype.toConstructor - * fixed; maxScan casing - * use regexp-clone - * added; geometry/intersects support - * support $and - * near: do not use "radius" - * callbacks always fire on next turn of loop - * defined collection interface - * remove time from tests - * clarify goals - * updated docs; - -0.0.1 / 2012-12-15 -================== - - * initial release diff --git a/node_modules/mongoose/node_modules/mquery/LICENSE b/node_modules/mongoose/node_modules/mquery/LICENSE deleted file mode 100644 index 38c529daa..000000000 --- a/node_modules/mongoose/node_modules/mquery/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2012 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/mquery/Makefile b/node_modules/mongoose/node_modules/mquery/Makefile deleted file mode 100644 index 2ad4e4713..000000000 --- a/node_modules/mongoose/node_modules/mquery/Makefile +++ /dev/null @@ -1,5 +0,0 @@ - -test: - @./node_modules/.bin/mocha $(T) $(TESTS) - -.PHONY: test diff --git a/node_modules/mongoose/node_modules/mquery/README.md b/node_modules/mongoose/node_modules/mquery/README.md deleted file mode 100644 index fed59b8f2..000000000 --- a/node_modules/mongoose/node_modules/mquery/README.md +++ /dev/null @@ -1,1020 +0,0 @@ -#mquery -=========== - -`mquery` is a fluent mongodb query builder designed to run in multiple environments. As of v0.1, `mquery` runs on `Node.js` only with support for the MongoDB shell and browser environments planned for upcoming releases. - -##Features - - - fluent query builder api - - custom base query support - - MongoDB 2.4 geoJSON support - - method + option combinations validation - - node.js driver compatibility - - environment detection - - [debug](https://github.com/visionmedia/debug) support - - separated collection implementations for maximum flexibility - -[![Build Status](https://travis-ci.org/aheckmann/mquery.png)](https://travis-ci.org/aheckmann/mquery) - -##Use - -```js -require('mongodb').connect(uri, function (err, db) { - if (err) return handleError(err); - - // get a collection - var collection = db.collection('artists'); - - // pass it to the constructor - mquery(collection).find({..}, callback); - - // or pass it to the collection method - mquery().find({..}).collection(collection).exec(callback) - - // or better yet, create a custom query constructor that has it always set - var Artist = mquery(collection).toConstructor(); - Artist().find(..).where(..).exec(callback) -}) -``` - -`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native). - - -##Fluent API - -###find() - -Declares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().find() -mquery().find(match) -mquery().find(callback) -mquery().find(match, function (err, docs) { - assert(Array.isArray(docs)); -}) -``` - -###findOne() - -Declares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().findOne() -mquery().findOne(match) -mquery().findOne(callback) -mquery().findOne(match, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) -``` - -###count() - -Declares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().count() -mquery().count(match) -mquery().count(callback) -mquery().count(match, function (err, number){ - console.log('we found %d matching documents', number); -}) -``` - -###remove() - -Declares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed. - -```js -mquery().remove() -mquery().remove(match) -mquery().remove(callback) -mquery().remove(match, function (err){}) -``` - -###update() - -Declares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`. - -```js -mquery().update() -mquery().update(match, updateDocument) -mquery().update(match, updateDocument, options) - -// the following all execute the command -mquery().update(callback) -mquery().update({$set: updateDocument, callback) -mquery().update(match, updateDocument, callback) -mquery().update(match, updateDocument, options, function (err, result){}) -mquery().update(true) // executes (unsafe write) -``` - -#####the update document - -All paths passed that are not `$atomic` operations will become `$set` ops. For example: - -```js -mquery(collection).where({ _id: id }).update({ title: 'words' }, callback) -``` - -becomes - -```js -collection.update({ _id: id }, { $set: { title: 'words' }}, callback) -``` - -This behavior can be overridden using the `overwrite` option (see below). - -#####options - -Options are passed to the `setOptions()` method. - -- overwrite - -Passing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection. - -```js -var q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true }); -q.update({ }, callback); // overwrite with an empty doc -``` - -The `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is. - -```js -// create a base query -var base = mquery({ _id: 108 }).collection(collection).toConstructor(); - -base().findOne(function (err, doc) { - console.log(doc); // { _id: 108, name: 'cajon' }) - - base().setOptions({ overwrite: true }).update({ changed: true }, function (err) { - base.findOne(function (err, doc) { - console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten - }); - }); -}) -``` - -- multi - -Updates only modify a single document by default. To update multiple documents, set the `multi` option to `true`. - -```js -mquery() - .collection(coll) - .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback) - -// another way of doing it -mquery({ name: /^match/ }) - .collection(coll) - .setOptions({ multi: true }) - .update({ $addToSet: { arr: 4 }}, callback) - -// update multiple documents with an empty doc -var q = mquery(collection).where({ name: /^match/ }); -q.setOptions({ multi: true, overwrite: true }) -q.update({ }); -q.update(function (err, result) { - console.log(arguments); -}); -``` - -###findOneAndUpdate() - -Declares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed. - -When executed, the first matching document (if found) is modified according to the update document and passed back to the callback. - -#####options - -Options are passed to the `setOptions()` method. - -- `new`: boolean - true to return the modified document rather than the original. defaults to true -- `upsert`: boolean - creates the object if it doesn't exist. defaults to false -- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update - -```js -query.findOneAndUpdate() -query.findOneAndUpdate(updateDocument) -query.findOneAndUpdate(match, updateDocument) -query.findOneAndUpdate(match, updateDocument, options) - -// the following all execute the command -query.findOneAndUpdate(callback) -query.findOneAndUpdate(updateDocument, callback) -query.findOneAndUpdate(match, updateDocument, callback) -query.findOneAndUpdate(match, updateDocument, options, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) - ``` - -###findOneAndRemove() - -Declares this query a _findAndModify_ with remove query. Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed. - -When executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback. - -#####options - -Options are passed to the `setOptions()` method. - -- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove - -```js -A.where().findOneAndRemove() -A.where().findOneAndRemove(match) -A.where().findOneAndRemove(match, options) - -// the following all execute the command -A.where().findOneAndRemove(callback) -A.where().findOneAndRemove(match, callback) -A.where().findOneAndRemove(match, options, function (err, doc) { - if (doc) { - // the document may not be found - console.log(doc); - } -}) - ``` - -###distinct() - -Declares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed. - -```js -mquery().distinct() -mquery().distinct(match) -mquery().distinct(match, field) -mquery().distinct(field) - -// the following all execute the command -mquery().distinct(callback) -mquery().distinct(field, callback) -mquery().distinct(match, callback) -mquery().distinct(match, field, function (err, result) { - console.log(result); -}) -``` - -###exec() - -Executes the query. - -```js -mquery().findOne().where('route').intersects(polygon).exec(function (err, docs){}) -``` - -------------- - -###all() - -Specifies an `$all` query condition - -```js -mquery().where('permission').all(['read', 'write']) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/) - -###and() - -Specifies arguments for an `$and` condition - -```js -mquery().and([{ color: 'green' }, { status: 'ok' }]) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/) - -###box() - -Specifies a `$box` condition - -```js -var lowerLeft = [40.73083, -73.99756] -var upperRight= [40.741404, -73.988135] - -mquery().where('location').within().box(lowerLeft, upperRight) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/) - -###circle() - -Specifies a `$center` or `$centerSphere` condition. - -```js -var area = { center: [50, 50], radius: 10, unique: true } -query.where('loc').within().circle(area) -query.circle('loc', area); - -// for spherical calculations -var area = { center: [50, 50], radius: 10, unique: true, spherical: true } -query.where('loc').within().circle(area) -query.circle('loc', area); -``` - -- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/) -- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/) - -###elemMatch() - -Specifies an `$elemMatch` condition - -```js -query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - -query.elemMatch('comment', function (elem) { - elem.where('author').equals('autobot'); - elem.where('votes').gte(5); -}) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/) - -###equals() - -Specifies the complementary comparison value for the path specified with `where()`. - -```js -mquery().where('age').equals(49); - -// is the same as - -mquery().where({ 'age': 49 }); -``` - -###exists() - -Specifies an `$exists` condition - -```js -// { name: { $exists: true }} -mquery().where('name').exists() -mquery().where('name').exists(true) -mquery().exists('name') - -// { name: { $exists: false }} -mquery().where('name').exists(false); -mquery().exists('name', false); -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/) - -###geometry() - -Specifies a `$geometry` condition - -```js -var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] -query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - -// or -var polyB = [[ 0, 0 ], [ 1, 1 ]] -query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - -// or -var polyC = [ 0, 0 ] -query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - -// or -query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - -// or -query.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] }) -``` - -`geometry()` **must** come after `intersects()`, `within()`, or `near()`. - -The `object` argument must contain `type` and `coordinates` properties. - -- type `String` -- coordinates `Array` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/) - -###gt() - -Specifies a `$gt` query condition. - -```js -mquery().where('clicks').gt(999) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/) - -###gte() - -Specifies a `$gte` query condition. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/) - -```js -mquery().where('clicks').gte(1000) -``` - -###in() - -Specifies an `$in` query condition. - -```js -mquery().where('author_id').in([3, 48901, 761]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/) - -###intersects() - -Declares an `$geoIntersects` query for `geometry()`. - -```js -query.where('path').intersects().geometry({ - type: 'LineString' - , coordinates: [[180.0, 11.0], [180, 9.0]] -}) - -// geometry arguments are supported -query.where('path').intersects({ - type: 'LineString' - , coordinates: [[180.0, 11.0], [180, 9.0]] -}) -``` - -**Must** be used after `where()`. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/) - -###lt() - -Specifies a `$lt` query condition. - -```js -mquery().where('clicks').lt(50) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/) - -###lte() - -Specifies a `$lte` query condition. - -```js -mquery().where('clicks').lte(49) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/) - -###maxDistance() - -Specifies a `$maxDistance` query condition. - -```js -mquery().where('location').near({ center: [139, 74.3] }).maxDistance(5) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/) - -###mod() - -Specifies a `$mod` condition - -```js -mquery().where('count').mod(2, 0) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/) - -###ne() - -Specifies a `$ne` query condition. - -```js -mquery().where('status').ne('ok') -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/) - -###nin() - -Specifies an `$nin` query condition. - -```js -mquery().where('author_id').nin([3, 48901, 761]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/) - -###nor() - -Specifies arguments for an `$nor` condition. - -```js -mquery().nor([{ color: 'green' }, { status: 'ok' }]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/) - -###near() - -Specifies arguments for a `$near` or `$nearSphere` condition. - -These operators return documents sorted by distance. - -####Example - -```js -query.where('loc').near({ center: [10, 10] }); -query.where('loc').near({ center: [10, 10], maxDistance: 5 }); -query.near('loc', { center: [10, 10], maxDistance: 5 }); - -// GeoJSON -query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }}); -query.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true }); -query.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] }); - -// For a $nearSphere condition, pass the `spherical` option. -query.near({ center: [10, 10], maxDistance: 5, spherical: true }); -``` - -[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing) - -###or() - -Specifies arguments for an `$or` condition. - -```js -mquery().or([{ color: 'red' }, { status: 'emergency' }]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/) - -###polygon() - -Specifies a `$polygon` condition - -```js -mquery().where('loc').within().polygon([10,20], [13, 25], [7,15]) -mquery().polygon('loc', [10,20], [13, 25], [7,15]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/) - -###regex() - -Specifies a `$regex` query condition. - -```js -mquery().where('name').regex(/^sixstepsrecords/) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/) - -###select() - -Specifies which document fields to include or exclude - -```js -// 1 means include, 0 means exclude -mquery().select({ name: 1, address: 1, _id: 0 }) - -// or - -mquery().select('name address -_id') -``` - -#####String syntax - -When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. - -```js -// include a and b, exclude c -query.select('a b -c'); - -// or you may use object notation, useful when -// you have keys already prefixed with a "-" -query.select({a: 1, b: 1, c: 0}); -``` - -_Cannot be used with `distinct()`._ - -###selected() - -Determines if the query has selected any fields. - -```js -var query = mquery(); -query.selected() // false -query.select('-name'); -query.selected() // true -``` - -###selectedInclusively() - -Determines if the query has selected any fields inclusively. - -```js -var query = mquery().select('name'); -query.selectedInclusively() // true - -var query = mquery(); -query.selected() // false -query.select('-name'); -query.selectedInclusively() // false -query.selectedExclusively() // true -``` - -###selectedExclusively() - -Determines if the query has selected any fields exclusively. - -```js -var query = mquery().select('-name'); -query.selectedExclusively() // true - -var query = mquery(); -query.selected() // false -query.select('name'); -query.selectedExclusively() // false -query.selectedInclusively() // true -``` - -###size() - -Specifies a `$size` query condition. - -```js -mquery().where('someArray').size(6) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/) - -###slice() - -Specifies a `$slice` projection for a `path` - -```js -mquery().where('comments').slice(5) -mquery().where('comments').slice(-5) -mquery().where('comments').slice([-10, 5]) -``` - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/) - -###within() - -Sets a `$geoWithin` or `$within` argument for geo-spatial queries. - -```js -mquery().within().box() -mquery().within().circle() -mquery().within().geometry() - -mquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); -mquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); -mquery().where('loc').within({ polygon: [[],[],[],[]] }); - -mquery().where('loc').within([], [], []) // polygon -mquery().where('loc').within([], []) // box -mquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry -``` - -As of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin). - -**Must** be used after `where()`. - -[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/) - -###where() - -Specifies a `path` for use with chaining - -```js -// instead of writing: -mquery().find({age: {$gte: 21, $lte: 65}}); - -// we can instead write: -mquery().where('age').gte(21).lte(65); - -// passing query conditions is permitted too -mquery().find().where({ name: 'vonderful' }) - -// chaining -mquery() -.where('age').gte(21).lte(65) -.where({ 'name': /^vonderful/i }) -.where('friends').slice(10) -.exec(callback) -``` - -###$where() - -Specifies a `$where` condition. - -Use `$where` when you need to select documents using a JavaScript expression. - -```js -query.$where('this.comments.length > 10 || this.name.length > 5').exec(callback) - -query.$where(function () { - return this.comments.length > 10 || this.name.length > 5; -}) -``` - -Only use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using. - ------------ - -###batchSize() - -Specifies the batchSize option. - -```js -query.batchSize(100) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/) - -###comment() - -Specifies the comment option. - -```js -query.comment('login query'); -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/) - -###hint() - -Sets query hints. - -```js -mquery().hint({ indexA: 1, indexB: -1 }) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/) - -###limit() - -Specifies the limit option. - -```js -query.limit(20) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/) - -###maxScan() - -Specifies the maxScan option. - -```js -query.maxScan(100) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/) - -###skip() - -Specifies the skip option. - -```js -query.skip(100).limit(20) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/) - -###sort() - -Sets the query sort order. - -If an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. - -If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - -```js -// these are equivalent -query.sort({ field: 'asc', test: -1 }); -query.sort('field -test'); -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/) - -###read() - -Sets the readPreference option for the query. - -```js -mquery().read('primary') -mquery().read('p') // same as primary - -mquery().read('primaryPreferred') -mquery().read('pp') // same as primaryPreferred - -mquery().read('secondary') -mquery().read('s') // same as secondary - -mquery().read('secondaryPreferred') -mquery().read('sp') // same as secondaryPreferred - -mquery().read('nearest') -mquery().read('n') // same as nearest - -// specifying tags -mquery().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) -``` - -#####Preferences: - -- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. -- `secondary` - Read from secondary if available, otherwise error. -- `primaryPreferred` - Read from primary if available, otherwise a secondary. -- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary. -- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - -Aliases - -- `p` primary -- `pp` primaryPreferred -- `s` secondary -- `sp` secondaryPreferred -- `n` nearest - -Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - -###slaveOk() - -Sets the slaveOk option. `true` allows reading from secondaries. - -**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2 - -```js -query.slaveOk() // true -query.slaveOk(true) -query.slaveOk(false) -``` - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/) - -###snapshot() - -Specifies this query as a snapshot query. - -```js -mquery().snapshot() // true -mquery().snapshot(true) -mquery().snapshot(false) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/) - -###tailable() - -Sets tailable option. - -```js -mquery().tailable() <== true -mquery().tailable(true) -mquery().tailable(false) -``` - -_Cannot be used with `distinct()`._ - -[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/) - -##Helpers - -###collection() - -Sets the querys collection. - -```js -mquery().collection(aCollection) -``` - - -###merge(object) - -Merges other mquery or match condition objects into this one. When an muery instance is passed, its match conditions, field selection and options are merged. - -```js -var drum = mquery({ type: 'drum' }).collection(instruments); -var redDrum = mqery({ color: 'red' }).merge(drum); -redDrum.count(function (err, n) { - console.log('there are %d red drums', n); -}) -``` - -Internally uses `mquery.canMerge` to determine validity. - -###setOptions(options) - -Sets query options. - -```js -mquery().setOptions({ collection: coll, limit: 20 }) -``` - -#####options - -- [tailable](#tailable) * -- [sort](#sort) * -- [limit](#limit) * -- [skip](#skip) * -- [maxScan](#maxScan) * -- [batchSize](#batchSize) * -- [comment](#comment) * -- [snapshot](#snapshot) * -- [hint](#hint) * -- [slaveOk](#slaveOk) * -- [safe](http://docs.mongodb.org/manual/reference/write-concern/): Boolean - passed through to the collection. Setting to `true` is equivalent to `{ w: 1 }` -- [collection](#collection): the collection to query against - -_* denotes a query helper method is also available_ - -###mquery.canMerge(conditions) - -Determines if `conditions` can be merged using `mquery().merge()`. - -```js -var query = mquery({ type: 'drum' }); -var okToMerge = mquery.canMerge(anObject) -if (okToMerge) { - query.merge(anObject); -} -``` - -##mquery.use$geoWithin - -MongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls. - -If you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`. - -```js -mquery.use$geoWithin = false; -``` - -##Custom Base Queries - -Often times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original. - -```js -var greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor(); - -// use it! -greatMovies().count(function (err, n) { - console.log('There are %d great movies', n); -}); - -greatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) { - console.log(docs); -}); -``` - -##Validation - -Method and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development. - -##Debug support - -Debug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable: - - DEBUG=mquery node yourprogram.js - -Read the debug module documentation for more details. - -##Future goals - - - mongo shell compatibility - - browser compatibility - - mongoose compatibility - -## Installation - - $ npm install mquery - -## License - -[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE) - diff --git a/node_modules/mongoose/node_modules/mquery/index.js b/node_modules/mongoose/node_modules/mquery/index.js deleted file mode 100644 index 51b6f49ce..000000000 --- a/node_modules/mongoose/node_modules/mquery/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = exports = require('./lib/mquery'); diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js b/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js deleted file mode 100644 index b2882e5aa..000000000 --- a/node_modules/mongoose/node_modules/mquery/lib/collection/collection.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -/** - * methods a collection must implement - */ - -var names = 'find findOne update remove count distict findAndModify aggregate'; -var methods = names.split(' '); - -/** - * Collection base class from which implementations inherit - */ - -function Collection () {} - -for (var i = 0, len = methods.length; i < len; ++i) { - var method = methods[i]; - Collection.prototype[method] = notImplemented(method); -} - -module.exports = exports = Collection; -Collection.methods = methods; - -/** - * creates a function which throws an implementation error - */ - -function notImplemented (method) { - return function () { - throw new Error('collection.' + method + ' not implemented'); - } -} - diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/index.js b/node_modules/mongoose/node_modules/mquery/lib/collection/index.js deleted file mode 100644 index 8ea60903f..000000000 --- a/node_modules/mongoose/node_modules/mquery/lib/collection/index.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var env = require('../env') - -if ('unknown' == env.type) { - throw new Error('Unknown environment') -} - -module.exports = - env.isNode ? require('./node') : - env.isMongo ? require('./mongo') : - require('./browser'); - diff --git a/node_modules/mongoose/node_modules/mquery/lib/collection/node.js b/node_modules/mongoose/node_modules/mquery/lib/collection/node.js deleted file mode 100644 index 577d437d9..000000000 --- a/node_modules/mongoose/node_modules/mquery/lib/collection/node.js +++ /dev/null @@ -1,96 +0,0 @@ -'use strict'; - -/** - * Module dependencies - */ - -var Collection = require('./collection'); -var utils = require('../utils'); - -function NodeCollection (col) { - this.collection = col; -} - -/** - * inherit from collection base class - */ - -utils.inherits(NodeCollection, Collection); - -/** - * find(match, options, function(err, docs)) - */ - -NodeCollection.prototype.find = function (match, options, cb) { - this.collection.find(match, options, function (err, cursor) { - if (err) return cb(err); - - cursor.toArray(cb); - }); -} - -/** - * findOne(match, options, function(err, doc)) - */ - -NodeCollection.prototype.findOne = function (match, options, cb) { - this.collection.findOne(match, options, cb); -} - -/** - * count(match, options, function(err, count)) - */ - -NodeCollection.prototype.count = function (match, options, cb) { - this.collection.count(match, options, cb); -} - -/** - * distinct(prop, match, options, function(err, count)) - */ - -NodeCollection.prototype.distinct = function (prop, match, options, cb) { - this.collection.distinct(prop, match, options, cb); -} - -/** - * update(match, update, options, function(err[, result])) - */ - -NodeCollection.prototype.update = function (match, update, options, cb) { - this.collection.update(match, update, options, cb); -} - -/** - * remove(match, options, function(err[, result]) - */ - -NodeCollection.prototype.remove = function (match, options, cb) { - this.collection.remove(match, options, cb); -} - -/** - * findAndModify(match, update, options, function(err, doc)) - */ - -NodeCollection.prototype.findAndModify = function (match, update, options, cb) { - var sort = Array.isArray(options.sort) ? options.sort : []; - this.collection.findAndModify(match, sort, update, options, cb); -} - -/** - * aggregation(operators..., function(err, doc)) - * TODO - */ - -/** - * Streams - * TODO - */ - -/** - * Expose - */ - -module.exports = exports = NodeCollection; - diff --git a/node_modules/mongoose/node_modules/mquery/lib/env.js b/node_modules/mongoose/node_modules/mquery/lib/env.js deleted file mode 100644 index 3313b4622..000000000 --- a/node_modules/mongoose/node_modules/mquery/lib/env.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -exports.isNode = 'undefined' != typeof process - && 'object' == typeof module - && 'object' == typeof global - && 'function' == typeof Buffer - && process.argv - -exports.isMongo = !exports.isNode - && 'function' == typeof printjson - && 'function' == typeof ObjectId - && 'function' == typeof rs - && 'function' == typeof sh; - -exports.isBrowser = !exports.isNode - && !exports.isMongo - && 'undefined' != typeof window; - -exports.type = exports.isNode ? 'node' - : exports.isMongo ? 'mongo' - : exports.isBrowser ? 'browser' - : 'unknown' diff --git a/node_modules/mongoose/node_modules/mquery/lib/mquery.js b/node_modules/mongoose/node_modules/mquery/lib/mquery.js deleted file mode 100644 index 5451e7b95..000000000 --- a/node_modules/mongoose/node_modules/mquery/lib/mquery.js +++ /dev/null @@ -1,2396 +0,0 @@ -'use strict'; - -/** - * Dependencies - */ - -var slice = require('sliced') -var assert = require('assert') -var util = require('util') -var utils = require('./utils') -var debug = require('debug')('mquery'); - -/** - * Query constructor used for building queries. - * - * ####Example: - * - * var query = new Query({ name: 'mquery' }); - * query.setOptions({ collection: moduleCollection }) - * query.where('age').gte(21).exec(callback); - * - * @param {Object} [criteria] - * @param {Object} [options] - * @api public - */ - -function Query (criteria, options) { - if (!(this instanceof Query)) - return new Query(criteria, options); - - var proto = this.constructor.prototype; - - this.op = proto.op || undefined; - - this.options = {}; - this.setOptions(proto.options); - - this._conditions = proto._conditions - ? utils.clone(proto._conditions) - : {}; - - this._fields = proto._fields - ? utils.clone(proto._fields) - : undefined; - - this._update = proto._update - ? utils.clone(proto._update) - : undefined; - - this._path = proto._path || undefined; - this._distinct = proto._distinct || undefined; - this._collection = proto._collection || undefined; - - if (options) { - this.setOptions(options); - } - - if (criteria) { - if (criteria.find && criteria.remove && criteria.update) { - // quack quack! - this.collection(criteria); - } else { - this.find(criteria); - } - } -} - -/** - * This is a parameter that the user can set which determines if mquery - * uses $within or $geoWithin for queries. It defaults to true which - * means $geoWithin will be used. If using MongoDB < 2.4 you should - * set this to false. - * - * @api public - * @property use$geoWithin - */ - -var $withinCmd = '$geoWithin'; -Object.defineProperty(Query, 'use$geoWithin', { - get: function ( ) { return $withinCmd == '$geoWithin' } - , set: function (v) { - if (true === v) { - // mongodb >= 2.4 - $withinCmd = '$geoWithin'; - } else { - $withinCmd = '$within'; - } - } -}); - -/** - * Converts this query to a constructor function with all arguments and options retained. - * - * ####Example - * - * // Create a query that will read documents with a "video" category from - * // `aCollection` on the primary node in the replica-set unless it is down, - * // in which case we'll read from a secondary node. - * var query = mquery({ category: 'video' }) - * query.setOptions({ collection: aCollection, read: 'primaryPreferred' }); - * - * // create a constructor based off these settings - * var Video = query.toConstructor(); - * - * // Video is now a subclass of mquery() and works the same way but with the - * // default query parameters and options set. - * - * // run a query with the previous settings but filter for movies with names - * // that start with "Life". - * Video().where({ name: /^Life/ }).exec(cb); - * - * @return {Query} new Query - * @api public - */ - -Query.prototype.toConstructor = function toConstructor () { - function CustomQuery (criteria, options) { - if (!(this instanceof CustomQuery)) - return new CustomQuery(criteria, options); - Query.call(this, criteria, options); - } - - utils.inherits(CustomQuery, Query); - - // set inherited defaults - var p = CustomQuery.prototype; - - p.options = {}; - p.setOptions(this.options); - - p.op = this.op; - p._conditions = utils.clone(this._conditions); - p._fields = utils.clone(this._fields); - p._update = utils.clone(this._update); - p._path = this._path; - p._distict = this._distinct; - p._collection = this._collection; - - return CustomQuery; -} - -/** - * Sets query options. - * - * ####Options: - * - * - [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors) * - * - [sort](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort(\)%7D%7D) * - * - [limit](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D) * - * - [skip](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D) * - * - [maxScan](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan) * - * - [batchSize](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D) * - * - [comment](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment) * - * - [snapshot](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D) * - * - [hint](http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint) * - * - [slaveOk](http://docs.mongodb.org/manual/applications/replication/#read-preference) * - * - [safe](http://www.mongodb.org/display/DOCS/getLastError+Command) - * - collection the collection to query against - * - * _* denotes a query helper method is also available_ - * - * @param {Object} options - * @api public - */ - -Query.prototype.setOptions = function (options) { - if (!(options && utils.isObject(options))) - return this; - - // set arbitrary options - var methods = utils.keys(options) - , method - - for (var i = 0; i < methods.length; ++i) { - method = methods[i]; - - // use methods if exist (safer option manipulation) - if ('function' == typeof this[method]) { - var args = utils.isArray(options[method]) - ? options[method] - : [options[method]]; - this[method].apply(this, args) - } else { - this.options[method] = options[method]; - } - } - - return this; -} - -/** - * Sets this Querys collection. - * - * @param {Collection} coll - * @return {Query} this - */ - -Query.prototype.collection = function collection (coll) { - this._collection = new Query.Collection(coll); - - return this; -} - -/** - * Specifies a `$where` condition - * - * Use `$where` when you need to select documents using a JavaScript expression. - * - * ####Example - * - * query.$where('this.comments.length > 10 || this.name.length > 5') - * - * query.$where(function () { - * return this.comments.length > 10 || this.name.length > 5; - * }) - * - * @param {String|Function} js javascript string or function - * @return {Query} this - * @memberOf Query - * @method $where - * @api public - */ - -Query.prototype.$where = function (js) { - this._conditions.$where = js; - return this; -} - -/** - * Specifies a `path` for use with chaining. - * - * ####Example - * - * // instead of writing: - * User.find({age: {$gte: 21, $lte: 65}}, callback); - * - * // we can instead write: - * User.where('age').gte(21).lte(65); - * - * // passing query conditions is permitted - * User.find().where({ name: 'vonderful' }) - * - * // chaining - * User - * .where('age').gte(21).lte(65) - * .where('name', /^vonderful/i) - * .where('friends').slice(10) - * .exec(callback) - * - * @param {String} [path] - * @param {Object} [val] - * @return {Query} this - * @api public - */ - -Query.prototype.where = function () { - if (!arguments.length) return this; - if (!this.op) this.op = 'find'; - - var type = typeof arguments[0]; - - if ('string' == type) { - this._path = arguments[0]; - - if (2 === arguments.length) { - this._conditions[this._path] = arguments[1]; - } - - return this; - } - - if ('object' == type && !Array.isArray(arguments[0])) { - return this.merge(arguments[0]); - } - - throw new TypeError('path must be a string or object'); -} - -/** - * Specifies the complementary comparison value for paths specified with `where()` - * - * ####Example - * - * User.where('age').equals(49); - * - * // is the same as - * - * User.where('age', 49); - * - * @param {Object} val - * @return {Query} this - * @api public - */ - -Query.prototype.equals = function equals (val) { - this._ensurePath('equals'); - var path = this._path; - this._conditions[path] = val; - return this; -} - -/** - * Specifies arguments for an `$or` condition. - * - * ####Example - * - * query.or([{ color: 'red' }, { status: 'emergency' }]) - * - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.or = function or (array) { - var or = this._conditions.$or || (this._conditions.$or = []); - if (!utils.isArray(array)) array = [array]; - or.push.apply(or, array); - return this; -} - -/** - * Specifies arguments for a `$nor` condition. - * - * ####Example - * - * query.nor([{ color: 'green' }, { status: 'ok' }]) - * - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.nor = function nor (array) { - var nor = this._conditions.$nor || (this._conditions.$nor = []); - if (!utils.isArray(array)) array = [array]; - nor.push.apply(nor, array); - return this; -} - -/** - * Specifies arguments for a `$and` condition. - * - * ####Example - * - * query.and([{ color: 'green' }, { status: 'ok' }]) - * - * @see $and http://docs.mongodb.org/manual/reference/operator/and/ - * @param {Array} array array of conditions - * @return {Query} this - * @api public - */ - -Query.prototype.and = function and (array) { - var and = this._conditions.$and || (this._conditions.$and = []); - if (!Array.isArray(array)) array = [array]; - and.push.apply(and, array); - return this; -} - -/** - * Specifies a $gt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * ####Example - * - * Thing.find().where('age').gt(21) - * - * // or - * Thing.find().gt('age', 21) - * - * @method gt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $gte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method gte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $lt query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lt - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $lte query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method lte - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $ne query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method ne - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $in query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method in - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $nin query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method nin - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies an $all query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method all - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $size query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method size - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $regex query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method regex - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/** - * Specifies a $maxDistance query condition. - * - * When called with one argument, the most recent path passed to `where()` is used. - * - * @method maxDistance - * @memberOf Query - * @param {String} [path] - * @param {Number} val - * @api public - */ - -/*! - * gt, gte, lt, lte, ne, in, nin, all, regex, size, maxDistance - * - * Thing.where('type').nin(array) - */ - -'gt gte lt lte ne in nin all regex size maxDistance'.split(' ').forEach(function ($conditional) { - Query.prototype[$conditional] = function () { - var path, val; - - if (1 === arguments.length) { - this._ensurePath($conditional); - val = arguments[0]; - path = this._path; - } else { - val = arguments[1]; - path = arguments[0]; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds['$' + $conditional] = val; - return this; - }; -}) - -/** - * Specifies a `$mod` condition - * - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @api public - */ - -Query.prototype.mod = function () { - var val, path; - - if (1 === arguments.length) { - this._ensurePath('mod') - val = arguments[0]; - path = this._path; - } else if (2 === arguments.length && !utils.isArray(arguments[1])) { - this._ensurePath('mod') - val = slice(arguments); - path = this._path; - } else if (3 === arguments.length) { - val = slice(arguments, 1); - path = arguments[0]; - } else { - val = arguments[1]; - path = arguments[0]; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$mod = val; - return this; -} - -/** - * Specifies an `$exists` condition - * - * ####Example - * - * // { name: { $exists: true }} - * Thing.where('name').exists() - * Thing.where('name').exists(true) - * Thing.find().exists('name') - * - * // { name: { $exists: false }} - * Thing.where('name').exists(false); - * Thing.find().exists('name', false); - * - * @param {String} [path] - * @param {Number} val - * @return {Query} this - * @api public - */ - -Query.prototype.exists = function () { - var path, val; - - if (0 === arguments.length) { - this._ensurePath('exists'); - path = this._path; - val = true; - } else if (1 === arguments.length) { - if ('boolean' === typeof arguments[0]) { - this._ensurePath('exists'); - path = this._path; - val = arguments[0]; - } else { - path = arguments[0]; - val = true; - } - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$exists = val; - return this; -} - -/** - * Specifies an `$elemMatch` condition - * - * ####Example - * - * query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}) - * - * query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}) - * - * query.elemMatch('comment', function (elem) { - * elem.where('author').equals('autobot'); - * elem.where('votes').gte(5); - * }) - * - * query.where('comment').elemMatch(function (elem) { - * elem.where({ author: 'autobot' }); - * elem.where('votes').gte(5); - * }) - * - * @param {String|Object|Function} path - * @param {Object|Function} criteria - * @return {Query} this - * @api public - */ - -Query.prototype.elemMatch = function () { - if (null == arguments[0]) - throw new TypeError("Invalid argument"); - - var fn, path, criteria; - - if ('function' === typeof arguments[0]) { - this._ensurePath('elemMatch'); - path = this._path; - fn = arguments[0]; - } else if (utils.isObject(arguments[0])) { - this._ensurePath('elemMatch'); - path = this._path; - criteria = arguments[0]; - } else if ('function' === typeof arguments[1]) { - path = arguments[0]; - fn = arguments[1]; - } else if (arguments[1] && utils.isObject(arguments[1])) { - path = arguments[0]; - criteria = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } - - if (fn) { - criteria = new Query; - fn(criteria); - criteria = criteria._conditions; - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds.$elemMatch = criteria; - return this; -} - -// Spatial queries - -/** - * Sugar for geo-spatial queries. - * - * ####Example - * - * query.within().box() - * query.within().circle() - * query.within().geometry() - * - * query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); - * query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); - * query.where('loc').within({ polygon: [[],[],[],[]] }); - * - * query.where('loc').within([], [], []) // polygon - * query.where('loc').within([], []) // box - * query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry - * - * ####NOTE: - * - * Must be used after `where()`. - * - * @memberOf Query - * @return {Query} this - * @api public - */ - -Query.prototype.within = function within () { - // opinionated, must be used after where - this._ensurePath('within'); - this._geoComparison = $withinCmd; - - if (0 === arguments.length) { - return this; - } - - if (2 === arguments.length) { - return this.box.apply(this, arguments); - } else if (2 < arguments.length) { - return this.polygon.apply(this, arguments); - } - - var area = arguments[0]; - - if (!area) - throw new TypeError('Invalid argument'); - - if (area.center) - return this.circle(area); - - if (area.box) - return this.box.apply(this, area.box); - - if (area.polygon) - return this.polygon.apply(this, area.polygon); - - if (area.type && area.coordinates) - return this.geometry(area); - - throw new TypeError('Invalid argument'); -} - -/** - * Specifies a $box condition - * - * ####Example - * - * var lowerLeft = [40.73083, -73.99756] - * var upperRight= [40.741404, -73.988135] - * - * query.where('loc').within().box(lowerLeft, upperRight) - * query.box('loc', lowerLeft, upperRight ) - * - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see Query#within #query_Query-within - * @param {String} path - * @param {Object} val - * @return {Query} this - * @api public - */ - -Query.prototype.box = function () { - var path, box; - - if (3 === arguments.length) { - // box('loc', [], []) - path = arguments[0]; - box = [arguments[1], arguments[2]]; - } else if (2 === arguments.length) { - // box([], []) - this._ensurePath('box'); - path = this._path; - box = [arguments[0], arguments[1]]; - } else { - throw new TypeError("Invalid argument"); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison || $withinCmd] = { '$box': box }; - return this; -} - -/** - * Specifies a $polygon condition - * - * ####Example - * - * query.where('loc').within().polygon([10,20], [13, 25], [7,15]) - * query.polygon('loc', [10,20], [13, 25], [7,15]) - * - * @param {String|Array} [path] - * @param {Array|Object} [val] - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.polygon = function () { - var val, path; - - if ('string' == typeof arguments[0]) { - // polygon('loc', [],[],[]) - path = arguments[0]; - val = slice(arguments, 1); - } else { - // polygon([],[],[]) - this._ensurePath('polygon'); - path = this._path; - val = slice(arguments); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison || $withinCmd] = { '$polygon': val }; - return this; -} - -/** - * Specifies a $center or $centerSphere condition. - * - * ####Example - * - * var area = { center: [50, 50], radius: 10, unique: true } - * query.where('loc').within().circle(area) - * query.center('loc', area); - * - * // for spherical calculations - * var area = { center: [50, 50], radius: 10, unique: true, spherical: true } - * query.where('loc').within().circle(area) - * query.center('loc', area); - * - * @param {String} [path] - * @param {Object} area - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.circle = function () { - var path, val; - - if (1 === arguments.length) { - this._ensurePath('circle'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } - - if (!('radius' in val && val.center)) - throw new Error('center and radius are required'); - - var conds = this._conditions[path] || (this._conditions[path] = {}); - - var type = val.spherical - ? '$centerSphere' - : '$center'; - - var wKey = this._geoComparison || $withinCmd; - conds[wKey] = {}; - conds[wKey][type] = [val.center, val.radius]; - - if ('unique' in val) - conds[wKey].$uniqueDocs = !! val.unique; - - return this; -} - -/** - * Specifies a `$near` or `$nearSphere` condition - * - * These operators return documents sorted by distance. - * - * ####Example - * - * query.where('loc').near({ center: [10, 10] }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5 }); - * query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); - * query.near('loc', { center: [10, 10], maxDistance: 5 }); - * query.near({ center: { type: 'Point', coordinates: [..] }}) - * query.near().geometry({ type: 'Point', coordinates: [..] }) - * - * @param {String} [path] - * @param {Object} val - * @return {Query} this - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @api public - */ - -Query.prototype.near = function near () { - var path, val; - - this._geoComparison = '$near'; - - if (0 === arguments.length) { - return this; - } else if (1 === arguments.length) { - this._ensurePath('near'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - path = arguments[0]; - val = arguments[1]; - } else { - throw new TypeError("Invalid argument"); - } - - if (!val.center) { - throw new Error('center is required'); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - - var type = val.spherical - ? '$nearSphere' - : '$near'; - - // center could be a GeoJSON object or an Array - if (Array.isArray(val.center)) { - conds[type] = val.center; - } else { - // GeoJSON? - if (val.center.type != 'Point' || !Array.isArray(val.center.coordinates)) { - throw new Error(util.format("Invalid GeoJSON specified for %s", type)); - } - conds[type] = { $geometry : val.center }; - } - - var radius = 'maxDistance' in val - ? val.maxDistance - : null; - - if (null != radius) { - conds.$maxDistance = radius; - } - - return this; -} - -/** - * Declares an intersects query for `geometry()`. - * - * ####Example - * - * query.where('path').intersects().geometry({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * query.where('path').intersects({ - * type: 'LineString' - * , coordinates: [[180.0, 11.0], [180, 9.0]] - * }) - * - * @param {Object} [arg] - * @return {Query} this - * @api public - */ - -Query.prototype.intersects = function intersects () { - // opinionated, must be used after where - this._ensurePath('intersects'); - - this._geoComparison = '$geoIntersects'; - - if (0 === arguments.length) { - return this; - } - - var area = arguments[0]; - - if (null != area && area.type && area.coordinates) - return this.geometry(area); - - throw new TypeError('Invalid argument'); -} - -/** - * Specifies a `$geometry` condition - * - * ####Example - * - * var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] - * query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) - * - * // or - * var polyB = [[ 0, 0 ], [ 1, 1 ]] - * query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) - * - * // or - * var polyC = [ 0, 0 ] - * query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) - * - * // or - * query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) - * - * ####NOTE: - * - * `geometry()` **must** come after either `intersects()` or `within()`. - * - * The `object` argument must contain `type` and `coordinates` properties. - * - type {String} - * - coordinates {Array} - * - * The most recent path passed to `where()` is used. - * - * @param {Object} object Must contain a `type` property which is a String and a `coordinates` property which is an Array. See the examples. - * @return {Query} this - * @see http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry - * @see http://www.mongodb.org/display/DOCS/Geospatial+Indexing - * @see $geometry http://docs.mongodb.org/manual/reference/operator/geometry/ - * @api public - */ - -Query.prototype.geometry = function geometry () { - if (!('$within' == this._geoComparison || - '$geoWithin' == this._geoComparison || - '$near' == this._geoComparison || - '$geoIntersects' == this._geoComparison)) { - throw new Error('geometry() must come after `within()`, `intersects()`, or `near()'); - } - - var val, path; - - if (1 === arguments.length) { - this._ensurePath('geometry'); - path = this._path; - val = arguments[0]; - } else { - throw new TypeError("Invalid argument"); - } - - if (!(val.type && Array.isArray(val.coordinates))) { - throw new TypeError('Invalid argument'); - } - - var conds = this._conditions[path] || (this._conditions[path] = {}); - conds[this._geoComparison] = { $geometry: val }; - - return this; -} - -// end spatial - -/** - * Specifies which document fields to include or exclude - * - * ####String syntax - * - * When passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included. - * - * ####Example - * - * // include a and b, exclude c - * query.select('a b -c'); - * - * // or you may use object notation, useful when - * // you have keys already prefixed with a "-" - * query.select({a: 1, b: 1, c: 0}); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @see SchemaType - * @api public - */ - -Query.prototype.select = function select () { - var arg = arguments[0]; - if (!arg) return this; - - if (arguments.length !== 1) { - throw new Error("Invalid select: select only takes 1 argument"); - } - - this._validate('select'); - - var fields = this._fields || (this._fields = {}); - var type = typeof arg; - - if ('string' == type || 'object' == type && 'number' == typeof arg.length && !Array.isArray(arg)) { - if ('string' == type) - arg = arg.split(/\s+/); - - for (var i = 0, len = arg.length; i < len; ++i) { - var field = arg[i]; - if (!field) continue; - var include = '-' == field[0] ? 0 : 1; - if (include === 0) field = field.substring(1); - fields[field] = include; - } - - return this; - } - - if (utils.isObject(arg) && !Array.isArray(arg)) { - var keys = utils.keys(arg); - for (var i = 0; i < keys.length; ++i) { - fields[keys[i]] = arg[keys[i]]; - } - return this; - } - - throw new TypeError('Invalid select() argument. Must be string or object.'); -} - -/** - * Specifies a $slice condition for a `path` - * - * ####Example - * - * query.slice('comments', 5) - * query.slice('comments', -5) - * query.slice('comments', [10, 5]) - * query.where('comments').slice(5) - * query.where('comments').slice([-10, 5]) - * - * @param {String} [path] - * @param {Number} val number/range of elements to slice - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements - * @api public - */ - -Query.prototype.slice = function () { - if (0 === arguments.length) - return this; - - this._validate('slice'); - - var path, val; - - if (1 === arguments.length) { - this._ensurePath('slice'); - path = this._path; - val = arguments[0]; - } else if (2 === arguments.length) { - if ('number' === typeof arguments[0]) { - this._ensurePath('slice'); - path = this._path; - val = slice(arguments); - } else { - path = arguments[0]; - val = arguments[1]; - } - } else if (3 === arguments.length) { - path = arguments[0]; - val = slice(arguments, 1); - } - - var myFields = this._fields || (this._fields = {}); - myFields[path] = { '$slice': val }; - return this; -} - -/** - * Sets the sort order - * - * If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1. - * - * If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending. - * - * ####Example - * - * // these are equivalent - * query.sort({ field: 'asc', test: -1 }); - * query.sort('field -test'); - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object|String} arg - * @return {Query} this - * @api public - */ - -Query.prototype.sort = function (arg) { - if (!arg) return this; - - this._validate('sort'); - - var type = typeof arg; - - if (1 === arguments.length && 'string' == type) { - arg = arg.split(/\s+/); - - for (var i = 0, len = arg.length; i < len; ++i) { - var field = arg[i]; - if (!field) continue; - var ascend = '-' == field[0] ? -1 : 1; - if (ascend === -1) field = field.substring(1); - push(this.options, field, ascend); - } - - return this; - } - - if (utils.isObject(arg)) { - var keys = utils.keys(arg); - for (var i = 0; i < keys.length; ++i) { - var field = keys[i]; - push(this.options, field, arg[field]); - } - - return this; - } - - throw new TypeError('Invalid sort() argument. Must be a string or object.'); -} - -/*! - * @ignore - */ - -function push (opts, field, value) { - var val = String(value || 1).toLowerCase(); - if (!/^(?:ascending|asc|descending|desc|1|-1)$/.test(val)) { - if (utils.isArray(value)) value = '['+value+']'; - throw new TypeError('Invalid sort value: {' + field + ': ' + value + ' }'); - } - // store `sort` in a sane format - var s = opts.sort || (opts.sort = {}); - var valueStr = value.toString() - .replace("asc", "1") - .replace("ascending", "1") - .replace("desc", "-1") - .replace("descending", "-1"); - s[field] = parseInt(valueStr); -} - -/** - * Specifies the limit option. - * - * ####Example - * - * query.limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method limit - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D - * @api public - */ -/** - * Specifies the skip option. - * - * ####Example - * - * query.skip(100).limit(20) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method skip - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D - * @api public - */ -/** - * Specifies the maxScan option. - * - * ####Example - * - * query.maxScan(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method maxScan - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan - * @api public - */ -/** - * Specifies the batchSize option. - * - * ####Example - * - * query.batchSize(100) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method batchSize - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D - * @api public - */ -/** - * Specifies the `comment` option. - * - * ####Example - * - * query.comment('login query') - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @method comment - * @memberOf Query - * @param {Number} val - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment - * @api public - */ - -/*! - * limit, skip, maxScan, batchSize, comment - * - * Sets these associated options. - * - * query.comment('feed query'); - */ - -;['limit', 'skip', 'maxScan', 'batchSize', 'comment'].forEach(function (method) { - Query.prototype[method] = function (v) { - this._validate(method); - this.options[method] = v; - return this; - }; -}) - -/** - * Specifies this query as a `snapshot` query. - * - * ####Example - * - * mquery().snapshot() // true - * mquery().snapshot(true) - * mquery().snapshot(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D - * @return {Query} this - * @api public - */ - -Query.prototype.snapshot = function () { - this._validate('snapshot'); - - this.options.snapshot = arguments.length - ? !! arguments[0] - : true - - return this; -} - -/** - * Sets query hints. - * - * ####Example - * - * query.hint({ indexA: 1, indexB: -1}) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Object} val a hint object - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint - * @api public - */ - -Query.prototype.hint = function () { - if (0 === arguments.length) return this; - - this._validate('hint'); - - var arg = arguments[0]; - if (utils.isObject(arg)) { - var hint = this.options.hint || (this.options.hint = {}); - - // must keep object keys in order so don't use Object.keys() - for (var k in arg) { - hint[k] = arg[k]; - } - - return this; - } - - throw new TypeError('Invalid hint. ' + arg); -} - -/** - * Sets the slaveOk option. _Deprecated_ in MongoDB 2.2 in favor of read preferences. - * - * ####Example: - * - * query.slaveOk() // true - * query.slaveOk(true) - * query.slaveOk(false) - * - * @deprecated use read() preferences instead if on mongodb >= 2.2 - * @param {Boolean} v defaults to true - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see read() - * @return {Query} this - * @api public - */ - -Query.prototype.slaveOk = function (v) { - this.options.slaveOk = arguments.length ? !!v : true; - return this; -} - -/** - * Sets the readPreference option for the query. - * - * ####Example: - * - * new Query().read('primary') - * new Query().read('p') // same as primary - * - * new Query().read('primaryPreferred') - * new Query().read('pp') // same as primaryPreferred - * - * new Query().read('secondary') - * new Query().read('s') // same as secondary - * - * new Query().read('secondaryPreferred') - * new Query().read('sp') // same as secondaryPreferred - * - * new Query().read('nearest') - * new Query().read('n') // same as nearest - * - * // with tags - * new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]) - * - * ####Preferences: - * - * primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. - * secondary Read from secondary if available, otherwise error. - * primaryPreferred Read from primary if available, otherwise a secondary. - * secondaryPreferred Read from a secondary if available, otherwise read from the primary. - * nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. - * - * Aliases - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * Read more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences). - * - * @param {String} pref one of the listed preference options or their aliases - * @param {Array} [tags] optional tags for this query - * @see mongodb http://docs.mongodb.org/manual/applications/replication/#read-preference - * @see driver http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences - * @return {Query} this - * @api public - */ - -Query.prototype.read = function (pref, tags) { - this.options.readPreference = utils.readPref(pref, tags); - return this; -} - -/** - * Sets tailable option. - * - * ####Example - * - * query.tailable() <== true - * query.tailable(true) - * query.tailable(false) - * - * ####Note - * - * Cannot be used with `distinct()` - * - * @param {Boolean} v defaults to true - * @see mongodb http://www.mongodb.org/display/DOCS/Tailable+Cursors - * @api public - */ - -Query.prototype.tailable = function () { - this._validate('tailable'); - - this.options.tailable = arguments.length - ? !! arguments[0] - : true; - - return this; -} - -/** - * Merges another Query or conditions object into this one. - * - * When a Query is passed, conditions, field selection and options are merged. - * - * @param {Query|Object} source - * @return {Query} this - */ - -Query.prototype.merge = function (source) { - if (!source) - return this; - - if (!Query.canMerge(source)) - throw new TypeError('Invalid argument. Expected instanceof mquery or plain object'); - - if (source instanceof Query) { - // if source has a feature, apply it to ourselves - - if (source._conditions) { - utils.merge(this._conditions, source._conditions); - } - - if (source._fields) { - this._fields || (this._fields = {}); - utils.merge(this._fields, source._fields); - } - - if (source.options) { - this.options || (this.options = {}); - utils.merge(this.options, source.options); - } - - if (source._update) { - this._update || (this._update = {}); - utils.mergeClone(this._update, source._update); - } - - if (source._distinct) { - this._distinct = source._distinct; - } - - return this; - } - - // plain object - utils.merge(this._conditions, source); - - return this; -} - -/** - * Finds documents. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.find() - * query.find(callback) - * query.find({ name: 'Burning Lights' }, callback) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.find = function (criteria, callback) { - this.op = 'find'; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var self = this - , conds = this._conditions - , options = this._optionsForExec() - - options.fields = this._fieldsForExec() - - debug('find', conds, options); - - this._collection.find(conds, options, utils.tick(callback)); - return this; -} - -/** - * Executes the query as a findOne() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.findOne().where('name', /^Burning/); - * - * query.findOne({ name: /^Burning/ }) - * - * query.findOne({ name: /^Burning/ }, callback); // executes - * - * query.findOne(function (err, doc) { - * if (err) return handleError(err); - * if (doc) { - * // doc may be null if no document matched - * - * } - * }); - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.findOne = function (criteria, callback) { - this.op = 'findOne'; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var self = this - , conds = this._conditions - , options = this._optionsForExec() - - options.fields = this._fieldsForExec(); - - debug('findOne', conds, options); - this._collection.findOne(conds, options, utils.tick(callback)); - - return this; -} - -/** - * Exectues the query as a count() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * query.count().where('color', 'black').exec(callback); - * - * query.count({ color: 'black' }).count(callback) - * - * query.count({ color: 'black' }, callback) - * - * query.where('color', 'black').count(function (err, count) { - * if (err) return handleError(err); - * console.log('there are %d kittens', count); - * }) - * - * @param {Object} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count - * @api public - */ - -Query.prototype.count = function (criteria, callback) { - this.op = 'count'; - this._validate(); - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) return this; - - var conds = this._conditions - , options = this._optionsForExec() - - debug('count', conds, options); - this._collection.count(conds, options, utils.tick(callback)); - return this; -} - -/** - * Declares or executes a distict() operation. - * - * Passing a `callback` executes the query. - * - * ####Example - * - * distinct(criteria, field, fn) - * distinct(criteria, field) - * distinct(field, fn) - * distinct(field) - * distinct(fn) - * distinct() - * - * @param {Object|Query} [criteria] - * @param {String} [field] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct - * @api public - */ - -Query.prototype.distinct = function (criteria, field, callback) { - this.op = 'distinct'; - this._validate(); - - if (!callback) { - switch (typeof field) { - case 'function': - callback = field; - if ('string' == typeof criteria) { - field = criteria; - criteria = undefined; - } - break; - case 'undefined': - case 'string': - break; - default: - throw new TypeError('Invalid `field` argument. Must be string or function') - break; - } - - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = field = undefined; - break; - case 'string': - field = criteria; - criteria = undefined; - break; - } - } - - if ('string' == typeof field) { - this._distinct = field; - } - - if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (!callback) { - return this; - } - - if (!this._distinct) { - throw new Error('No value for `distinct` has been declared'); - } - - var conds = this._conditions - , options = this._optionsForExec() - - debug('distinct', conds, options); - this._collection.distinct(this._distinct, conds, options, utils.tick(callback)); - - return this; -} - -/** - * Declare and/or execute this query as an update() operation. - * - * _All paths passed that are not $atomic operations will become $set ops._ - * - * ####Example - * - * mquery({ _id: id }).update({ title: 'words' }, ...) - * - * becomes - * - * collection.update({ _id: id }, { $set: { title: 'words' }}, ...) - * - * ####Note - * - * Passing an empty object `{}` as the doc will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection. - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the `exec()` method. - * - * var q = mquery(collection).where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).update(); // not executed - * - * var q = mquery(collection).where({ _id: id }); - * q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe - * - * // keys that are not $atomic ops become $set. - * // this executes the same command as the previous example. - * q.update({ name: 'bob' }).where({ _id: id }).exec(); - * - * var q = mquery(collection).update(); // not executed - * - * // overwriting with empty docs - * var q.where({ _id: id }).setOptions({ overwrite: true }) - * q.update({ }, callback); // executes - * - * // multi update with overwrite to empty doc - * var q = mquery(collection).where({ _id: id }); - * q.setOptions({ multi: true, overwrite: true }) - * q.update({ }); - * q.update(callback); // executed - * - * // multi updates - * mquery() - * .collection(coll) - * .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback) - * // more multi updates - * mquery({ }) - * .collection(coll) - * .setOptions({ multi: true }) - * .update({ $set: { arr: [] }}, callback) - * - * // single update by default - * mquery({ email: 'address@example.com' }) - * .collection(coll) - * .update({ $inc: { counter: 1 }}, callback) - * - * // summary - * update(criteria, doc, opts, cb) // executes - * update(criteria, doc, opts) - * update(criteria, doc, cb) // executes - * update(criteria, doc) - * update(doc, cb) // executes - * update(doc) - * update(cb) // executes - * update(true) // executes (unsafe write) - * update() - * - * @param {Object} [criteria] - * @param {Object} [doc] the update command - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.update = function update (criteria, doc, options, callback) { - this.op = 'update'; - var force; - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = undefined; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - break; - case 1: - switch (typeof criteria) { - case 'function': - callback = criteria; - criteria = options = doc = undefined; - break; - case 'boolean': - // execution with no callback (unsafe write) - force = criteria; - criteria = undefined; - break; - default: - doc = criteria; - criteria = options = undefined; - break; - } - } - - if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - if (doc) { - this._mergeUpdate(doc); - } - - if (utils.isObject(options)) { - // { overwrite: true } - this.setOptions(options); - } - - // we are done if we don't have callback and they are - // not forcing an unsafe write. - if (!(force || callback)) - return this; - - if (!this._update || - !this.options.overwrite && 0 === utils.keys(this._update).length) { - callback && utils.soon(callback.bind(null, null, 0)); - return this; - } - - options = this._optionsForExec(); - if (!callback) options.safe = false; - - var criteria = this._conditions; - doc = this._updateForExec(); - - debug('update', criteria, doc, options); - this._collection.update(criteria, doc, options, utils.tick(callback)); - - return this; -} - -/** - * Declare and/or execute this query as a remove() operation. - * - * ####Example - * - * mquery(collection).remove({ artist: 'Anne Murray' }, callback) - * - * ####Note - * - * The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the `exec()` method. - * - * // not executed - * var query = mquery(collection).remove({ name: 'Anne Murray' }) - * - * // executed - * mquery(collection).remove({ name: 'Anne Murray' }, callback) - * mquery(collection).remove({ name: 'Anne Murray' }).remove(callback) - * - * // executed without a callback (unsafe write) - * query.exec() - * - * // summary - * query.remove(conds, fn); // executes - * query.remove(conds) - * query.remove(fn) // executes - * query.remove() - * - * @param {Object|Query} [criteria] mongodb selector - * @param {Function} [callback] - * @return {Query} this - * @api public - */ - -Query.prototype.remove = function (criteria, callback) { - this.op = 'remove'; - var force; - - if ('function' === typeof criteria) { - callback = criteria; - criteria = undefined; - } else if (Query.canMerge(criteria)) { - this.merge(criteria); - } else if (true === criteria) { - force = criteria; - criteria = undefined; - } - - if (!(force || callback)) - return this; - - var options = this._optionsForExec() - if (!callback) options.safe = false; - - var conds = this._conditions; - - debug('remove', conds, options); - this._collection.remove(conds, options, utils.tick(callback)); - - return this; -} - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) update command. - * - * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes immediately if `callback` is passed. - * - * ####Available options - * - * - `new`: bool - true to return the modified document rather than the original. defaults to true - * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * query.findOneAndUpdate(conditions, update, options, callback) // executes - * query.findOneAndUpdate(conditions, update, options) // returns Query - * query.findOneAndUpdate(conditions, update, callback) // executes - * query.findOneAndUpdate(conditions, update) // returns Query - * query.findOneAndUpdate(update, callback) // returns Query - * query.findOneAndUpdate(update) // returns Query - * query.findOneAndUpdate(callback) // executes - * query.findOneAndUpdate() // returns Query - * - * @param {Object|Query} [query] - * @param {Object} [doc] - * @param {Object} [options] - * @param {Function} [callback] - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @return {Query} this - * @api public - */ - -Query.prototype.findOneAndUpdate = function (criteria, doc, options, callback) { - this.op = 'findOneAndUpdate'; - this._validate(); - - switch (arguments.length) { - case 3: - if ('function' == typeof options) { - callback = options; - options = {}; - } - break; - case 2: - if ('function' == typeof doc) { - callback = doc; - doc = criteria; - criteria = undefined; - } - options = undefined; - break; - case 1: - if ('function' == typeof criteria) { - callback = criteria; - criteria = options = doc = undefined; - } else { - doc = criteria; - criteria = options = undefined; - } - } - - if (Query.canMerge(criteria)) { - this.merge(criteria); - } - - // apply doc - if (doc) { - this._mergeUpdate(doc); - } - - options && this.setOptions(options); - - if (!callback) return this; - return this._findAndModify('update', callback); -} - -/** - * Issues a mongodb [findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) remove command. - * - * Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if `callback` is passed. - * - * ####Available options - * - * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update - * - * ####Examples - * - * A.where().findOneAndRemove(conditions, options, callback) // executes - * A.where().findOneAndRemove(conditions, options) // return Query - * A.where().findOneAndRemove(conditions, callback) // executes - * A.where().findOneAndRemove(conditions) // returns Query - * A.where().findOneAndRemove(callback) // executes - * A.where().findOneAndRemove() // returns Query - * - * @param {Object} [conditions] - * @param {Object} [options] - * @param {Function} [callback] - * @return {Query} this - * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command - * @api public - */ - -Query.prototype.findOneAndRemove = function (conditions, options, callback) { - this.op = 'findOneAndRemove'; - this._validate(); - - if ('function' == typeof options) { - callback = options; - options = undefined; - } else if ('function' == typeof conditions) { - callback = conditions; - conditions = undefined; - } - - // apply conditions - if (Query.canMerge(conditions)) { - this.merge(conditions); - } - - // apply options - options && this.setOptions(options); - - if (!callback) return this; - - return this._findAndModify('remove', callback); -} - -/** - * _findAndModify - * - * @param {String} type - either "remove" or "update" - * @param {Function} callback - * @api private - */ - -Query.prototype._findAndModify = function (type, callback) { - assert.equal('function', typeof callback); - - var opts = this._optionsForExec() - , self = this - , fields - , sort - , doc - - if ('remove' == type) { - opts.remove = true; - } else { - if (!('new' in opts)) opts.new = true; - if (!('upsert' in opts)) opts.upsert = false; - - doc = this._updateForExec() - if (!doc) { - if (opts.upsert) { - // still need to do the upsert to empty doc - doc = { $set: {} }; - } else { - return this.findOne(callback); - } - } - } - - var fields = this._fieldsForExec(); - if (fields) { - opts.fields = fields; - } - - var conds = this._conditions; - - debug('findAndModify', conds, doc, opts); - - this._collection - .findAndModify(conds, doc, opts, utils.tick(callback)); - - return this; -} - -/** - * Executes the query - * - * ####Examples - * - * query.exec(); - * query.exec(callback); - * query.exec('update'); - * query.exec('find', callback); - * - * @param {String|Function} [operation] - * @param {Function} [callback] - * @return {Promise} - * @api public - */ - -Query.prototype.exec = function exec (op, callback) { - switch (typeof op) { - case 'function': - callback = op; - op = null; - break; - case 'string': - this.op = op; - break; - } - - assert.ok(this.op, "Missing query type: (find, update, etc)"); - - if ('update' == this.op || 'remove' == this.op) { - callback || (callback = true); - } - - this[this.op](callback); -} - -/** - * Determines if field selection has been made. - * - * @return {Boolean} - * @api public - */ - -Query.prototype.selected = function selected () { - return !! (this._fields && Object.keys(this._fields).length > 0); -} - -/** - * Determines if inclusive field selection has been made. - * - * query.selectedInclusively() // false - * query.select('name') - * query.selectedInclusively() // true - * query.selectedExlusively() // false - * - * @returns {Boolean} - */ - -Query.prototype.selectedInclusively = function selectedInclusively () { - if (!this._fields) return false; - - var keys = Object.keys(this._fields); - if (0 === keys.length) return false; - - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (0 === this._fields[key]) return false; - } - - return true; -} - -/** - * Determines if exclusive field selection has been made. - * - * query.selectedExlusively() // false - * query.select('-name') - * query.selectedExlusively() // true - * query.selectedInclusively() // false - * - * @returns {Boolean} - */ - -Query.prototype.selectedExclusively = function selectedExclusively () { - if (!this._fields) return false; - - var keys = Object.keys(this._fields); - if (0 === keys.length) return false; - - for (var i = 0; i < keys.length; ++i) { - var key = keys[i]; - if (0 === this._fields[key]) return true; - } - - return false; -} - -/** - * Merges `doc` with the current update object. - * - * @param {Object} doc - */ - -Query.prototype._mergeUpdate = function (doc) { - if (!this._update) this._update = {}; - if (doc instanceof Query) { - if (doc._update) { - utils.mergeClone(this._update, doc._update); - } - } else { - utils.mergeClone(this._update, doc); - } -} - -/** - * Returns default options. - * - * @return {Object} - * @api private - */ - -Query.prototype._optionsForExec = function () { - var options = utils.clone(this.options, { retainKeyOrder: true }); - return options; -} - -/** - * Returns fields selection for this query. - * - * @return {Object} - * @api private - */ - -Query.prototype._fieldsForExec = function () { - return utils.clone(this._fields); -} - -/** - * Return an update document with corrected $set operations. - * - * @api private - */ - -Query.prototype._updateForExec = function () { - var update = utils.clone(this._update, { retainKeyOrder: true }) - , ops = utils.keys(update) - , i = ops.length - , ret = {} - , hasKeys - , val - - while (i--) { - var op = ops[i]; - - if (this.options.overwrite) { - ret[op] = update[op]; - continue; - } - - if ('$' !== op[0]) { - // fix up $set sugar - if (!ret.$set) { - if (update.$set) { - ret.$set = update.$set; - } else { - ret.$set = {}; - } - } - ret.$set[op] = update[op]; - ops.splice(i, 1); - if (!~ops.indexOf('$set')) ops.push('$set'); - } else if ('$set' === op) { - if (!ret.$set) { - ret[op] = update[op]; - } - } else { - ret[op] = update[op]; - } - } - - return ret; -} - -/** - * Make sure _path is set. - * - * @parmam {String} method - */ - -Query.prototype._ensurePath = function (method) { - if (!this._path) { - var msg = method + '() must be used after where() ' - + 'when called with these arguments' - throw new Error(msg); - } -} - -/*! - * Permissions - */ - -Query.permissions = require('./permissions'); - -Query._isPermitted = function (a, b) { - var denied = Query.permissions[b]; - if (!denied) return true; - return true !== denied[a]; -} - -Query.prototype._validate = function (action) { - var fail; - var validator; - - if (undefined === action) { - - validator = Query.permissions[this.op]; - if ('function' != typeof validator) return true; - - fail = validator(this); - - } else if (!Query._isPermitted(action, this.op)) { - fail = action; - } - - if (fail) { - throw new Error(fail + ' cannot be used with ' + this.op); - } -} - -/** - * Determines if `conds` can be merged using `mquery().merge()` - * - * @param {Object} conds - * @return {Boolean} - */ - -Query.canMerge = function (conds) { - return conds instanceof Query || utils.isObject(conds); -} - -/*! - * Exports. - */ - -Query.utils = utils; -Query.env = require('./env') -Query.Collection = require('./collection'); -Query.BaseCollection = require('./collection/collection'); -module.exports = exports = Query; - -// TODO -// test utils diff --git a/node_modules/mongoose/node_modules/mquery/lib/permissions.js b/node_modules/mongoose/node_modules/mquery/lib/permissions.js deleted file mode 100644 index 07351d3a8..000000000 --- a/node_modules/mongoose/node_modules/mquery/lib/permissions.js +++ /dev/null @@ -1,91 +0,0 @@ -'use strict'; - -var denied = exports; - -denied.distinct = function (self) { - if (self._fields && Object.keys(self._fields).length > 0) { - return 'field selection and slice' - } - - var keys = Object.keys(denied.distinct); - var err; - - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -}; -denied.distinct.select = -denied.distinct.slice = -denied.distinct.sort = -denied.distinct.limit = -denied.distinct.skip = -denied.distinct.batchSize = -denied.distinct.comment = -denied.distinct.maxScan = -denied.distinct.snapshot = -denied.distinct.hint = -denied.distinct.tailable = true; - - -// aggregation integration - - -denied.findOneAndUpdate = -denied.findOneAndRemove = function (self) { - var keys = Object.keys(denied.findOneAndUpdate); - var err; - - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -} -denied.findOneAndUpdate.limit = -denied.findOneAndUpdate.skip = -denied.findOneAndUpdate.batchSize = -denied.findOneAndUpdate.maxScan = -denied.findOneAndUpdate.snapshot = -denied.findOneAndUpdate.hint = -denied.findOneAndUpdate.tailable = -denied.findOneAndUpdate.comment = true; - - -denied.count = function (self) { - if (self._fields && Object.keys(self._fields).length > 0) { - return 'field selection and slice' - } - - var keys = Object.keys(denied.count); - var err; - - keys.every(function (option) { - if (self.options[option]) { - err = option; - return false; - } - return true; - }); - - return err; -} - -denied.count.select = -denied.count.slice = -denied.count.sort = -denied.count.batchSize = -denied.count.comment = -denied.count.maxScan = -denied.count.snapshot = -denied.count.hint = -denied.count.tailable = true; diff --git a/node_modules/mongoose/node_modules/mquery/lib/utils.js b/node_modules/mongoose/node_modules/mquery/lib/utils.js deleted file mode 100644 index fe0e1621b..000000000 --- a/node_modules/mongoose/node_modules/mquery/lib/utils.js +++ /dev/null @@ -1,319 +0,0 @@ -'use strict'; - -/*! - * Module dependencies. - */ - -var mongodb = require('mongodb') - , ReadPref = mongodb.ReadPreference - , ObjectId = mongodb.ObjectID - , RegExpClone = require('regexp-clone') - -/** - * Object clone with Mongoose natives support. - * - * Creates a minimal data Object. - * It does not clone empty Arrays, empty Objects, and undefined values. - * This makes the data payload sent to MongoDB as minimal as possible. - * - * @param {Object} obj the object to clone - * @param {Object} options - * @return {Object} the cloned object - * @api private - */ - -exports.clone = function clone (obj, options) { - if (obj === undefined || obj === null) - return obj; - - if (Array.isArray(obj)) - return exports.cloneArray(obj, options); - - if ('Object' === obj.constructor.name) - return exports.cloneObject(obj, options); - - if ('Date' === obj.constructor.name || 'Function' === obj.constructor.name) - return new obj.constructor(+obj); - - if ('RegExp' === obj.constructor.name) { - return RegExpClone(obj); - } - - if (obj instanceof ObjectId) - return new ObjectId(obj.id); - - if (obj.valueOf) - return obj.valueOf(); -}; -var clone = exports.clone; - -/*! - * ignore - */ - -var cloneObject = exports.cloneObject = function cloneObject (obj, options) { - var retainKeyOrder = options && options.retainKeyOrder - , minimize = options && options.minimize - , ret = {} - , hasKeys - , keys - , val - , k - , i - - if (retainKeyOrder) { - for (k in obj) { - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - hasKeys || (hasKeys = true); - ret[k] = val; - } - } - } else { - // faster - - keys = Object.keys(obj); - i = keys.length; - - while (i--) { - k = keys[i]; - val = clone(obj[k], options); - - if (!minimize || ('undefined' !== typeof val)) { - if (!hasKeys) hasKeys = true; - ret[k] = val; - } - } - } - - return minimize - ? hasKeys && ret - : ret; -}; - -var cloneArray = exports.cloneArray = function cloneArray (arr, options) { - var ret = []; - for (var i = 0, l = arr.length; i < l; i++) - ret.push(clone(arr[i], options)); - return ret; -}; - -/** - * process.nextTick helper. - * - * Wraps the given `callback` in a try/catch. If an error is - * caught it will be thrown on nextTick. - * - * node-mongodb-native had a habit of state corruption when - * an error was immediately thrown from within a collection - * method (find, update, etc) callback. - * - * @param {Function} [callback] - * @api private - */ - -var tick = exports.tick = function tick (callback) { - if ('function' !== typeof callback) return; - return function () { - // callbacks should always be fired on the next - // turn of the event loop. A side benefit is - // errors thrown from executing the callback - // will not cause drivers state to be corrupted - // which has historically been a problem. - var args = arguments; - soon(function(){ - callback.apply(this, args); - }); - } -} - -/** - * Merges `from` into `to` without overwriting existing properties. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -var merge = exports.merge = function merge (to, from) { - var keys = Object.keys(from) - , i = keys.length - , key - - while (i--) { - key = keys[i]; - if ('undefined' === typeof to[key]) { - to[key] = from[key]; - } else { - if (exports.isObject(from[key])) { - merge(to[key], from[key]); - } else { - to[key] = from[key]; - } - } - } -} - -/** - * Same as merge but clones the assigned values. - * - * @param {Object} to - * @param {Object} from - * @api private - */ - -var mergeClone = exports.mergeClone = function mergeClone (to, from) { - var keys = Object.keys(from) - , i = keys.length - , key - - while (i--) { - key = keys[i]; - if ('undefined' === typeof to[key]) { - // make sure to retain key order here because of a bug handling the $each - // operator in mongodb 2.4.4 - to[key] = clone(from[key], { retainKeyOrder : 1}); - } else { - if (exports.isObject(from[key])) { - mergeClone(to[key], from[key]); - } else { - // make sure to retain key order here because of a bug handling the - // $each operator in mongodb 2.4.4 - to[key] = clone(from[key], { retainKeyOrder : 1}); - } - } - } -} - -/** - * Read pref helper (mongo 2.2 drivers support this) - * - * Allows using aliases instead of full preference names: - * - * p primary - * pp primaryPreferred - * s secondary - * sp secondaryPreferred - * n nearest - * - * @param {String|Array} pref - * @param {Array} [tags] - */ - -exports.readPref = function readPref (pref, tags) { - if (Array.isArray(pref)) { - tags = pref[1]; - pref = pref[0]; - } - - switch (pref) { - case 'p': - pref = 'primary'; - break; - case 'pp': - pref = 'primaryPreferred'; - break; - case 's': - pref = 'secondary'; - break; - case 'sp': - pref = 'secondaryPreferred'; - break; - case 'n': - pref = 'nearest'; - break; - } - - return new ReadPref(pref, tags); -} - -/** - * Object.prototype.toString.call helper - */ - -var toString = Object.prototype.toString; -exports.toString = function (arg) { - return toString.call(arg); -} - -/** - * Determines if `arg` is an object. - * - * @param {Object|Array|String|Function|RegExp|any} arg - * @return {Boolean} - */ - -exports.isObject = function (arg) { - return '[object Object]' == exports.toString(arg); -} - -/** - * Determines if `arg` is an array. - * - * @param {Object} - * @return {Boolean} - * @see nodejs utils - */ - -exports.isArray = function (arg) { - return Array.isArray(arg) || - 'object' == typeof arg && '[object Array]' == exports.toString(arg); -} - -/** - * Object.keys helper - */ - -exports.keys = Object.keys || function (obj) { - var keys = []; - for (var k in obj) if (obj.hasOwnProperty(k)) { - keys.push(k); - } - return keys; -} - -/** - * Basic Object.create polyfill. - * Only one argument is supported. - * - * Based on https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/create - */ - -exports.create = 'function' == typeof Object.create - ? Object.create - : create; - -function create (proto) { - if (arguments.length > 1) { - throw new Error("Adding properties is not supported") - } - - function F () {} - F.prototype = proto; - return new F; -} - -/** - * inheritance - */ - -exports.inherits = function (ctor, superCtor) { - ctor.prototype = exports.create(superCtor.prototype); - ctor.prototype.constructor = ctor; -} - -/** - * nextTick helper - * compat with node 0.10 which behaves differently than previous versions - */ - -var soon = exports.soon = 'function' == typeof setImmediate - ? setImmediate - : process.nextTick; - -/** - * need to export this for checking issues - */ - -exports.mongo = mongodb; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore b/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore deleted file mode 100644 index f1250e584..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md b/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md deleted file mode 100644 index 22206323d..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/History.md +++ /dev/null @@ -1,47 +0,0 @@ - -0.7.0 / 2012-05-04 -================== - - * Added .component to package.json - * Added debug.component.js build - -0.6.0 / 2012-03-16 -================== - - * Added support for "-" prefix in DEBUG [Vinay Pulim] - * Added `.enabled` flag to the node version [TooTallNate] - -0.5.0 / 2012-02-02 -================== - - * Added: humanize diffs. Closes #8 - * Added `debug.disable()` to the CS variant - * Removed padding. Closes #10 - * Fixed: persist client-side variant again. Closes #9 - -0.4.0 / 2012-02-01 -================== - - * Added browser variant support for older browsers [TooTallNate] - * Added `debug.enable('project:*')` to browser variant [TooTallNate] - * Added padding to diff (moved it to the right) - -0.3.0 / 2012-01-26 -================== - - * Added millisecond diff when isatty, otherwise UTC string - -0.2.0 / 2012-01-22 -================== - - * Added wildcard support - -0.1.0 / 2011-12-02 -================== - - * Added: remove colors unless stderr isatty [TooTallNate] - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile deleted file mode 100644 index 692f2c1e9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Makefile +++ /dev/null @@ -1,4 +0,0 @@ - -debug.component.js: head.js debug.js tail.js - cat $^ > $@ - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md b/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md deleted file mode 100644 index 419fcdf52..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/Readme.md +++ /dev/null @@ -1,130 +0,0 @@ - -# debug - - tiny node.js debugging utility. - -## Installation - -``` -$ npm install debug -``` - -## Example - - This module is modelled after node core's debugging technique, allowing you to enable one or more topic-specific debugging functions, for example core does the following within many modules: - -```js -var debug; -if (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) { - debug = function(x) { - var prefix = process.pid + ',' + - (process.env.NODE_WORKER_ID ? 'Worker' : 'Master'); - console.error(prefix, x); - }; -} else { - debug = function() { }; -} -``` - - This concept is extremely simple but it works well. With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. - -Example _app.js_: - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example _worker.js_: - -```js -var debug = require('debug')('worker'); - -setInterval(function(){ - debug('doing some work'); -}, 1000); -``` - - The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: - - ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) - - ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) - -## Millisecond diff - - When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - - When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - - ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - -## Conventions - - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". - -## Wildcards - - The "*" character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with "connect:". - -## Browser support - - Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - a('doing some work'); -}, 1200); -``` - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.component.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.component.js deleted file mode 100644 index e6e9dbf60..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.component.js +++ /dev/null @@ -1,120 +0,0 @@ -;(function(){ - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } -} - -/** - * The currently active debug mode names. - */ - -debug.names = []; -debug.skips = []; - -/** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - -debug.enable = function(name) { - localStorage.debug = name; - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } -}; - -/** - * Disable debug output. - * - * @api public - */ - -debug.disable = function(){ - debug.enable(''); -}; - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -}; - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; -}; - -// persist - -if (window.localStorage) debug.enable(localStorage.debug); - module.exports = debug; - -})(); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js deleted file mode 100644 index 905fbd459..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/debug.js +++ /dev/null @@ -1,116 +0,0 @@ - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - if (!debug.enabled(name)) return function(){}; - - return function(fmt){ - var curr = new Date; - var ms = curr - (debug[name] || curr); - debug[name] = curr; - - fmt = name - + ' ' - + fmt - + ' +' + debug.humanize(ms); - - // This hackery is required for IE8 - // where `console.log` doesn't have 'apply' - window.console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); - } -} - -/** - * The currently active debug mode names. - */ - -debug.names = []; -debug.skips = []; - -/** - * Enables a debug mode by name. This can include modes - * separated by a colon and wildcards. - * - * @param {String} name - * @api public - */ - -debug.enable = function(name) { - localStorage.debug = name; - - var split = (name || '').split(/[\s,]+/) - , len = split.length; - - for (var i = 0; i < len; i++) { - name = split[i].replace('*', '.*?'); - if (name[0] === '-') { - debug.skips.push(new RegExp('^' + name.substr(1) + '$')); - } - else { - debug.names.push(new RegExp('^' + name + '$')); - } - } -}; - -/** - * Disable debug output. - * - * @api public - */ - -debug.disable = function(){ - debug.enable(''); -}; - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -debug.humanize = function(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -}; - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -debug.enabled = function(name) { - for (var i = 0, len = debug.skips.length; i < len; i++) { - if (debug.skips[i].test(name)) { - return false; - } - } - for (var i = 0, len = debug.names.length; i < len; i++) { - if (debug.names[i].test(name)) { - return true; - } - } - return false; -}; - -// persist - -if (window.localStorage) debug.enable(localStorage.debug); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/app.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/app.js deleted file mode 100644 index 05374d98d..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/app.js +++ /dev/null @@ -1,19 +0,0 @@ - -var debug = require('../')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/browser.html b/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/browser.html deleted file mode 100644 index 7510eee7b..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/browser.html +++ /dev/null @@ -1,24 +0,0 @@ - - - debug() - - - - - - - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/wildcards.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/wildcards.js deleted file mode 100644 index 1fdac20a9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/wildcards.js +++ /dev/null @@ -1,10 +0,0 @@ - -var debug = { - foo: require('../')('test:foo'), - bar: require('../')('test:bar'), - baz: require('../')('test:baz') -}; - -debug.foo('foo') -debug.bar('bar') -debug.baz('baz') \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/worker.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/worker.js deleted file mode 100644 index 7f6d2886c..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/example/worker.js +++ /dev/null @@ -1,22 +0,0 @@ - -// DEBUG=* node example/worker -// DEBUG=worker:* node example/worker -// DEBUG=worker:a node example/worker -// DEBUG=worker:b node example/worker - -var a = require('../')('worker:a') - , b = require('../')('worker:b'); - -function work() { - a('doing lots of uninteresting work'); - setTimeout(work, Math.random() * 1000); -} - -work(); - -function workb() { - b('doing some work'); - setTimeout(workb, Math.random() * 2000); -} - -workb(); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/head.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/head.js deleted file mode 100644 index 55d38175e..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/head.js +++ /dev/null @@ -1 +0,0 @@ -;(function(){ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js deleted file mode 100644 index ee5445415..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/debug'); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js deleted file mode 100644 index 969d12225..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/lib/debug.js +++ /dev/null @@ -1,135 +0,0 @@ - -/** - * Module dependencies. - */ - -var tty = require('tty'); - -/** - * Expose `debug()` as the module. - */ - -module.exports = debug; - -/** - * Enabled debuggers. - */ - -var names = [] - , skips = []; - -(process.env.DEBUG || '') - .split(/[\s,]+/) - .forEach(function(name){ - name = name.replace('*', '.*?'); - if (name[0] === '-') { - skips.push(new RegExp('^' + name.substr(1) + '$')); - } else { - names.push(new RegExp('^' + name + '$')); - } - }); - -/** - * Colors. - */ - -var colors = [6, 2, 3, 4, 5, 1]; - -/** - * Previous debug() call. - */ - -var prev = {}; - -/** - * Previously assigned color. - */ - -var prevColor = 0; - -/** - * Is stdout a TTY? Colored output is disabled when `true`. - */ - -var isatty = tty.isatty(2); - -/** - * Select a color. - * - * @return {Number} - * @api private - */ - -function color() { - return colors[prevColor++ % colors.length]; -} - -/** - * Humanize the given `ms`. - * - * @param {Number} m - * @return {String} - * @api private - */ - -function humanize(ms) { - var sec = 1000 - , min = 60 * 1000 - , hour = 60 * min; - - if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; - if (ms >= min) return (ms / min).toFixed(1) + 'm'; - if (ms >= sec) return (ms / sec | 0) + 's'; - return ms + 'ms'; -} - -/** - * Create a debugger with the given `name`. - * - * @param {String} name - * @return {Type} - * @api public - */ - -function debug(name) { - function disabled(){} - disabled.enabled = false; - - var match = skips.some(function(re){ - return re.test(name); - }); - - if (match) return disabled; - - match = names.some(function(re){ - return re.test(name); - }); - - if (!match) return disabled; - var c = color(); - - function colored(fmt) { - var curr = new Date; - var ms = curr - (prev[name] || curr); - prev[name] = curr; - - fmt = ' \033[9' + c + 'm' + name + ' ' - + '\033[3' + c + 'm\033[90m' - + fmt + '\033[3' + c + 'm' - + ' +' + humanize(ms) + '\033[0m'; - - console.error.apply(this, arguments); - } - - function plain(fmt) { - fmt = new Date().toUTCString() - + ' ' + name + ' ' + fmt; - console.error.apply(this, arguments); - } - - colored.enabled = plain.enabled = true; - - return isatty - ? colored - : plain; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json deleted file mode 100644 index da7428cf8..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "debug", - "version": "0.7.0", - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "dependencies": {}, - "devDependencies": { - "mocha": "*" - }, - "main": "index", - "browserify": "debug.component.js", - "engines": { - "node": "*" - }, - "component": { - "scripts": { - "debug": "debug.component.js" - } - }, - "readme": "\n# debug\n\n tiny node.js debugging utility.\n\n## Installation\n\n```\n$ npm install debug\n```\n\n## Example\n\n This module is modelled after node core's debugging technique, allowing you to enable one or more topic-specific debugging functions, for example core does the following within many modules:\n\n```js\nvar debug;\nif (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) {\n debug = function(x) {\n var prefix = process.pid + ',' +\n (process.env.NODE_WORKER_ID ? 'Worker' : 'Master');\n console.error(prefix, x);\n };\n} else {\n debug = function() { };\n}\n```\n\n This concept is extremely simple but it works well. With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility.\n \nExample _app.js_:\n\n```js\nvar debug = require('debug')('http')\n , http = require('http')\n , name = 'My App';\n\n// fake app\n\ndebug('booting %s', name);\n\nhttp.createServer(function(req, res){\n debug(req.method + ' ' + req.url);\n res.end('hello\\n');\n}).listen(3000, function(){\n debug('listening');\n});\n\n// fake worker of some kind\n\nrequire('./worker');\n```\n\nExample _worker.js_:\n\n```js\nvar debug = require('debug')('worker');\n\nsetInterval(function(){\n debug('doing some work');\n}, 1000);\n```\n\n The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples:\n\n ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png)\n\n ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png)\n\n## Millisecond diff\n\n When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the \"+NNNms\" will show you how much time was spent between calls.\n\n ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png)\n\n When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below:\n \n ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png)\n\n## Conventions\n\n If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use \":\" to separate features. For example \"bodyParser\" from Connect would then be \"connect:bodyParser\". \n\n## Wildcards\n\n The \"*\" character may be used as a wildcard. Suppose for example your library has debuggers named \"connect:bodyParser\", \"connect:compress\", \"connect:session\", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.\n\n You can also exclude specific debuggers by prefixing them with a \"-\" character. For example, `DEBUG=* -connect:*` would include all debuggers except those starting with \"connect:\".\n\n## Browser support\n\n Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. \n\n```js\na = debug('worker:a');\nb = debug('worker:b');\n\nsetInterval(function(){\n a('doing some work');\n}, 1000);\n\nsetInterval(function(){\n a('doing some work');\n}, 1200);\n```\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "_id": "debug@0.7.0", - "dist": { - "shasum": "b16ab3bc97e49bc1f64dc14d80fe6654e26e0198" - }, - "_from": "debug@0.7.0", - "_resolved": "https://registry.npmjs.org/debug/-/debug-0.7.0.tgz" -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/debug/tail.js b/node_modules/mongoose/node_modules/mquery/node_modules/debug/tail.js deleted file mode 100644 index 5bf3fd354..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/debug/tail.js +++ /dev/null @@ -1,4 +0,0 @@ - - module.exports = debug; - -})(); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/.travis.yml b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/.travis.yml deleted file mode 100644 index 0140117b6..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.10 # development version of 0.8, may be unstable \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/CONTRIBUTING.md b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/CONTRIBUTING.md deleted file mode 100644 index 2a1c52e2a..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/CONTRIBUTING.md +++ /dev/null @@ -1,23 +0,0 @@ -## Contributing to the driver - -### Bugfixes - -- Before starting to write code, look for existing [tickets](https://github.com/mongodb/node-mongodb-native/issues) or [create one](https://github.com/mongodb/node-mongodb-native/issues/new) for your specific issue. That way you avoid working on something that might not be of interest or that has been addressed already in a different branch. -- Fork the [repo](https://github.com/mongodb/node-mongodb-native) _or_ for small documentation changes, navigate to the source on github and click the [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. -- Follow the general coding style of the rest of the project: - - 2 space tabs - - no trailing whitespace - - comma last - - inline documentation for new methods, class members, etc - - 0 space between conditionals/functions, and their parenthesis and curly braces - - `if(..) {` - - `for(..) {` - - `while(..) {` - - `function(err) {` -- Write tests and make sure they pass (execute `make test` from the cmd line to run the test suite). - -### Documentation - -To contribute to the [API documentation](http://mongodb.github.com/node-mongodb-native/) just make your changes to the inline documentation of the appropriate [source code](https://github.com/mongodb/node-mongodb-native/tree/master/docs) in the master branch and submit a [pull request](https://help.github.com/articles/using-pull-requests/). You might also use the github [Edit](https://github.com/blog/844-forking-with-the-edit-button) button. - -If you'd like to preview your documentation changes, first commit your changes to your local master branch, then execute `make generate_docs`. Make sure you have the python documentation framework sphinx installed `easy_install sphinx`. The docs are generated under `docs/build'. If all looks good, submit a [pull request](https://help.github.com/articles/using-pull-requests/) to the master branch with your changes. \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/LICENSE b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/Makefile deleted file mode 100644 index 59d2bfeb8..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -NPM = npm -NODEUNIT = node_modules/nodeunit/bin/nodeunit -DOX = node_modules/dox/bin/dox -name = all - -total: build_native - -test_functional: - node test/runner.js -t functional - -test_ssl: - node test/runner.js -t ssl - -test_replicaset: - node test/runner.js -t replicaset - -test_sharded: - node test/runner.js -t sharded - -test_auth: - node test/runner.js -t auth - -generate_docs: - $(NODE) dev/tools/build-docs.js - make --directory=./docs/sphinx-docs --file=Makefile html - -.PHONY: total diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/Readme.md b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/Readme.md deleted file mode 100644 index 0d4830f12..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/Readme.md +++ /dev/null @@ -1,421 +0,0 @@ -Up to date documentation -======================== - -[Documentation](http://mongodb.github.com/node-mongodb-native/) - -Install -======= - -To install the most recent release from npm, run: - - npm install mongodb - -That may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version) - -To install the latest from the repository, run:: - - npm install path/to/node-mongodb-native - -Community -========= -Check out the google group [node-mongodb-native](http://groups.google.com/group/node-mongodb-native) for questions/answers from users of the driver. - -Live Examples -============ - - -Introduction -============ - -This is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/. - -A simple example of inserting a document. - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db.collection('test_insert'); - collection.insert({a:2}, function(err, docs) { - - collection.count(function(err, count) { - console.log(format("count = %s", count)); - }); - - // Locate all the entries using find - collection.find().toArray(function(err, results) { - console.dir(results); - // Let's close the db - db.close(); - }); - }); - }) -``` - -Data types -========== - -To store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code). - -In particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example: - -```javascript - // Get the objectID type - var ObjectID = require('mongodb').ObjectID; - - var idString = '4e4e1638c85e808431000003'; - collection.findOne({_id: new ObjectID(idString)}, console.log) // ok - collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined -``` - -Here are the constructors the non-Javascript BSON primitive types: - -```javascript - // Fetch the library - var mongo = require('mongodb'); - // Create new instances of BSON types - new mongo.Long(numberString) - new mongo.ObjectID(hexString) - new mongo.Timestamp() // the actual unique number is generated on insert. - new mongo.DBRef(collectionName, id, dbName) - new mongo.Binary(buffer) // takes a string or Buffer - new mongo.Code(code, [context]) - new mongo.Symbol(string) - new mongo.MinKey() - new mongo.MaxKey() - new mongo.Double(number) // Force double storage -``` - -The C/C++ bson parser/serializer --------------------------------- - -If you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below - -```javascript - // using native_parser: - MongoClient.connect('mongodb://127.0.0.1:27017/test' - , {db: {native_parser: true}}, function(err, db) {}) -``` - -The C++ parser uses the js objects both for serialization and deserialization. - -GitHub information -================== - -The source code is available at http://github.com/mongodb/node-mongodb-native. -You can either clone the repository or download a tarball of the latest release. - -Once you have the source you can test the driver by running - - $ make test - -in the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass. - -Examples -======== - -For examples look in the examples/ directory. You can execute the examples using node. - - $ cd examples - $ node queries.js - -GridStore -========= - -The GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition. - -For more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md) - -Replicasets -=========== -For more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/) - -Primary Key Factories ---------------------- - -Defining your own primary key factory allows you to generate your own series of id's -(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long "string". - -Simple example below - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - // Custom factory (need to provide a 12 byte array); - CustomPKFactory = function() {} - CustomPKFactory.prototype = new Object(); - CustomPKFactory.createPk = function() { - return new ObjectID("aaaaaaaaaaaa"); - } - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.dropDatabase(function(err, done) { - - db.createCollection('test_custom_key', function(err, collection) { - - collection.insert({'a':1}, function(err, docs) { - - collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}).toArray(function(err, items) { - console.dir(items); - // Let's close the db - db.close(); - }); - }); - }); - }); - }); -``` - -Documentation -============= - -If this document doesn't answer your questions, see the source of -[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js) -or [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js), -or the documentation at MongoDB for query and update formats. - -Find ----- - -The find method is actually a factory method to create -Cursor objects. A Cursor lazily uses the connection the first time -you call `nextObject`, `each`, or `toArray`. - -The basic operation on a cursor is the `nextObject` method -that fetches the next matching document from the database. The convenience -methods `each` and `toArray` call `nextObject` until the cursor is exhausted. - -Signatures: - -```javascript - var cursor = collection.find(query, [fields], options); - cursor.sort(fields).limit(n).skip(m). - - cursor.nextObject(function(err, doc) {}); - cursor.each(function(err, doc) {}); - cursor.toArray(function(err, docs) {}); - - cursor.rewind() // reset the cursor to its initial state. -``` - -Useful chainable methods of cursor. These can optionally be options of `find` instead of method calls: - - * `.limit(n).skip(m)` to control paging. - * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes: - * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2. - * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above - * `.sort([['field1', 'desc'], 'field2'])` same as above - * `.sort('field1')` ascending by field1 - -Other options of `find`: - -* `fields` the fields to fetch (to avoid transferring the entire document) -* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors). -* `batchSize` The number of the subset of results to request the database -to return for every request. This should initially be greater than 1 otherwise -the database will automatically close the cursor. The batch size can be set to 1 -with `batchSize(n, function(err){})` after performing the initial query to the database. -* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint). -* `explain` turns this into an explain query. You can also call -`explain()` on any cursor to fetch the explanation. -* `snapshot` prevents documents that are updated while the query is active -from being returned multiple times. See more -[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database). -* `timeout` if false, asks MongoDb not to time out this cursor after an -inactivity period. - - -For information on how to create queries, see the -[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying). - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - var collection = db - .collection('test') - .find({}) - .limit(10) - .toArray(function(err, docs) { - console.dir(docs); - }); - }); -``` - -Insert ------- - -Signature: - -```javascript - collection.insert(docs, options, [callback]); -``` - -where `docs` can be a single document or an array of documents. - -Useful options: - -* `safe:true` Should always set if you have a callback. - -See also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting). - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) { - if (err) console.warn(err.message); - if (err && err.message.indexOf('E11000 ') !== -1) { - // this _id was already inserted in the database - } - }); - }); -``` - -Note that there's no reason to pass a callback to the insert or update commands -unless you use the `safe:true` option. If you don't specify `safe:true`, then -your callback will be called immediately. - -Update; update and insert (upsert) ----------------------------------- - -The update operation will update the first document that matches your query -(or all documents that match if you use `multi:true`). -If `safe:true`, `upsert` is not set, and no documents match, your callback will return 0 documents updated. - -See the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for -the modifier (`$inc`, `$set`, `$push`, etc.) formats. - -Signature: - -```javascript - collection.update(criteria, objNew, options, [callback]); -``` - -Useful options: - -* `safe:true` Should always set if you have a callback. -* `multi:true` If set, all matching documents are updated, not just the first. -* `upsert:true` Atomically inserts the document if no documents matched. - -Example for `update`: - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - - db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) { - if (err) console.warn(err.message); - else console.log('successfully updated'); - }); - }); -``` - -Find and modify ---------------- - -`findAndModify` is like `update`, but it also gives the updated document to -your callback. But there are a few key differences between findAndModify and -update: - - 1. The signatures differ. - 2. You can only findAndModify a single item, not multiple items. - -Signature: - -```javascript - collection.findAndModify(query, sort, update, options, callback) -``` - -The sort parameter is used to specify which object to operate on, if more than -one document matches. It takes the same format as the cursor sort (see -Connection.find above). - -See the -[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command) -for more details. - -Useful options: - -* `remove:true` set to a true to remove the object before returning -* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove. -* `upsert:true` Atomically inserts the document if no documents matched. - -Example for `findAndModify`: - -```javascript - var MongoClient = require('mongodb').MongoClient - , format = require('util').format; - - MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { - if(err) throw err; - db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) { - if (err) console.warn(err.message); - else console.dir(object); // undefined if no matching object exists. - }); - }); -``` - -Save ----- - -The `save` method is a shorthand for upsert if the document contains an -`_id`, or an insert if there is no `_id`. - -Sponsors -======== -Just as Felix Geisendörfer I'm also working on the driver for my own startup and this driver is a big project that also benefits other companies who are using MongoDB. - -If your company could benefit from a even better-engineered node.js mongodb driver I would appreciate any type of sponsorship you may be able to provide. All the sponsors will get a lifetime display in this readme, priority support and help on problems and votes on the roadmap decisions for the driver. If you are interested contact me on [christkv AT g m a i l.com](mailto:christkv@gmail.com) for details. - -And I'm very thankful for code contributions. If you are interested in working on features please contact me so we can discuss API design and testing. - -Release Notes -============= - -See HISTORY - -Credits -======= - -1. [10gen](http://github.com/mongodb/mongo-ruby-driver/) -2. [Google Closure Library](http://code.google.com/closure/library/) -3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser) - -Contributors -============ - -Aaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy - -License -======= - - Copyright 2009 - 2012 Christian Amor Kvalheim. - - 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. - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/index.js deleted file mode 100644 index 4f59e9d92..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./lib/mongodb'); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/admin.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/admin.js deleted file mode 100644 index 6e9cd306c..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/admin.js +++ /dev/null @@ -1,339 +0,0 @@ -/*! - * Module dependencies. - */ -var Collection = require('./collection').Collection, - Cursor = require('./cursor').Cursor, - DbCommand = require('./commands/db_command').DbCommand, - utils = require('./utils'); - -/** - * Allows the user to access the admin functionality of MongoDB - * - * @class Represents the Admin methods of MongoDB. - * @param {Object} db Current db instance we wish to perform Admin operations on. - * @return {Function} Constructor for Admin type. - */ -function Admin(db) { - if(!(this instanceof Admin)) return new Admin(db); - this.db = db; -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from buildInfo or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.buildInfo = function(callback) { - this.serverInfo(callback); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverInfo or null if an error occured. - * @return {null} Returns no result - * @api private - */ -Admin.prototype.serverInfo = function(callback) { - this.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err != null) return callback(err, null); - return callback(null, doc.documents[0]); - }); -} - -/** - * Retrieve this db's server status. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from serverStatus or null if an error occured. - * @return {null} - * @api public - */ -Admin.prototype.serverStatus = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { - if(err == null && doc.documents[0].ok === 1) { - callback(null, doc.documents[0]); - } else { - if(err) return callback(err, false); - return callback(utils.toError(doc.documents[0]), false); - } - }); -}; - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingLevel or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.profilingLevel = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({profile:-1}, function(err, doc) { - doc = doc.documents[0]; - - if(err == null && doc.ok === 1) { - var was = doc.was; - if(was == 0) return callback(null, "off"); - if(was == 1) return callback(null, "slow_only"); - if(was == 2) return callback(null, "all"); - return callback(new Error("Error: illegal profiling level value " + was), null); - } else { - err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - } - }); -}; - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ping or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.ping = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - - this.db.executeDbAdminCommand({ping: 1}, callback); -} - -/** - * Authenticate against MongoDB - * - * @param {String} username The user name for the authentication. - * @param {String} password The password for the authentication. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authenticate or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.authenticate = function(username, password, callback) { - this.db.authenticate(username, password, {authdb: 'admin'}, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Logout current authenticated user - * - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.logout = function(callback) { - this.db.logout({authdb: 'admin'}, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Add a user to the MongoDB server, if the user exists it will - * overwrite the current password - * - * Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username The user name for the authentication. - * @param {String} password The password for the authentication. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.addUser = function(username, password, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - options.dbName = 'admin'; - // Add user - this.db.addUser(username, password, options, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Remove a user from the MongoDB server - * - * Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username The user name for the authentication. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - options.dbName = 'admin'; - - this.db.removeUser(username, options, function(err, doc) { - return callback(err, doc); - }) -} - -/** - * Set the current profiling level of MongoDB - * - * @param {String} level The new profiling level (off, slow_only, all) - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from setProfilingLevel or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.setProfilingLevel = function(level, callback) { - var self = this; - var command = {}; - var profile = 0; - - if(level == "off") { - profile = 0; - } else if(level == "slow_only") { - profile = 1; - } else if(level == "all") { - profile = 2; - } else { - return callback(new Error("Error: illegal profiling level value " + level)); - } - - // Set up the profile number - command['profile'] = profile; - - this.db.executeDbAdminCommand(command, function(err, doc) { - doc = doc.documents[0]; - - if(err == null && doc.ok === 1) - return callback(null, level); - return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - }); -}; - -/** - * Retrive the current profiling information for MongoDB - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from profilingInfo or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.profilingInfo = function(callback) { - try { - new Cursor(this.db, new Collection(this.db, DbCommand.SYSTEM_PROFILE_COLLECTION), {}, {}, {dbName: 'admin'}).toArray(function(err, items) { - return callback(err, items); - }); - } catch (err) { - return callback(err, null); - } -}; - -/** - * Execute a db command against the Admin database - * - * @param {Object} command A command object `{ping:1}`. - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.command = function(command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - // Execute a command - this.db.executeDbAdminCommand(command, options, function(err, doc) { - // Ensure change before event loop executes - return callback != null ? callback(err, doc) : null; - }); -} - -/** - * Validate an existing collection - * - * @param {String} collectionName The name of the collection to validate. - * @param {Object} [options] Optional parameters to the command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from validateCollection or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - - var self = this; - var command = {validate: collectionName}; - var keys = Object.keys(options); - - // Decorate command with extra options - for(var i = 0; i < keys.length; i++) { - if(options.hasOwnProperty(keys[i])) { - command[keys[i]] = options[keys[i]]; - } - } - - this.db.executeDbCommand(command, function(err, doc) { - if(err != null) return callback(err, null); - doc = doc.documents[0]; - - if(doc.ok === 0) - return callback(new Error("Error with validate command"), null); - if(doc.result != null && doc.result.constructor != String) - return callback(new Error("Error with validation data"), null); - if(doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error("Error: invalid collection " + collectionName), null); - if(doc.valid != null && !doc.valid) - return callback(new Error("Error: invalid collection " + collectionName), null); - - return callback(null, doc); - }); -}; - -/** - * List the available databases - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from listDatabases or null if an error occured. - * @return {null} Returns no result - * @api public - */ -Admin.prototype.listDatabases = function(callback) { - // Execute the listAllDatabases command - this.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, doc) { - if(err != null) return callback(err, null); - return callback(null, doc.documents[0]); - }); -} - -/** - * Get ReplicaSet status - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from replSetGetStatus or null if an error occured. - * @return {null} - * @api public - */ -Admin.prototype.replSetGetStatus = function(callback) { - var self = this; - - this.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { - if(err == null && doc.documents[0].ok === 1) - return callback(null, doc.documents[0]); - if(err) return callback(err, false); - return callback(utils.toError(doc.documents[0]), false); - }); -}; - -/** - * @ignore - */ -exports.Admin = Admin; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js deleted file mode 100644 index 09558965f..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_cr.js +++ /dev/null @@ -1,57 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils'); - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Execute all four - db._executeQueryCommand(DbCommand.createGetNonceCommand(db), options, function(err, result, connection) { - // Execute on all the connections - if(err == null) { - // Nonce used to make authentication request with md5 hash - var nonce = result.documents[0].nonce; - // Execute command - db._executeQueryCommand(DbCommand.createAuthenticationCommand(db, username, password, nonce, authdb), {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result - && Array.isArray(result.documents) - && result.documents.length > 0 - && (result.documents[0].err != null || result.documents[0].errmsg != null)) { - errorObject = utils.toError(result.documents[0]); - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null - && result && Array.isArray(result.documents) && result.documents.length > 0 - && result.documents[0].ok == 1) { // We authenticated correctly save the credentials - db.serverConfig.auth.add('MONGODB-CR', db.databaseName, username, password, authdb); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js deleted file mode 100644 index 47b5155ed..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_gssapi.js +++ /dev/null @@ -1,149 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , format = require('util').format; - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - var error = null; - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - - // Start Auth process for a connection - GSSAPIInitialize(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) { - // Adjust number of connections left to connect - numberOfConnections = numberOfConnections - 1; - // If we have an error save it - if(err) error = err; - - // We are done - if(numberOfConnections == 0) { - if(err) return callback(error, false); - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return callback(null, true); - } - }); - } -} - -// -// Initialize step -var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, connection, callback) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, gssapiServiceName); - - // Perform initialization - mongo_auth_process.init(username, password, function(err, context) { - if(err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if(err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, connection, callback) { - // Build the sasl start command - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: payload - , autoAuthorize: 1 - }; - - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - // Get the payload - doc = doc.documents[0]; - var db_payload = doc.payload; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - - // Get the result document - doc = doc.documents[0]; - - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback); - }); - }); -} - -var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, connection, callback) { - // Build final command - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Let's finish the auth process against mongodb - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err, false); - - mongo_auth_process.transition(null, function(err, payload) { - if(err) return callback(err, false); - callback(null, true); - }); - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js deleted file mode 100644 index 594181db0..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_plain.js +++ /dev/null @@ -1,66 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , Binary = require('bson').Binary - , format = require('util').format; - -var authenticate = function(db, username, password, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Create payload - var payload = new Binary(format("\x00%s\x00%s", username, password)); - - // Let's start the sasl process - var command = { - saslStart: 1 - , mechanism: 'PLAIN' - , payload: payload - , autoAuthorize: 1 - }; - - // Grab all the connections - var connections = options['connection'] != null ? [options['connection']] : db.serverConfig.allRawConnections(); - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - var connection = connections[i]; - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - - // Ensure we save any error - if(err) { - errorObject = err; - } else if(result.documents[0].err != null || result.documents[0].errmsg != null){ - errorObject = utils.toError(result.documents[0]); - } - - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - if(errorObject == null && result.documents[0].ok == 1) { - // We authenticated correctly save the credentials - db.serverConfig.auth.add('PLAIN', db.databaseName, username, password); - // Return callback - internalCallback(errorObject, true); - } else { - internalCallback(errorObject, false); - } - } - }); - } -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js deleted file mode 100644 index 316fa3a49..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/auth/mongodb_sspi.js +++ /dev/null @@ -1,135 +0,0 @@ -var DbCommand = require('../commands/db_command').DbCommand - , utils = require('../utils') - , format = require('util').format; - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -var authenticate = function(db, username, password, authdb, options, callback) { - var numberOfConnections = 0; - var errorObject = null; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - - if(options['connection'] != null) { - //if a connection was explicitly passed on options, then we have only one... - numberOfConnections = 1; - } else { - // Get the amount of connections in the pool to ensure we have authenticated all comments - numberOfConnections = db.serverConfig.allRawConnections().length; - options['onAll'] = true; - } - - // Set the sspi server name - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - - // Grab all the connections - var connections = db.serverConfig.allRawConnections(); - var error = null; - - // Authenticate all connections - for(var i = 0; i < numberOfConnections; i++) { - // Start Auth process for a connection - SSIPAuthenticate(db, username, password, authdb, gssapiServiceName, connections[i], function(err, result) { - // Adjust number of connections left to connect - numberOfConnections = numberOfConnections - 1; - // If we have an error save it - if(err) error = err; - - // We are done - if(numberOfConnections == 0) { - if(err) return callback(err, false); - // We authenticated correctly save the credentials - db.serverConfig.auth.add('GSSAPI', db.databaseName, username, password, authdb, gssapiServiceName); - // Return valid callback - return callback(null, true); - } - }); - } -} - -var SSIPAuthenticate = function(db, username, password, authdb, service_name, connection, callback) { - // -------------------------------------------------------------- - // Async Version - // -------------------------------------------------------------- - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: '' - , autoAuthorize: 1 - }; - - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.socketOptions.host, connection.socketOptions.port, service_name); - - // Execute first sasl step - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.init(username, password, function(err) { - if(err) return callback(err); - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - db._executeQueryCommand(DbCommand.createDbCommand(db, command, {}, '$external'), {connection:connection}, function(err, doc) { - if(err) return callback(err); - doc = doc.documents[0]; - - if(doc.done) return callback(null, true); - callback(new Error("Authentication failed"), false); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.authenticate = authenticate; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/collection.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/collection.js deleted file mode 100644 index 7c2ae0fb6..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/collection.js +++ /dev/null @@ -1,1730 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var InsertCommand = require('./commands/insert_command').InsertCommand - , QueryCommand = require('./commands/query_command').QueryCommand - , DeleteCommand = require('./commands/delete_command').DeleteCommand - , UpdateCommand = require('./commands/update_command').UpdateCommand - , DbCommand = require('./commands/db_command').DbCommand - , ObjectID = require('bson').ObjectID - , Code = require('bson').Code - , Cursor = require('./cursor').Cursor - , utils = require('./utils'); - -/** - * Precompiled regexes - * @ignore -**/ -const eErrorMessages = /No matching object found/; - -/** - * toString helper. - * @ignore - */ -var toString = Object.prototype.toString; - -/** - * Create a new Collection instance (INTERNAL TYPE) - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **slaveOk** {Boolean, default:false}, Allow reads from secondaries. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - * @class Represents a Collection - * @param {Object} db db instance. - * @param {String} collectionName collection name. - * @param {Object} [pkFactory] alternative primary key factory. - * @param {Object} [options] additional options for the collection. - * @return {Object} a collection instance. - */ -function Collection (db, collectionName, pkFactory, options) { - if(!(this instanceof Collection)) return new Collection(db, collectionName, pkFactory, options); - - checkCollectionName(collectionName); - - this.db = db; - this.collectionName = collectionName; - this.internalHint = null; - this.opts = options != null && ('object' === typeof options) ? options : {}; - this.slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - this.serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; - this.raw = options == null || options.raw == null ? db.raw : options.raw; - - this.readPreference = options == null || options.readPreference == null ? db.serverConfig.options.readPreference : options.readPreference; - this.readPreference = this.readPreference == null ? 'primary' : this.readPreference; - - this.pkFactory = pkFactory == null - ? ObjectID - : pkFactory; - - var self = this; -} - -/** - * Inserts a single document or a an array of documents into MongoDB. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **continueOnError/keepGoing** {Boolean, default:false}, keep inserting documents even if one document has an error, *mongodb 1.9.1 >*. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **forceServerObjectId** {Boolean, default:false}, let server assign ObjectId instead of the driver - * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Array|Object} docs - * @param {Object} [options] optional options for insert command - * @param {Function} [callback] optional callback for the function, must be provided when using a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.insert = function insert (docs, options, callback) { - if ('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - insertAll(self, Array.isArray(docs) ? docs : [docs], options, callback); - return this; -}; - -/** - * @ignore - */ -var checkCollectionName = function checkCollectionName (collectionName) { - if('string' !== typeof collectionName) { - throw Error("collection name must be a String"); - } - - if(!collectionName || collectionName.indexOf('..') != -1) { - throw Error("collection names cannot be empty"); - } - - if(collectionName.indexOf('$') != -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { - throw Error("collection names must not contain '$'"); - } - - if(collectionName.match(/^\.|\.$/) != null) { - throw Error("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the colletion name - if(!!~collectionName.indexOf("\x00")) { - throw new Error("collection names cannot contain a null character"); - } -}; - -/** - * Removes documents specified by `selector` from the db. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **single** {Boolean, default:false}, removes the first document found. - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} [selector] optional select, no selector is equivalent to removing all documents. - * @param {Object} [options] additional options during remove. - * @param {Function} [callback] must be provided if you performing a remove with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.remove = function remove(selector, options, callback) { - if ('function' === typeof selector) { - callback = selector; - selector = options = {}; - } else if ('function' === typeof options) { - callback = options; - options = {}; - } - - // Ensure options - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Ensure we have at least an empty selector - selector = selector == null ? {} : selector; - // Set up flags for the command, if we have a single document remove - var flags = 0 | (options.single ? 1 : 0); - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = this.db.databaseName; - } - - // Create a delete command - var deleteCommand = new DeleteCommand( - this.db - , dbName + "." + this.collectionName - , selector - , flags); - - var self = this; - var errorOptions = _getWriteConcern(self, options, callback); - // Execute the command, do not add a callback as it's async - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - var commandOptions = {read:false}; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - // Set safe option - commandOptions['safe'] = true; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - this.db._executeRemoveCommand(deleteCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if(err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else { - callback(null, error[0].n); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - var result = this.db._executeRemoveCommand(deleteCommand); - // If no callback just return - if (!callback) return; - // If error return error - if (result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(); - } -}; - -/** - * Renames the collection. - * - * Options - * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists. - * - * @param {String} newName the new name of the collection. - * @param {Object} [options] returns option results. - * @param {Function} callback the callback accepting the result - * @return {null} - * @api public - */ -Collection.prototype.rename = function rename(newName, options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {} - } - - // Ensure the new name is valid - checkCollectionName(newName); - - // Execute the command, return the new renamed collection if successful - self.db._executeQueryCommand(DbCommand.createRenameCollectionCommand(self.db, self.collectionName, newName, options) - , utils.handleSingleCommandResultReturn(true, false, function(err, result) { - if(err) return callback(err, null) - try { - if(options.new_collection) - return callback(null, new Collection(self.db, newName, self.db.pkFactory)); - self.collectionName = newName; - callback(null, self); - } catch(err) { - callback(err, null); - } - })); -} - -/** - * @ignore - */ -var insertAll = function insertAll (self, docs, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // Insert options (flags for insert) - var insertFlags = {}; - // If we have a mongodb version >= 1.9.1 support keepGoing attribute - if(options['keepGoing'] != null) { - insertFlags['keepGoing'] = options['keepGoing']; - } - - // If we have a mongodb version >= 1.9.1 support keepGoing attribute - if(options['continueOnError'] != null) { - insertFlags['continueOnError'] = options['continueOnError']; - } - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = self.db.databaseName; - } - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - insertFlags['serializeFunctions'] = options['serializeFunctions']; - } else { - insertFlags['serializeFunctions'] = self.serializeFunctions; - } - - // Get checkKeys value - var checkKeys = typeof options.checkKeys != 'boolean' ? true : options.checkKeys; - - // Pass in options - var insertCommand = new InsertCommand( - self.db - , dbName + "." + self.collectionName, checkKeys, insertFlags); - - // Add the documents and decorate them with id's if they have none - for(var index = 0, len = docs.length; index < len; ++index) { - var doc = docs[index]; - - // Add id to each document if it's not already defined - if (!(Buffer.isBuffer(doc)) - && doc['_id'] == null - && self.db.forceServerObjectId != true - && options.forceServerObjectId != true) { - doc['_id'] = self.pkFactory.createPk(); - } - - insertCommand.add(doc); - } - - // Collect errorOptions - var errorOptions = _getWriteConcern(self, options, callback); - // Default command options - var commandOptions = {}; - // If safe is defined check for error message - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - self.db._executeInsertCommand(insertCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if (err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else { - callback(null, docs); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute the call without a write concern - var result = self.db._executeInsertCommand(insertCommand, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - - // Otherwise just return - return callback(null, docs); - } -}; - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} [doc] the document to save - * @param {Object} [options] additional options during remove. - * @param {Function} [callback] must be provided if you performing a safe save - * @return {null} - * @api public - */ -Collection.prototype.save = function save(doc, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - // Throw an error if attempting to perform a bulk operation - if(Array.isArray(doc)) throw new Error("doc parameter must be a single document"); - // Extract the id, if we have one we need to do a update command - var id = doc['_id']; - var commandOptions = _getWriteConcern(this, options, callback); - - if(id) { - commandOptions.upsert = true; - this.update({ _id: id }, doc, commandOptions, callback); - } else { - this.insert(doc, commandOptions, callback && function (err, docs) { - if(err) return callback(err, null); - - if(Array.isArray(docs)) { - callback(err, docs[0]); - } else { - callback(err, docs); - } - }); - } -}; - -/** - * Updates documents. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **upsert** {Boolean, default:false}, perform an upsert operation. - * - **multi** {Boolean, default:false}, update all documents matching the selector. - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **checkKeys** {Boolean, default:true}, allows for disabling of document key checking (WARNING OPENS YOU UP TO INJECTION ATTACKS) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} selector the query to select the document/documents to be updated - * @param {Object} document the fields/vals to be updated, or in the case of an upsert operation, inserted. - * @param {Object} [options] additional options during update. - * @param {Function} [callback] must be provided if you performing an update with a writeconcern - * @return {null} - * @api public - */ -Collection.prototype.update = function update(selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // DbName - var dbName = options['dbName']; - // If no dbname defined use the db one - if(dbName == null) { - dbName = this.db.databaseName; - } - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') return callback(new Error("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') return callback(new Error("document must be a valid JavaScript object")); - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = this.serializeFunctions; - } - - // Build the options command - var updateCommand = new UpdateCommand( - this.db - , dbName + "." + this.collectionName - , selector - , document - , options); - - var self = this; - // Unpack the error options if any - var errorOptions = _getWriteConcern(this, options, callback); - // If safe is defined check for error message - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - var commandOptions = {read:false}; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute command with safe options (rolls up both command and safe command into one and executes them on the same connection) - this.db._executeUpdateCommand(updateCommand, commandOptions, function (err, error) { - error = error && error.documents; - if(!callback) return; - - if(err) { - callback(err); - } else if(error[0].err || error[0].errmsg) { - callback(utils.toError(error[0])); - } else { - // Perform the callback - callback(null, error[0].n, error[0]); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute update - var result = this.db._executeUpdateCommand(updateCommand); - // If no callback just return - if (!callback) return; - // If error return error - if (result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(); - } -}; - -/** - * The distinct command returns returns a list of distinct values for the given key across a collection. - * - * Options - * - **readPreference** {String}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {String} key key to run distinct against. - * @param {Object} [query] option query to narrow the returned objects. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from distinct or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.distinct = function distinct(key, query, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - - var mapCommandHash = { - 'distinct': this.collectionName - , 'query': query - , 'key': key - }; - - // Set read preference if we set one - var readPreference = options['readPreference'] ? options['readPreference'] : false; - // Execute the command - this.db._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this.db, mapCommandHash) - , {read:readPreference} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - callback(null, result.values); - })); -}; - -/** - * Count number of matching documents in the db to a query. - * - * Options - * - **skip** {Number}, The number of documents to skip for the count. - * - **limit** {Number}, The limit of documents to count. - * - **readPreference** {String}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Object} [query] query to filter by before performing count. - * @param {Object} [options] additional options during count. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the count method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.count = function count (query, options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - query = args.length ? args.shift() || {} : {}; - options = args.length ? args.shift() || {} : {}; - var skip = options.skip; - var limit = options.limit; - - // Final query - var commandObject = { - 'count': this.collectionName - , 'query': query - , 'fields': null - }; - - // Add limit and skip if defined - if(typeof skip == 'number') commandObject.skip = skip; - if(typeof limit == 'number') commandObject.limit = limit; - - // Set read preference if we set one - var readPreference = _getReadConcern(this, options); - - // Execute the command - this.db._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this.db, commandObject) - , {read: readPreference} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - if(result == null) return callback(new Error("no result returned for count"), null); - callback(null, result.n); - })); -}; - - -/** - * Drop the collection - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the drop method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.drop = function drop(callback) { - this.db.dropCollection(this.collectionName, callback); -}; - -/** - * Find and update a document. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **remove** {Boolean, default:false}, set to true to remove the object before returning. - * - **upsert** {Boolean, default:false}, perform an upsert operation. - * - **new** {Boolean, default:false}, set to true if you want to return the modified object rather than the original. Ignored for remove. - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} query query object to locate the object to modify - * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate - * @param {Object} doc - the fields/vals to be updated - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndModify method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.findAndModify = function findAndModify (query, sort, doc, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - var self = this; - - var queryObject = { - 'findandmodify': this.collectionName - , 'query': query - , 'sort': utils.formattedOrderClause(sort) - }; - - queryObject.new = options.new ? 1 : 0; - queryObject.remove = options.remove ? 1 : 0; - queryObject.upsert = options.upsert ? 1 : 0; - - if (options.fields) { - queryObject.fields = options.fields; - } - - if (doc && !options.remove) { - queryObject.update = doc; - } - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = this.serializeFunctions; - } - - // Only run command and rely on getLastError command - var command = DbCommand.createDbCommand(this.db, queryObject, options) - // Execute command - this.db._executeQueryCommand(command - , {read:false}, utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - return callback(null, result.value, result); - })); -} - -/** - * Find and remove a document - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} query query object to locate the object to modify - * @param {Array} sort - if multiple docs match, choose the first one in the specified sort order as the object to manipulate - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findAndRemove method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.findAndRemove = function(query, sort, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - // Add the remove option - options['remove'] = true; - // Execute the callback - this.findAndModify(query, sort, null, options, callback); -} - -var testForFields = { - limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 - , numberOfRetries: 1, awaitdata: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 - , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1 -}; - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * - * Various argument possibilities - * - callback? - * - selector, callback?, - * - selector, fields, callback? - * - selector, options, callback? - * - selector, fields, options, callback? - * - selector, fields, skip, limit, callback? - * - selector, fields, skip, limit, timeout, callback? - * - * Options - * - **limit** {Number, default:0}, sets the limit of documents returned in the query. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination). - * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * - **explain** {Boolean, default:false}, explain the query instead of returning the data. - * - **snapshot** {Boolean, default:false}, snapshot query. - * - **timeout** {Boolean, default:false}, specify if the cursor can timeout. - * - **tailable** {Boolean, default:false}, specify if the cursor is tailable. - * - **tailableRetryInterval** {Number, default:100}, specify the miliseconds between getMores on tailable cursor. - * - **numberOfRetries** {Number, default:5}, specify the number of times to retry the tailable cursor. - * - **awaitdata** {Boolean, default:false} allow the cursor to wait for data, only applicable for tailable cursor. - * - **exhaust** {Boolean, default:false} have the server send all the documents at once as getMore packets, not recommended. - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **returnKey** {Boolean, default:false}, only return the index key. - * - **maxScan** {Number}, Limit the number of items to scan. - * - **min** {Number}, Set index bounds. - * - **max** {Number}, Set index bounds. - * - **showDiskLoc** {Boolean, default:false}, Show disk location of results. - * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler. - * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - **numberOfRetries** {Number, default:5}, if using awaidata specifies the number of times to retry on timeout. - * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system - * - * @param {Object|ObjectID} query query object to locate the object to modify - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the find method or null if an error occured. - * @return {Cursor} returns a cursor to the query - * @api public - */ -Collection.prototype.find = function find () { - var options - , args = Array.prototype.slice.call(arguments, 0) - , has_callback = typeof args[args.length - 1] === 'function' - , has_weird_callback = typeof args[0] === 'function' - , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) - , len = args.length - , selector = len >= 1 ? args[0] : {} - , fields = len >= 2 ? args[1] : undefined; - - if(len === 1 && has_weird_callback) { - // backwards compat for callback?, options case - selector = {}; - options = args[0]; - } - - if(len === 2 && !Array.isArray(fields)) { - var fieldKeys = Object.getOwnPropertyNames(fields); - var is_option = false; - - for(var i = 0; i < fieldKeys.length; i++) { - if(testForFields[fieldKeys[i]] != null) { - is_option = true; - break; - } - } - - if(is_option) { - options = fields; - fields = undefined; - } else { - options = {}; - } - } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { - var newFields = {}; - // Rewrite the array - for(var i = 0; i < fields.length; i++) { - newFields[fields[i]] = 1; - } - // Set the fields - fields = newFields; - } - - if(3 === len) { - options = args[2]; - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Validate correctness of the field selector - var object = fields; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { - selector = {_id:selector}; - } - - // If it's a serialized fields field we need to just let it through - // user be warned it better be good - if(options && options.fields && !(Buffer.isBuffer(options.fields))) { - fields = {}; - - if(Array.isArray(options.fields)) { - if(!options.fields.length) { - fields['_id'] = 1; - } else { - for (var i = 0, l = options.fields.length; i < l; i++) { - fields[options.fields[i]] = 1; - } - } - } else { - fields = options.fields; - } - } - - if (!options) options = {}; - options.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; - options.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; - options.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.raw; - options.hint = options.hint != null ? normalizeHintField(options.hint) : this.internalHint; - options.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; - // If we have overridden slaveOk otherwise use the default db setting - options.slaveOk = options.slaveOk != null ? options.slaveOk : this.db.slaveOk; - - // Set option - var o = options; - // Support read/readPreference - if(o["read"] != null) o["readPreference"] = o["read"]; - // Set the read preference - o.read = o["readPreference"] ? o.readPreference : this.readPreference; - // Adjust slave ok if read preference is secondary or secondary only - if(o.read == "secondary" || o.read == "secondaryOnly") options.slaveOk = true; - - // callback for backward compatibility - if(callback) { - // TODO refactor Cursor args - callback(null, new Cursor(this.db, this, selector, fields, o)); - } else { - return new Cursor(this.db, this, selector, fields, o); - } -}; - -/** - * Normalizes a `hint` argument. - * - * @param {String|Object|Array} hint - * @return {Object} - * @api private - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if(typeof hint == 'string') { - finalHint = hint; - } else if(Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if(hint != null && typeof hint == 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Finds a single document based on the query - * - * Various argument possibilities - * - callback? - * - selector, callback?, - * - selector, fields, callback? - * - selector, options, callback? - * - selector, fields, options, callback? - * - selector, fields, skip, limit, callback? - * - selector, fields, skip, limit, timeout, callback? - * - * Options - * - **limit** {Number, default:0}, sets the limit of documents returned in the query. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **fields** {Object}, the fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * - **skip** {Number, default:0}, set to skip N documents ahead in your query (useful for pagination). - * - **hint** {Object}, tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * - **explain** {Boolean, default:false}, explain the query instead of returning the data. - * - **snapshot** {Boolean, default:false}, snapshot query. - * - **timeout** {Boolean, default:false}, specify if the cursor can timeout. - * - **tailable** {Boolean, default:false}, specify if the cursor is tailable. - * - **batchSize** {Number, default:0}, set the batchSize for the getMoreCommand when iterating over the query results. - * - **returnKey** {Boolean, default:false}, only return the index key. - * - **maxScan** {Number}, Limit the number of items to scan. - * - **min** {Number}, Set index bounds. - * - **max** {Number}, Set index bounds. - * - **showDiskLoc** {Boolean, default:false}, Show disk location of results. - * - **comment** {String}, You can put a $comment field on a query to make looking in the profiler logs simpler. - * - **raw** {Boolean, default:false}, Return all BSON documents as Raw Buffer documents. - * - **readPreference** {String}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - **partial** {Boolean, default:false}, specify if the cursor should return partial results when querying against a sharded system - * - * @param {Object|ObjectID} query query object to locate the object to modify - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the findOne method or null if an error occured. - * @return {Cursor} returns a cursor to the query - * @api public - */ -Collection.prototype.findOne = function findOne () { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - var cursor = this.find.apply(this, args).limit(-1).batchSize(1); - // Return the item - cursor.nextObject(function(err, item) { - if(err != null) return callback(utils.toError(err), null); - callback(null, item); - }); -}; - -/** - * Creates an index on the collection. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the createIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.createIndex = function createIndex (fieldOrSpec, options, callback) { - // Clean up call - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Collect errorOptions - var errorOptions = _getWriteConcern(this, options, callback); - // Execute create index - this.db.createIndex(this.collectionName, fieldOrSpec, options, callback); -}; - -/** - * Ensures that an index exists, if it does not it creates it - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the ensureIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.ensureIndex = function ensureIndex (fieldOrSpec, options, callback) { - // Clean up call - if (typeof callback === 'undefined' && typeof options === 'function') { - callback = options; - options = {}; - } - - if (options == null) { - options = {}; - } - - // Execute create index - this.db.ensureIndex(this.collectionName, fieldOrSpec, options, callback); -}; - -/** - * Retrieves this collections index info. - * - * Options - * - **full** {Boolean, default:false}, returns the full raw index information. - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexInformation method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexInformation = function indexInformation (options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - // Call the index information - this.db.indexInformation(this.collectionName, options, callback); -}; - -/** - * Drops an index from this collection. - * - * @param {String} name - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndex method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.dropIndex = function dropIndex (name, callback) { - this.db.dropIndex(this.collectionName, name, callback); -}; - -/** - * Drops all indexes from this collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropAllIndexes method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.dropAllIndexes = function dropIndexes (callback) { - this.db.dropIndex(this.collectionName, '*', function (err, result) { - if(err) return callback(err, false); - callback(null, true); - }); -} - -/** - * Drops all indexes from this collection. - * - * @deprecated - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the dropIndexes method or null if an error occured. - * @return {null} - * @api private - */ -Collection.prototype.dropIndexes = Collection.prototype.dropAllIndexes; - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the reIndex method or null if an error occured. - * @return {null} - * @api public -**/ -Collection.prototype.reIndex = function(callback) { - this.db.reIndex(this.collectionName, callback); -} - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * Options - * - **out** {Object}, sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * - **query** {Object}, query filter object. - * - **sort** {Object}, sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * - **limit** {Number}, number of objects to return from collection. - * - **keeptemp** {Boolean, default:false}, keep temporary data. - * - **finalize** {Function | String}, finalize function. - * - **scope** {Object}, can pass in variables that can be access from map/reduce/finalize. - * - **jsMode** {Boolean, default:false}, it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * - **verbose** {Boolean, default:false}, provide statistics on job execution time. - * - **readPreference** {String, only for inline results}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Function|String} map the mapping function. - * @param {Function|String} reduce the reduce function. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the mapReduce method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.mapReduce = function mapReduce (map, reduce, options, callback) { - if ('function' === typeof options) callback = options, options = {}; - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if(null == options.out) { - throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); - } - - if ('function' === typeof map) { - map = map.toString(); - } - - if ('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if ('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - - var mapCommandHash = { - mapreduce: this.collectionName - , map: map - , reduce: reduce - }; - - // Add any other options passed in - for (var name in options) { - if ('scope' == name) { - mapCommandHash[name] = processScope(options[name]); - } else { - mapCommandHash[name] = options[name]; - } - } - - // Set read preference if we set one - var readPreference = _getReadConcern(this, options); - - // If we have a read preference and inline is not set as output fail hard - if((readPreference != false && readPreference != 'primary') - && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { - throw new Error("a readPreference can only be provided when performing an inline mapReduce"); - } - - // self - var self = this; - var cmd = DbCommand.createDbCommand(this.db, mapCommandHash); - - this.db._executeQueryCommand(cmd, {read:readPreference}, function (err, result) { - if(err) return callback(err); - if(!result || !result.documents || result.documents.length == 0) - return callback(Error("command failed to return results"), null) - - // Check if we have an error - if(1 != result.documents[0].ok || result.documents[0].err || result.documents[0].errmsg) { - return callback(utils.toError(result.documents[0])); - } - - // Create statistics value - var stats = {}; - if(result.documents[0].timeMillis) stats['processtime'] = result.documents[0].timeMillis; - if(result.documents[0].counts) stats['counts'] = result.documents[0].counts; - if(result.documents[0].timing) stats['timing'] = result.documents[0].timing; - - // invoked with inline? - if(result.documents[0].results) { - return callback(null, result.documents[0].results, stats); - } - - // The returned collection - var collection = null; - - // If we have an object it's a different db - if(result.documents[0].result != null && typeof result.documents[0].result == 'object') { - var doc = result.documents[0].result; - collection = self.db.db(doc.db).collection(doc.collection); - } else { - // Create a collection object that wraps the result collection - collection = self.db.collection(result.documents[0].result) - } - - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return callback(err, collection); - } - - // Return stats as third set of values - callback(err, collection, stats); - }); -}; - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope (scope) { - if (!utils.isObject(scope)) { - return scope; - } - - var keys = Object.keys(scope); - var i = keys.length; - var key; - - while (i--) { - key = keys[i]; - if ('function' == typeof scope[key]) { - scope[key] = new Code(String(scope[key])); - } - } - - return scope; -} - -/** - * Group function helper - * @ignore - */ -var groupFunction = function () { - var c = db[ns].find(condition); - var map = new Map(); - var reduce_function = reduce; - - while (c.hasNext()) { - var obj = c.next(); - var key = {}; - - for (var i = 0, len = keys.length; i < len; ++i) { - var k = keys[i]; - key[k] = obj[k]; - } - - var aggObj = map.get(key); - - if (aggObj == null) { - var newObj = Object.extend({}, key); - aggObj = Object.extend(newObj, initial); - map.put(key, aggObj); - } - - reduce_function(obj, aggObj); - } - - return { "result": map.values() }; -}.toString(); - -/** - * Run a group command across a collection - * - * Options - * - **readPreference** {String}, the preferred read preference (Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Object|Array|Function|Code} keys an object, array or function expressing the keys to group by. - * @param {Object} condition an optional condition that must be true for a row to be considered. - * @param {Object} initial initial value of the aggregation counter object. - * @param {Function|Code} reduce the reduce function aggregates (reduces) the objects iterated - * @param {Function|Code} finalize an optional function to be run on each item in the result set just before the item is returned. - * @param {Boolean} command specify if you wish to run using the internal group command or using eval, default is true. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the group method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.group = function group(keys, condition, initial, reduce, finalize, command, options, callback) { - var args = Array.prototype.slice.call(arguments, 3); - callback = args.pop(); - // Fetch all commands - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if(!(typeof finalize == 'function')) { - command = finalize; - finalize = null; - } - - if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { - keys = Object.keys(keys); - } - - if(typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if(typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - // Execute using the command - if(command) { - var reduceFunction = reduce instanceof Code - ? reduce - : new Code(reduce); - - var selector = { - group: { - 'ns': this.collectionName - , '$reduce': reduceFunction - , 'cond': condition - , 'initial': initial - , 'out': "inline" - } - }; - - // if finalize is defined - if(finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || keys instanceof Code) { - selector.group.$keyf = keys instanceof Code - ? keys - : new Code(keys); - } else { - var hash = {}; - keys.forEach(function (key) { - hash[key] = 1; - }); - selector.group.key = hash; - } - - var cmd = DbCommand.createDbSlaveOkCommand(this.db, selector); - // Set read preference if we set one - var readPreference = _getReadConcern(this, options); - // Execute the command - this.db._executeQueryCommand(cmd - , {read:readPreference} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - callback(null, result.retval); - })); - } else { - // Create execution scope - var scope = reduce != null && reduce instanceof Code - ? reduce.scope - : {}; - - scope.ns = this.collectionName; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - this.db.eval(new Code(groupfn, scope), function (err, results) { - if (err) return callback(err, null); - callback(null, results.result || results); - }); - } -}; - -/** - * Returns the options of the collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the options method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.options = function options(callback) { - this.db.collectionsInfo(this.collectionName, function (err, cursor) { - if (err) return callback(err); - cursor.nextObject(function (err, document) { - callback(err, document && document.options || null); - }); - }); -}; - -/** - * Returns if the collection is a capped collection - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the isCapped method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.isCapped = function isCapped(callback) { - this.options(function(err, document) { - if(err != null) { - callback(err); - } else { - callback(null, document && document.capped); - } - }); -}; - -/** - * Checks if one or more indexes exist on the collection - * - * @param {String|Array} indexNames check if one or more indexes exist on the collection. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexExists method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexExists = function indexExists(indexes, callback) { - this.indexInformation(function(err, indexInformation) { - // If we have an error return - if(err != null) return callback(err, null); - // Let's check for the index names - if(Array.isArray(indexes)) { - for(var i = 0; i < indexes.length; i++) { - if(indexInformation[indexes[i]] == null) { - return callback(null, false); - } - } - - // All keys found return true - return callback(null, true); - } else { - return callback(null, indexInformation[indexes] != null); - } - }); -} - -/** - * Execute the geoNear command to search for items in the collection - * - * Options - * - **num** {Number}, max number of results to return. - * - **maxDistance** {Number}, include results up to maxDistance from the point. - * - **distanceMultiplier** {Number}, include a value to multiply the distances with allowing for range conversions. - * - **query** {Object}, filter the results by a query. - * - **spherical** {Boolean, default:false}, perform query using a spherical model. - * - **uniqueDocs** {Boolean, default:false}, the closest location in a document to the center of the search region will always be returned MongoDB > 2.X. - * - **includeLocs** {Boolean, default:false}, include the location data fields in the top level of the results MongoDB > 2.X. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoNear method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.geoNear = function geoNear(x, y, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - geoNear:this.collectionName, - near: [x, y] - } - - // Decorate object if any with known properties - if(options['num'] != null) commandObject['num'] = options['num']; - if(options['maxDistance'] != null) commandObject['maxDistance'] = options['maxDistance']; - if(options['distanceMultiplier'] != null) commandObject['distanceMultiplier'] = options['distanceMultiplier']; - if(options['query'] != null) commandObject['query'] = options['query']; - if(options['spherical'] != null) commandObject['spherical'] = options['spherical']; - if(options['uniqueDocs'] != null) commandObject['uniqueDocs'] = options['uniqueDocs']; - if(options['includeLocs'] != null) commandObject['includeLocs'] = options['includeLocs']; - - // Ensure we have the right read preference inheritance - options.readPreference = _getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, function (err, res) { - if (err) { - callback(err); - } else if (res.err || res.errmsg) { - callback(utils.toError(res)); - } else { - // should we only be returning res.results here? Not sure if the user - // should see the other return information - callback(null, res); - } - }); -} - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * Options - * - **maxDistance** {Number}, include results up to maxDistance from the point. - * - **search** {Object}, filter the results by a query. - * - **limit** {Number}, max number of results to return. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Number} x point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {Number} y point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {Objects} [options] options for the map reduce job. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the geoHaystackSearch method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.geoHaystackSearch = function geoHaystackSearch(x, y, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - geoSearch:this.collectionName, - near: [x, y] - } - - // Decorate object if any with known properties - if(options['maxDistance'] != null) commandObject['maxDistance'] = options['maxDistance']; - if(options['query'] != null) commandObject['search'] = options['query']; - if(options['search'] != null) commandObject['search'] = options['search']; - if(options['limit'] != null) commandObject['limit'] = options['limit']; - - // Ensure we have the right read preference inheritance - options.readPreference = _getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, function (err, res) { - if (err) { - callback(err); - } else if (res.err || res.errmsg) { - callback(utils.toError(res)); - } else { - // should we only be returning res.results here? Not sure if the user - // should see the other return information - callback(null, res); - } - }); -} - -/** - * Retrieve all the indexes on the collection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the indexes method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.indexes = function indexes(callback) { - // Return all the index information - this.db.indexInformation(this.collectionName, {full:true}, callback); -} - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.1 - * - * Options - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Array} array containing all the aggregation framework commands for the execution. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the aggregate method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - // * - **explain** {Boolean}, return the query plan for the aggregation pipeline instead of the results. 2.3, 2.4 - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - var self = this; - - // If we have any of the supported options in the options object - var opts = args[args.length - 1]; - options = opts.readPreference || opts.explain ? args.pop() : {} - - // Convert operations to an array - if(!Array.isArray(args[0])) { - pipeline = []; - // Push all the operations to the pipeline - for(var i = 0; i < args.length; i++) pipeline.push(args[i]); - } - - // Build the command - var command = { aggregate : this.collectionName, pipeline : pipeline}; - - // Ensure we have the right read preference inheritance - options.readPreference = _getReadConcern(this, options); - - // Execute the command - this.db.command(command, options, function(err, result) { - if(err) { - callback(err); - } else if(result['err'] || result['errmsg']) { - callback(utils.toError(result)); - } else if(typeof result == 'object' && result['serverPipeline']) { - callback(null, result); - } else { - callback(null, result.result); - } - }); -} - -/** - * Get all the collection statistics. - * - * Options - * - **scale** {Number}, divide the returned sizes by scale value. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Objects} [options] options for the stats command. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the stats method or null if an error occured. - * @return {null} - * @api public - */ -Collection.prototype.stats = function stats(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - collStats:this.collectionName, - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Ensure we have the right read preference inheritance - options.readPreference = _getReadConcern(this, options); - - // Execute the command - this.db.command(commandObject, options, callback); -} - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, "hint", { - enumerable: true - , get: function () { - return this.internalHint; - } - , set: function (v) { - this.internalHint = normalizeHintField(v); - } -}); - -var _getReadConcern = function(self, options) { - if(options.readPreference) return options.readPreference; - if(self.readPreference) return self.readPreference; - if(self.db.readPreference) return self.readPreference; - return 'primary'; -} - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options, callback) { - // Final options - var finalOptions = {w:1}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(self.opts.w != null || typeof self.opts.j == 'boolean' || typeof self.opts.journal == 'boolean' || typeof self.opts.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.opts); - } else if(typeof self.opts.safe == "boolean") { - finalOptions = {w: (self.opts.safe ? 1 : 0)}; - } else if(self.db.safe.w != null || typeof self.db.safe.j == 'boolean' || typeof self.db.safe.journal == 'boolean' || typeof self.db.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.safe); - } else if(self.db.options.w != null || typeof self.db.options.j == 'boolean' || typeof self.db.options.journal == 'boolean' || typeof self.db.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.options); - } else if(typeof self.db.safe == "boolean") { - finalOptions = {w: (self.db.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * Expose. - */ -exports.Collection = Collection; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/base_command.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/base_command.js deleted file mode 100644 index 955858283..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/base_command.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - Base object used for common functionality -**/ -var BaseCommand = exports.BaseCommand = function BaseCommand() { -}; - -var id = 1; -BaseCommand.prototype.getRequestId = function getRequestId() { - if (!this.requestId) this.requestId = id++; - return this.requestId; -}; - -BaseCommand.prototype.setMongosReadPreference = function setMongosReadPreference(readPreference, tags) {} - -BaseCommand.prototype.updateRequestId = function() { - this.requestId = id++; - return this.requestId; -}; - -// OpCodes -BaseCommand.OP_REPLY = 1; -BaseCommand.OP_MSG = 1000; -BaseCommand.OP_UPDATE = 2001; -BaseCommand.OP_INSERT = 2002; -BaseCommand.OP_GET_BY_OID = 2003; -BaseCommand.OP_QUERY = 2004; -BaseCommand.OP_GET_MORE = 2005; -BaseCommand.OP_DELETE = 2006; -BaseCommand.OP_KILL_CURSORS = 2007; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/db_command.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/db_command.js deleted file mode 100644 index b7019c8fb..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/db_command.js +++ /dev/null @@ -1,245 +0,0 @@ -var QueryCommand = require('./query_command').QueryCommand, - InsertCommand = require('./insert_command').InsertCommand, - inherits = require('util').inherits, - utils = require('../utils'), - crypto = require('crypto'); - -/** - Db Command -**/ -var DbCommand = exports.DbCommand = function(dbInstance, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) { - QueryCommand.call(this); - this.collectionName = collectionName; - this.queryOptions = queryOptions; - this.numberToSkip = numberToSkip; - this.numberToReturn = numberToReturn; - this.query = query; - this.returnFieldSelector = returnFieldSelector; - this.db = dbInstance; - - if(this.db && this.db.slaveOk) { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Make sure we don't get a null exception - options = options == null ? {} : options; - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(DbCommand, QueryCommand); - -// Constants -DbCommand.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; -DbCommand.SYSTEM_INDEX_COLLECTION = "system.indexes"; -DbCommand.SYSTEM_PROFILE_COLLECTION = "system.profile"; -DbCommand.SYSTEM_USER_COLLECTION = "system.users"; -DbCommand.SYSTEM_COMMAND_COLLECTION = "$cmd"; -DbCommand.SYSTEM_JS_COLLECTION = "system.js"; - -// New commands -DbCommand.NcreateIsMasterCommand = function(db, databaseName) { - return new DbCommand(db, databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null); -}; - -// Provide constructors for different db commands -DbCommand.createIsMasterCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'ismaster':1}, null); -}; - -DbCommand.createCollectionInfoCommand = function(db, selector) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_NAMESPACE_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, 0, selector, null); -}; - -DbCommand.createGetNonceCommand = function(db, options) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'getnonce':1}, null); -}; - -DbCommand.createAuthenticationCommand = function(db, username, password, nonce, authdb) { - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password); - var key = md5.digest('hex'); - // Creat selector - var selector = {'authenticate':1, 'user':username, 'nonce':nonce, 'key':key}; - // Create db command - return new DbCommand(db, authdb + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NONE, 0, -1, selector, null); -}; - -DbCommand.createLogoutCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'logout':1}, null); -}; - -DbCommand.createCreateCollectionCommand = function(db, collectionName, options) { - var selector = {'create':collectionName}; - // Modify the options to ensure correct behaviour - for(var name in options) { - if(options[name] != null && options[name].constructor != Function) selector[name] = options[name]; - } - // Execute the command - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, selector, null); -}; - -DbCommand.createDropCollectionCommand = function(db, collectionName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'drop':collectionName}, null); -}; - -DbCommand.createRenameCollectionCommand = function(db, fromCollectionName, toCollectionName, options) { - var renameCollection = db.databaseName + "." + fromCollectionName; - var toCollection = db.databaseName + "." + toCollectionName; - var dropTarget = options && options.dropTarget ? options.dropTarget : false; - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}, null); -}; - -DbCommand.createGetLastErrorCommand = function(options, db) { - - if (typeof db === 'undefined') { - db = options; - options = {}; - } - // Final command - var command = {'getlasterror':1}; - // If we have an options Object let's merge in the fields (fsync/wtimeout/w) - if('object' === typeof options) { - for(var name in options) { - command[name] = options[name] - } - } - - // Special case for w == 1, remove the w - if(1 == command.w) { - delete command.w; - } - - // Execute command - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command, null); -}; - -DbCommand.createGetLastStatusCommand = DbCommand.createGetLastErrorCommand; - -DbCommand.createGetPreviousErrorsCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'getpreverror':1}, null); -}; - -DbCommand.createResetErrorHistoryCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'reseterror':1}, null); -}; - -DbCommand.createCreateIndexCommand = function(db, collectionName, fieldOrSpec, options) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if('string' == typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - - } else if(utils.isArray(fieldOrSpec)) { - - fieldOrSpec.forEach(function(f) { - if('string' == typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if(utils.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if(utils.isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - - } else if(utils.isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - // Generate the index name - var indexName = typeof options.name == 'string' - ? options.name - : indexes.join("_"); - - var selector = { - 'ns': db.databaseName + "." + collectionName, - 'key': fieldHash, - 'name': indexName - } - - // Ensure we have a correct finalUnique - var finalUnique = options == null || 'object' === typeof options - ? false - : options; - - // Set up options - options = options == null || typeof options == 'boolean' - ? {} - : options; - - // Add all the options - var keys = Object.keys(options); - for(var i = 0; i < keys.length; i++) { - selector[keys[i]] = options[keys[i]]; - } - - if(selector['unique'] == null) - selector['unique'] = finalUnique; - - var name = db.databaseName + "." + DbCommand.SYSTEM_INDEX_COLLECTION; - var cmd = new InsertCommand(db, name, false); - return cmd.add(selector); -}; - -DbCommand.logoutCommand = function(db, command_hash, options) { - var dbName = options != null && options['authdb'] != null ? options['authdb'] : db.databaseName; - return new DbCommand(db, dbName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null); -} - -DbCommand.createDropIndexCommand = function(db, collectionName, indexName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'deleteIndexes':collectionName, 'index':indexName}, null); -}; - -DbCommand.createReIndexCommand = function(db, collectionName) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'reIndex':collectionName}, null); -}; - -DbCommand.createDropDatabaseCommand = function(db) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, {'dropDatabase':1}, null); -}; - -DbCommand.createDbCommand = function(db, command_hash, options, auth_db) { - var db_name = (auth_db ? auth_db : db.databaseName) + "." + DbCommand.SYSTEM_COMMAND_COLLECTION; - return new DbCommand(db, db_name, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null, options); -}; - -DbCommand.createAdminDbCommand = function(db, command_hash) { - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT, 0, -1, command_hash, null); -}; - -DbCommand.createAdminDbCommandSlaveOk = function(db, command_hash) { - return new DbCommand(db, "admin." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null); -}; - -DbCommand.createDbSlaveOkCommand = function(db, command_hash, options) { - return new DbCommand(db, db.databaseName + "." + DbCommand.SYSTEM_COMMAND_COLLECTION, QueryCommand.OPTS_NO_CURSOR_TIMEOUT | QueryCommand.OPTS_SLAVE, 0, -1, command_hash, null, options); -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/delete_command.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/delete_command.js deleted file mode 100644 index c2765a7b9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/delete_command.js +++ /dev/null @@ -1,129 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var DeleteCommand = exports.DeleteCommand = function(db, collectionName, selector, flags) { - BaseCommand.call(this); - - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("delete raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.flags = flags; - this.collectionName = collectionName; - this.selector = selector; - this.db = db; -}; - -inherits(DeleteCommand, BaseCommand); - -DeleteCommand.OP_DELETE = 2006; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - int32 ZERO; // 0 - reserved for future use - mongo.BSON selector; // query object. See below for details. -} -*/ -DeleteCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.selector, false, true) + (4 * 4); - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (DeleteCommand.OP_DELETE >> 24) & 0xff; - _command[_index + 2] = (DeleteCommand.OP_DELETE >> 16) & 0xff; - _command[_index + 1] = (DeleteCommand.OP_DELETE >> 8) & 0xff; - _command[_index] = DeleteCommand.OP_DELETE & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the flags - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(this.selector)) { - documentLength = this.selector.length; - // Copy the data into the current buffer - this.selector.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(this.selector, this.checkKeys, _command, _index) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/get_more_command.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/get_more_command.js deleted file mode 100644 index 1b6b1727a..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/get_more_command.js +++ /dev/null @@ -1,88 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits, - binaryutils = require('../utils'); - -/** - Get More Document Command -**/ -var GetMoreCommand = exports.GetMoreCommand = function(db, collectionName, numberToReturn, cursorId) { - BaseCommand.call(this); - - this.collectionName = collectionName; - this.numberToReturn = numberToReturn; - this.cursorId = cursorId; - this.db = db; -}; - -inherits(GetMoreCommand, BaseCommand); - -GetMoreCommand.OP_GET_MORE = 2005; - -GetMoreCommand.prototype.toBinary = function() { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 8 + (4 * 4); - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index++] = totalLengthOfCommand & 0xff; - _command[_index++] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index++] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index++] = (totalLengthOfCommand >> 24) & 0xff; - - // Write the request ID - _command[_index++] = this.requestId & 0xff; - _command[_index++] = (this.requestId >> 8) & 0xff; - _command[_index++] = (this.requestId >> 16) & 0xff; - _command[_index++] = (this.requestId >> 24) & 0xff; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the op_code for the command - _command[_index++] = GetMoreCommand.OP_GET_MORE & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 8) & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 16) & 0xff; - _command[_index++] = (GetMoreCommand.OP_GET_MORE >> 24) & 0xff; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Number of documents to return - _command[_index++] = this.numberToReturn & 0xff; - _command[_index++] = (this.numberToReturn >> 8) & 0xff; - _command[_index++] = (this.numberToReturn >> 16) & 0xff; - _command[_index++] = (this.numberToReturn >> 24) & 0xff; - - // Encode the cursor id - var low_bits = this.cursorId.getLowBits(); - // Encode low bits - _command[_index++] = low_bits & 0xff; - _command[_index++] = (low_bits >> 8) & 0xff; - _command[_index++] = (low_bits >> 16) & 0xff; - _command[_index++] = (low_bits >> 24) & 0xff; - - var high_bits = this.cursorId.getHighBits(); - // Encode high bits - _command[_index++] = high_bits & 0xff; - _command[_index++] = (high_bits >> 8) & 0xff; - _command[_index++] = (high_bits >> 16) & 0xff; - _command[_index++] = (high_bits >> 24) & 0xff; - // Return command - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/insert_command.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/insert_command.js deleted file mode 100644 index c6e51e957..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/insert_command.js +++ /dev/null @@ -1,161 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var InsertCommand = exports.InsertCommand = function(db, collectionName, checkKeys, options) { - BaseCommand.call(this); - - this.collectionName = collectionName; - this.documents = []; - this.checkKeys = checkKeys == null ? true : checkKeys; - this.db = db; - this.flags = 0; - this.serializeFunctions = false; - - // Ensure valid options hash - options = options == null ? {} : options; - - // Check if we have keepGoing set -> set flag if it's the case - if(options['keepGoing'] != null && options['keepGoing']) { - // This will finish inserting all non-index violating documents even if it returns an error - this.flags = 1; - } - - // Check if we have keepGoing set -> set flag if it's the case - if(options['continueOnError'] != null && options['continueOnError']) { - // This will finish inserting all non-index violating documents even if it returns an error - this.flags = 1; - } - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(InsertCommand, BaseCommand); - -// OpCodes -InsertCommand.OP_INSERT = 2002; - -InsertCommand.prototype.add = function(document) { - if(Buffer.isBuffer(document)) { - var object_size = document[0] | document[1] << 8 | document[2] << 16 | document[3] << 24; - if(object_size != document.length) { - var error = new Error("insert raw message size does not match message header size [" + document.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.documents.push(document); - return this; -}; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - BSON[] documents; // one or more documents to insert into the collection -} -*/ -InsertCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + (4 * 4); - // var docLength = 0 - for(var i = 0; i < this.documents.length; i++) { - if(Buffer.isBuffer(this.documents[i])) { - totalLengthOfCommand += this.documents[i].length; - } else { - // Calculate size of document - totalLengthOfCommand += this.db.bson.calculateObjectSize(this.documents[i], this.serializeFunctions, true); - } - } - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (InsertCommand.OP_INSERT >> 24) & 0xff; - _command[_index + 2] = (InsertCommand.OP_INSERT >> 16) & 0xff; - _command[_index + 1] = (InsertCommand.OP_INSERT >> 8) & 0xff; - _command[_index] = InsertCommand.OP_INSERT & 0xff; - // Adjust index - _index = _index + 4; - // Write flags if any - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write all the bson documents to the buffer at the index offset - for(var i = 0; i < this.documents.length; i++) { - // Document binary length - var documentLength = 0 - var object = this.documents[i]; - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - // Serialize the document straight to the buffer - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - - return _command; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js deleted file mode 100644 index d8ccb0c3a..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/kill_cursor_command.js +++ /dev/null @@ -1,98 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits, - binaryutils = require('../utils'); - -/** - Insert Document Command -**/ -var KillCursorCommand = exports.KillCursorCommand = function(db, cursorIds) { - BaseCommand.call(this); - - this.cursorIds = cursorIds; - this.db = db; -}; - -inherits(KillCursorCommand, BaseCommand); - -KillCursorCommand.OP_KILL_CURSORS = 2007; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - int32 numberOfCursorIDs; // number of cursorIDs in message - int64[] cursorIDs; // array of cursorIDs to close -} -*/ -KillCursorCommand.prototype.toBinary = function() { - // Calculate total length of the document - var totalLengthOfCommand = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (KillCursorCommand.OP_KILL_CURSORS >> 24) & 0xff; - _command[_index + 2] = (KillCursorCommand.OP_KILL_CURSORS >> 16) & 0xff; - _command[_index + 1] = (KillCursorCommand.OP_KILL_CURSORS >> 8) & 0xff; - _command[_index] = KillCursorCommand.OP_KILL_CURSORS & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Number of cursors to kill - var numberOfCursors = this.cursorIds.length; - _command[_index + 3] = (numberOfCursors >> 24) & 0xff; - _command[_index + 2] = (numberOfCursors >> 16) & 0xff; - _command[_index + 1] = (numberOfCursors >> 8) & 0xff; - _command[_index] = numberOfCursors & 0xff; - // Adjust index - _index = _index + 4; - - // Encode all the cursors - for(var i = 0; i < this.cursorIds.length; i++) { - // Encode the cursor id - var low_bits = this.cursorIds[i].getLowBits(); - // Encode low bits - _command[_index + 3] = (low_bits >> 24) & 0xff; - _command[_index + 2] = (low_bits >> 16) & 0xff; - _command[_index + 1] = (low_bits >> 8) & 0xff; - _command[_index] = low_bits & 0xff; - // Adjust index - _index = _index + 4; - - var high_bits = this.cursorIds[i].getHighBits(); - // Encode high bits - _command[_index + 3] = (high_bits >> 24) & 0xff; - _command[_index + 2] = (high_bits >> 16) & 0xff; - _command[_index + 1] = (high_bits >> 8) & 0xff; - _command[_index] = high_bits & 0xff; - // Adjust index - _index = _index + 4; - } - - return _command; -}; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/query_command.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/query_command.js deleted file mode 100644 index 16045b88e..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/query_command.js +++ /dev/null @@ -1,280 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Insert Document Command -**/ -var QueryCommand = exports.QueryCommand = function(db, collectionName, queryOptions, numberToSkip, numberToReturn, query, returnFieldSelector, options) { - BaseCommand.call(this); - - // Validate correctness off the selector - var object = query, - object_size; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - object = returnFieldSelector; - if(Buffer.isBuffer(object)) { - object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Make sure we don't get a null exception - options = options == null ? {} : options; - // Set up options - this.collectionName = collectionName; - this.queryOptions = queryOptions; - this.numberToSkip = numberToSkip; - this.numberToReturn = numberToReturn; - - // Ensure we have no null query - query = query == null ? {} : query; - // Wrap query in the $query parameter so we can add read preferences for mongos - this.query = query; - this.returnFieldSelector = returnFieldSelector; - this.db = db; - - // Force the slave ok flag to be set if we are not using primary read preference - if(this.db && this.db.slaveOk) { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(QueryCommand, BaseCommand); - -QueryCommand.OP_QUERY = 2004; - -/* - * Adds the read prefrence to the current command - */ -QueryCommand.prototype.setMongosReadPreference = function(readPreference, tags) { - // If we have readPreference set to true set to secondary prefered - if(readPreference == true) { - readPreference = 'secondaryPreferred'; - } else if(readPreference == 'false') { - readPreference = 'primary'; - } - - // Force the slave ok flag to be set if we are not using primary read preference - if(readPreference != false && readPreference != 'primary') { - this.queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Backward compatibility, ensure $query only set on read preference so 1.8.X works - if((readPreference != null || tags != null) && this.query['$query'] == null) { - this.query = {'$query': this.query}; - } - - // If we have no readPreference set and no tags, check if the slaveOk bit is set - if(readPreference == null && tags == null) { - // If we have a slaveOk bit set the read preference for MongoS - if(this.queryOptions & QueryCommand.OPTS_SLAVE) { - this.query['$readPreference'] = {mode: 'secondary'} - } else { - this.query['$readPreference'] = {mode: 'primary'} - } - } - - // Build read preference object - if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') { - this.query['$readPreference'] = readPreference.toObject(); - } else if(readPreference != null) { - // Add the read preference - this.query['$readPreference'] = {mode: readPreference}; - - // If we have tags let's add them - if(tags != null) { - this.query['$readPreference']['tags'] = tags; - } - } -} - -/* -struct { - MsgHeader header; // standard message header - int32 opts; // query options. See below for details. - cstring fullCollectionName; // "dbname.collectionname" - int32 numberToSkip; // number of documents to skip when returning results - int32 numberToReturn; // number of documents to return in the first OP_REPLY - BSON query ; // query object. See below for details. - [ BSON returnFieldSelector; ] // OPTIONAL : selector indicating the fields to return. See below for details. -} -*/ -QueryCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Total length of the command - var totalLengthOfCommand = 0; - // Calculate total length of the document - if(Buffer.isBuffer(this.query)) { - totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.query.length + (4 * 4); - } else { - totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + 4 + this.db.bson.calculateObjectSize(this.query, this.serializeFunctions, true) + (4 * 4); - } - - // Calculate extra fields size - if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) { - if(Object.keys(this.returnFieldSelector).length > 0) { - totalLengthOfCommand += this.db.bson.calculateObjectSize(this.returnFieldSelector, this.serializeFunctions, true); - } - } else if(Buffer.isBuffer(this.returnFieldSelector)) { - totalLengthOfCommand += this.returnFieldSelector.length; - } - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (QueryCommand.OP_QUERY >> 24) & 0xff; - _command[_index + 2] = (QueryCommand.OP_QUERY >> 16) & 0xff; - _command[_index + 1] = (QueryCommand.OP_QUERY >> 8) & 0xff; - _command[_index] = QueryCommand.OP_QUERY & 0xff; - // Adjust index - _index = _index + 4; - - // Write the query options - _command[_index + 3] = (this.queryOptions >> 24) & 0xff; - _command[_index + 2] = (this.queryOptions >> 16) & 0xff; - _command[_index + 1] = (this.queryOptions >> 8) & 0xff; - _command[_index] = this.queryOptions & 0xff; - // Adjust index - _index = _index + 4; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the number of documents to skip - _command[_index + 3] = (this.numberToSkip >> 24) & 0xff; - _command[_index + 2] = (this.numberToSkip >> 16) & 0xff; - _command[_index + 1] = (this.numberToSkip >> 8) & 0xff; - _command[_index] = this.numberToSkip & 0xff; - // Adjust index - _index = _index + 4; - - // Write the number of documents to return - _command[_index + 3] = (this.numberToReturn >> 24) & 0xff; - _command[_index + 2] = (this.numberToReturn >> 16) & 0xff; - _command[_index + 1] = (this.numberToReturn >> 8) & 0xff; - _command[_index] = this.numberToReturn & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - var object = this.query; - - // Serialize the selector - if(Buffer.isBuffer(object)) { - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - // Serialize the document straight to the buffer - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - // Push field selector if available - if(this.returnFieldSelector != null && !(Buffer.isBuffer(this.returnFieldSelector))) { - if(Object.keys(this.returnFieldSelector).length > 0) { - var documentLength = this.db.bson.serializeWithBufferAndIndex(this.returnFieldSelector, this.checkKeys, _command, _index, this.serializeFunctions) - _index + 1; - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - } if(this.returnFieldSelector != null && Buffer.isBuffer(this.returnFieldSelector)) { - // Document binary length - var documentLength = 0 - var object = this.returnFieldSelector; - - // Serialize the selector - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - } - - // Return finished command - return _command; -}; - -// Constants -QueryCommand.OPTS_NONE = 0; -QueryCommand.OPTS_TAILABLE_CURSOR = 2; -QueryCommand.OPTS_SLAVE = 4; -QueryCommand.OPTS_OPLOG_REPLY = 8; -QueryCommand.OPTS_NO_CURSOR_TIMEOUT = 16; -QueryCommand.OPTS_AWAIT_DATA = 32; -QueryCommand.OPTS_EXHAUST = 64; -QueryCommand.OPTS_PARTIAL = 128; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/update_command.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/update_command.js deleted file mode 100644 index daa3cba48..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/commands/update_command.js +++ /dev/null @@ -1,189 +0,0 @@ -var BaseCommand = require('./base_command').BaseCommand, - inherits = require('util').inherits; - -/** - Update Document Command -**/ -var UpdateCommand = exports.UpdateCommand = function(db, collectionName, spec, document, options) { - BaseCommand.call(this); - - var object = spec; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("update spec raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - var object = document; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("update document raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - this.collectionName = collectionName; - this.spec = spec; - this.document = document; - this.db = db; - this.serializeFunctions = false; - this.checkKeys = typeof options.checkKeys != 'boolean' ? false : options.checkKeys; - - // Generate correct flags - var db_upsert = 0; - var db_multi_update = 0; - db_upsert = options != null && options['upsert'] != null ? (options['upsert'] == true ? 1 : 0) : db_upsert; - db_multi_update = options != null && options['multi'] != null ? (options['multi'] == true ? 1 : 0) : db_multi_update; - - // Flags - this.flags = parseInt(db_multi_update.toString() + db_upsert.toString(), 2); - // Let us defined on a command basis if we want functions to be serialized or not - if(options['serializeFunctions'] != null && options['serializeFunctions']) { - this.serializeFunctions = true; - } -}; - -inherits(UpdateCommand, BaseCommand); - -UpdateCommand.OP_UPDATE = 2001; - -/* -struct { - MsgHeader header; // standard message header - int32 ZERO; // 0 - reserved for future use - cstring fullCollectionName; // "dbname.collectionname" - int32 flags; // bit vector. see below - BSON spec; // the query to select the document - BSON document; // the document data to update with or insert -} -*/ -UpdateCommand.prototype.toBinary = function(bsonSettings) { - // Validate that we are not passing 0x00 in the colletion name - if(!!~this.collectionName.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Calculate total length of the document - var totalLengthOfCommand = 4 + Buffer.byteLength(this.collectionName) + 1 + 4 + this.db.bson.calculateObjectSize(this.spec, false, true) + - this.db.bson.calculateObjectSize(this.document, this.serializeFunctions, true) + (4 * 4); - - // Enforce maximum bson size - if(!bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxBsonSize) - throw new Error("Document exceeds maximum allowed bson size of " + bsonSettings.maxBsonSize + " bytes"); - - if(bsonSettings.disableDriverBSONSizeCheck - && totalLengthOfCommand > bsonSettings.maxMessageSizeBytes) - throw new Error("Command exceeds maximum message size of " + bsonSettings.maxMessageSizeBytes + " bytes"); - - // Let's build the single pass buffer command - var _index = 0; - var _command = new Buffer(totalLengthOfCommand); - // Write the header information to the buffer - _command[_index + 3] = (totalLengthOfCommand >> 24) & 0xff; - _command[_index + 2] = (totalLengthOfCommand >> 16) & 0xff; - _command[_index + 1] = (totalLengthOfCommand >> 8) & 0xff; - _command[_index] = totalLengthOfCommand & 0xff; - // Adjust index - _index = _index + 4; - // Write the request ID - _command[_index + 3] = (this.requestId >> 24) & 0xff; - _command[_index + 2] = (this.requestId >> 16) & 0xff; - _command[_index + 1] = (this.requestId >> 8) & 0xff; - _command[_index] = this.requestId & 0xff; - // Adjust index - _index = _index + 4; - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - // Write the op_code for the command - _command[_index + 3] = (UpdateCommand.OP_UPDATE >> 24) & 0xff; - _command[_index + 2] = (UpdateCommand.OP_UPDATE >> 16) & 0xff; - _command[_index + 1] = (UpdateCommand.OP_UPDATE >> 8) & 0xff; - _command[_index] = UpdateCommand.OP_UPDATE & 0xff; - // Adjust index - _index = _index + 4; - - // Write zero - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - _command[_index++] = 0; - - // Write the collection name to the command - _index = _index + _command.write(this.collectionName, _index, 'utf8') + 1; - _command[_index - 1] = 0; - - // Write the update flags - _command[_index + 3] = (this.flags >> 24) & 0xff; - _command[_index + 2] = (this.flags >> 16) & 0xff; - _command[_index + 1] = (this.flags >> 8) & 0xff; - _command[_index] = this.flags & 0xff; - // Adjust index - _index = _index + 4; - - // Document binary length - var documentLength = 0 - var object = this.spec; - - // Serialize the selector - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(object, this.checkKeys, _command, _index, false) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - // Document binary length - var documentLength = 0 - var object = this.document; - - // Serialize the document - // If we are passing a raw buffer, do minimal validation - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) throw new Error("raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - documentLength = object.length; - // Copy the data into the current buffer - object.copy(_command, _index); - } else { - documentLength = this.db.bson.serializeWithBufferAndIndex(object, false, _command, _index, this.serializeFunctions) - _index + 1; - } - - // Write the length to the document - _command[_index + 3] = (documentLength >> 24) & 0xff; - _command[_index + 2] = (documentLength >> 16) & 0xff; - _command[_index + 1] = (documentLength >> 8) & 0xff; - _command[_index] = documentLength & 0xff; - // Update index in buffer - _index = _index + documentLength; - // Add terminating 0 for the object - _command[_index - 1] = 0; - - return _command; -}; - -// Constants -UpdateCommand.DB_UPSERT = 0; -UpdateCommand.DB_MULTI_UPDATE = 1; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/base.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/base.js deleted file mode 100644 index 30cdc5f5c..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/base.js +++ /dev/null @@ -1,442 +0,0 @@ -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , mongodb_cr_authenticate = require('../auth/mongodb_cr.js').authenticate - , mongodb_gssapi_authenticate = require('../auth/mongodb_gssapi.js').authenticate - , mongodb_sspi_authenticate = require('../auth/mongodb_sspi.js').authenticate; - -var id = 0; - -/** - * Internal class for callback storage - * @ignore - */ -var CallbackStore = function() { - // Make class an event emitter - EventEmitter.call(this); - // Add a info about call variable - this._notReplied = {}; - this.id = id++; -} - -/** - * @ignore - */ -inherits(CallbackStore, EventEmitter); - -CallbackStore.prototype.notRepliedToIds = function() { - return Object.keys(this._notReplied); -} - -CallbackStore.prototype.callbackInfo = function(id) { - return this._notReplied[id]; -} - -/** - * Internal class for holding non-executed commands - * @ignore - */ -var NonExecutedOperationStore = function(config) { - this.config = config; - this.commands = { - read: [] - , write_reads: [] - , write: [] - }; -} - -NonExecutedOperationStore.prototype.write = function(op) { - this.commands.write.push(op); -} - -NonExecutedOperationStore.prototype.read_from_writer = function(op) { - this.commands.write_reads.push(op); -} - -NonExecutedOperationStore.prototype.read = function(op) { - this.commands.read.push(op); -} - -NonExecutedOperationStore.prototype.execute_queries = function(executeInsertCommand) { - var connection = this.config.checkoutReader(); - if(connection == null || connection instanceof Error) return; - - // Write out all the queries - while(this.commands.read.length > 0) { - // Get the next command - var command = this.commands.read.shift(); - command.options.connection = connection; - // Execute the next command - command.executeQueryCommand(command.db, command.db_command, command.options, command.callback); - } -} - -NonExecutedOperationStore.prototype.execute_writes = function() { - var connection = this.config.checkoutWriter(); - if(connection == null || connection instanceof Error) return; - - // Write out all the queries to the primary - while(this.commands.write_reads.length > 0) { - // Get the next command - var command = this.commands.write_reads.shift(); - command.options.connection = connection; - // Execute the next command - command.executeQueryCommand(command.db, command.db_command, command.options, command.callback); - } - - // Execute all write operations - while(this.commands.write.length > 0) { - // Get the next command - var command = this.commands.write.shift(); - // Set the connection - command.options.connection = connection; - // Execute the next command - command.executeInsertCommand(command.db, command.db_command, command.options, command.callback); - } -} - -/** - * Internal class for authentication storage - * @ignore - */ -var AuthStore = function() { - this._auths = []; -} - -AuthStore.prototype.add = function(authMechanism, dbName, username, password, authdbName, gssapiServiceName) { - // Check for duplicates - if(!this.contains(dbName)) { - // Base config - var config = { - 'username':username - , 'password':password - , 'db': dbName - , 'authMechanism': authMechanism - , 'gssapiServiceName': gssapiServiceName - }; - - // Add auth source if passed in - if(typeof authdbName == 'string') { - config['authdb'] = authdbName; - } - - // Push the config - this._auths.push(config); - } -} - -AuthStore.prototype.contains = function(dbName) { - for(var i = 0; i < this._auths.length; i++) { - if(this._auths[i].db == dbName) return true; - } - - return false; -} - -AuthStore.prototype.remove = function(dbName) { - var newAuths = []; - - // Filter out all the login details - for(var i = 0; i < this._auths.length; i++) { - if(this._auths[i].db != dbName) newAuths.push(this._auths[i]); - } - - // Set the filtered list - this._auths = newAuths; -} - -AuthStore.prototype.get = function(index) { - return this._auths[index]; -} - -AuthStore.prototype.length = function() { - return this._auths.length; -} - -AuthStore.prototype.toArray = function() { - return this._auths.slice(0); -} - -/** - * Internal class for storing db references - * @ignore - */ -var DbStore = function() { - this._dbs = []; -} - -DbStore.prototype.add = function(db) { - var found = false; - - // Only add if it does not exist already - for(var i = 0; i < this._dbs.length; i++) { - if(db.databaseName == this._dbs[i].databaseName) found = true; - } - - // Only add if it does not already exist - if(!found) { - this._dbs.push(db); - } -} - -DbStore.prototype.reset = function() { - this._dbs = []; -} - -DbStore.prototype.fetch = function(databaseName) { - // Only add if it does not exist already - for(var i = 0; i < this._dbs.length; i++) { - if(databaseName == this._dbs[i].databaseName) - return this._dbs[i]; - } - - return null; -} - -DbStore.prototype.emit = function(event, message, object, reset, filterDb, rethrow_if_no_listeners) { - var emitted = false; - - // Emit the events - for(var i = 0; i < this._dbs.length; i++) { - if(this._dbs[i].listeners(event).length > 0) { - if(filterDb == null || filterDb.databaseName !== this._dbs[i].databaseName - || filterDb.tag !== this._dbs[i].tag) { - this._dbs[i].emit(event, message, object == null ? this._dbs[i] : object); - emitted = true; - } - } - } - - // Emit error message - if(message - && event == 'error' - && !emitted - && rethrow_if_no_listeners - && object && object.db) { - process.nextTick(function() { - object.db.emit(event, message, null); - }) - } - - // Not emitted and we have enabled rethrow, let process.uncaughtException - // deal with the issue - if(!emitted && rethrow_if_no_listeners) { - throw message; - } -} - -var Base = function Base() { - EventEmitter.call(this); - - // Callback store is part of connection specification - if(Base._callBackStore == null) { - Base._callBackStore = new CallbackStore(); - } - - // Create a new callback store - this._callBackStore = new CallbackStore(); - // All commands not being executed - this._commandsStore = new NonExecutedOperationStore(this); - // Create a new auth store - this.auth = new AuthStore(); - // Contains all the dbs attached to this server config - this._dbStore = new DbStore(); -} - -/** - * @ignore - */ -inherits(Base, EventEmitter); - -/** - * @ignore - */ -Base.prototype._apply_auths = function(db, callback) { - _apply_auths_serially(this, db, this.auth.toArray(), callback); -} - -var _apply_auths_serially = function(self, db, auths, callback) { - if(auths.length == 0) return callback(null, null); - // Get the first auth - var auth = auths.shift(); - var connections = self.allRawConnections(); - var connectionsLeft = connections.length; - var options = {}; - - if(auth.authMechanism == 'GSSAPI') { - // We have the kerberos library, execute auth process - if(process.platform == 'win32') { - mongodb_sspi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } else { - mongodb_gssapi_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } - } else if(auth.authMechanism == 'MONGODB-CR') { - mongodb_cr_authenticate(db, auth.username, auth.password, auth.authdb, options, callback); - } -} - -/** - * Fire all the errors - * @ignore - */ -Base.prototype.__executeAllCallbacksWithError = function(err) { - // Check all callbacks - var keys = Object.keys(this._callBackStore._notReplied); - // For each key check if it's a callback that needs to be returned - for(var j = 0; j < keys.length; j++) { - var info = this._callBackStore._notReplied[keys[j]]; - // Execute callback with error - this._callBackStore.emit(keys[j], err, null); - // Remove the key - delete this._callBackStore._notReplied[keys[j]]; - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[keys[j]]; - } - } -} - -/** - * Fire all the errors - * @ignore - */ -Base.prototype.__executeAllServerSpecificErrorCallbacks = function(host, port, err) { - // Check all callbacks - var keys = Object.keys(this._callBackStore._notReplied); - // For each key check if it's a callback that needs to be returned - for(var j = 0; j < keys.length; j++) { - var info = this._callBackStore._notReplied[keys[j]]; - - if(info.connection) { - // Unpack the connection settings - var _host = info.connection.socketOptions.host; - var _port = info.connection.socketOptions.port; - // If the server matches execute the callback with the error - if(_port == port && _host == host) { - this._callBackStore.emit(keys[j], err, null); - // Remove the key - delete this._callBackStore._notReplied[keys[j]]; - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[keys[j]]; - } - } - } - } -} - -/** - * Register a handler - * @ignore - * @api private - */ -Base.prototype._registerHandler = function(db_command, raw, connection, exhaust, callback) { - // Check if we have exhausted - if(typeof exhaust == 'function') { - callback = exhaust; - exhaust = false; - } - - // Add the callback to the list of handlers - this._callBackStore.once(db_command.getRequestId(), callback); - // Add the information about the reply - this._callBackStore._notReplied[db_command.getRequestId().toString()] = {start: new Date().getTime(), 'raw': raw, connection:connection, exhaust:exhaust}; -} - -/** - * Re-Register a handler, on the cursor id f.ex - * @ignore - * @api private - */ -Base.prototype._reRegisterHandler = function(newId, object, callback) { - // Add the callback to the list of handlers - this._callBackStore.once(newId, object.callback.listener); - // Add the information about the reply - this._callBackStore._notReplied[newId] = object.info; -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._callHandler = function(id, document, err) { - var self = this; - - // If there is a callback peform it - if(this._callBackStore.listeners(id).length >= 1) { - // Get info object - var info = this._callBackStore._notReplied[id]; - // Delete the current object - delete this._callBackStore._notReplied[id]; - // Call the handle directly don't emit - var callback = this._callBackStore.listeners(id)[0].listener; - // Remove the listeners - this._callBackStore.removeAllListeners(id); - // Force key deletion because it nulling it not deleting in 0.10.X - if(this._callBackStore._events) { - delete this._callBackStore._events[id]; - } - - try { - // Execute the callback if one was provided - if(typeof callback == 'function') callback(err, document, info.connection); - } catch(err) { - self._emitAcrossAllDbInstances(self, null, "error", err, self, true, true); - } - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._hasHandler = function(id) { - return this._callBackStore.listeners(id).length >= 1; -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._removeHandler = function(id) { - // Remove the information - if(this._callBackStore._notReplied[id] != null) delete this._callBackStore._notReplied[id]; - // Remove the callback if it's registered - this._callBackStore.removeAllListeners(id); - // Force cleanup _events, node.js seems to set it as a null value - if(this._callBackStore._events) { - delete this._callBackStore._events[id]; - } -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._findHandler = function(id) { - var info = this._callBackStore._notReplied[id]; - // Return the callback - return {info:info, callback:(this._callBackStore.listeners(id).length >= 1) ? this._callBackStore.listeners(id)[0] : null} -} - -/** - * - * @ignore - * @api private - */ -Base.prototype._emitAcrossAllDbInstances = function(server, filterDb, event, message, object, resetConnection, rethrow_if_no_listeners) { - if(resetConnection) { - for(var i = 0; i < this._dbStore._dbs.length; i++) { - if(typeof this._dbStore._dbs[i].openCalled != 'undefined') - this._dbStore._dbs[i].openCalled = false; - } - } - - // Fire event - this._dbStore.emit(event, message, object, resetConnection, filterDb, rethrow_if_no_listeners); -} - -exports.Base = Base; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection.js deleted file mode 100644 index 8f4d4c0ee..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection.js +++ /dev/null @@ -1,507 +0,0 @@ -var utils = require('./connection_utils'), - inherits = require('util').inherits, - net = require('net'), - EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits, - binaryutils = require('../utils'), - tls = require('tls'); - -var Connection = exports.Connection = function(id, socketOptions) { - // Set up event emitter - EventEmitter.call(this); - // Store all socket options - this.socketOptions = socketOptions ? socketOptions : {host:'localhost', port:27017, domainSocket:false}; - // Set keep alive default if not overriden - if(this.socketOptions.keepAlive == null && (process.platform !== "sunos" || process.platform !== "win32")) this.socketOptions.keepAlive = 100; - // Id for the connection - this.id = id; - // State of the connection - this.connected = false; - // Set if this is a domain socket - this.domainSocket = this.socketOptions.domainSocket; - - // - // Connection parsing state - // - this.maxBsonSize = socketOptions.maxBsonSize ? socketOptions.maxBsonSize : Connection.DEFAULT_MAX_BSON_SIZE; - this.maxMessageSizeBytes = socketOptions.maxMessageSizeBytes ? socketOptions.maxMessageSizeBytes : Connection.DEFAULT_MAX_MESSAGE_SIZE; - // Contains the current message bytes - this.buffer = null; - // Contains the current message size - this.sizeOfMessage = 0; - // Contains the readIndex for the messaage - this.bytesRead = 0; - // Contains spill over bytes from additional messages - this.stubBuffer = 0; - - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[], end:[]}; - - // Just keeps list of events we allow - resetHandlers(this, false); - // Bson object - this.maxBsonSettings = { - disableDriverBSONSizeCheck: this.socketOptions['disableDriverBSONSizeCheck'] || false - , maxBsonSize: this.maxBsonSize - , maxMessageSizeBytes: this.maxMessageSizeBytes - } -} - -// Set max bson size -Connection.DEFAULT_MAX_BSON_SIZE = 1024 * 1024 * 4; -// Set default to max bson to avoid overflow or bad guesses -Connection.DEFAULT_MAX_MESSAGE_SIZE = Connection.DEFAULT_MAX_BSON_SIZE; - -// Inherit event emitter so we can emit stuff wohoo -inherits(Connection, EventEmitter); - -Connection.prototype.start = function() { - var self = this; - - // If we have a normal connection - if(this.socketOptions.ssl) { - // Create new connection instance - if(this.domainSocket) { - this.connection = net.createConnection(this.socketOptions.host); - } else { - this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host); - } - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("opened connection", this.socketOptions); - } - // Set options on the socket - this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout); - // Work around for 0.4.X - if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay); - // Set keep alive if defined - if(process.version.indexOf("v0.4") == -1) { - if(this.socketOptions.keepAlive > 0) { - this.connection.setKeepAlive(true, this.socketOptions.keepAlive); - } else { - this.connection.setKeepAlive(false); - } - } - - // Check if the driver should validate the certificate - var validate_certificates = this.socketOptions.sslValidate == true ? true : false; - - // Create options for the tls connection - var tls_options = { - socket: this.connection - , rejectUnauthorized: false - } - - // If we wish to validate the certificate we have provided a ca store - if(validate_certificates) { - tls_options.ca = this.socketOptions.sslCA; - } - - // If we have a certificate to present - if(this.socketOptions.sslCert) { - tls_options.cert = this.socketOptions.sslCert; - tls_options.key = this.socketOptions.sslKey; - } - - // If the driver has been provided a private key password - if(this.socketOptions.sslPass) { - tls_options.passphrase = this.socketOptions.sslPass; - } - - // Contains the cleartext stream - var cleartext = null; - // Attempt to establish a TLS connection to the server - try { - cleartext = tls.connect(this.socketOptions.port, this.socketOptions.host, tls_options, function() { - // If we have a ssl certificate validation error return an error - if(cleartext.authorizationError && validate_certificates) { - // Emit an error - return self.emit("error", cleartext.authorizationError, self, {ssl:true}); - } - - // Connect to the server - connectHandler(self)(); - }) - } catch(err) { - return self.emit("error", "SSL connection failed", self, {ssl:true}); - } - - // Save the output stream - this.writeSteam = cleartext; - - // Set up data handler for the clear stream - cleartext.on("data", createDataHandler(this)); - // Do any handling of end event of the stream - cleartext.on("end", endHandler(this)); - cleartext.on("error", errorHandler(this)); - - // Handle any errors - this.connection.on("error", errorHandler(this)); - // Handle timeout - this.connection.on("timeout", timeoutHandler(this)); - // Handle drain event - this.connection.on("drain", drainHandler(this)); - // Handle the close event - this.connection.on("close", closeHandler(this)); - } else { - // Create new connection instance - if(this.domainSocket) { - this.connection = net.createConnection(this.socketOptions.host); - } else { - this.connection = net.createConnection(this.socketOptions.port, this.socketOptions.host); - } - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("opened connection", this.socketOptions); - } - - // Set options on the socket - this.connection.setTimeout(this.socketOptions.connectTimeoutMS != null ? this.socketOptions.connectTimeoutMS : this.socketOptions.timeout); - // Work around for 0.4.X - if(process.version.indexOf("v0.4") == -1) this.connection.setNoDelay(this.socketOptions.noDelay); - // Set keep alive if defined - if(process.version.indexOf("v0.4") == -1) { - if(this.socketOptions.keepAlive > 0) { - this.connection.setKeepAlive(true, this.socketOptions.keepAlive); - } else { - this.connection.setKeepAlive(false); - } - } - - // Set up write stream - this.writeSteam = this.connection; - // Add handlers - this.connection.on("error", errorHandler(this)); - // Add all handlers to the socket to manage it - this.connection.on("connect", connectHandler(this)); - // this.connection.on("end", endHandler(this)); - this.connection.on("data", createDataHandler(this)); - this.connection.on("timeout", timeoutHandler(this)); - this.connection.on("drain", drainHandler(this)); - this.connection.on("close", closeHandler(this)); - } -} - -// Check if the sockets are live -Connection.prototype.isConnected = function() { - return this.connected && !this.connection.destroyed && this.connection.writable && this.connection.readable; -} - -// Write the data out to the socket -Connection.prototype.write = function(command, callback) { - try { - // If we have a list off commands to be executed on the same socket - if(Array.isArray(command)) { - for(var i = 0; i < command.length; i++) { - try { - // Pass in the bson validation settings (validate early) - var binaryCommand = command[i].toBinary(this.maxBsonSettings) - - if(this.logger != null && this.logger.doDebug) - this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]}); - - this.writeSteam.write(binaryCommand); - } catch(err) { - return callback(err, null); - } - } - } else { - try { - // Pass in the bson validation settings (validate early) - var binaryCommand = command.toBinary(this.maxBsonSettings) - - if(this.logger != null && this.logger.doDebug) - this.logger.debug("writing command to mongodb", {binary: binaryCommand, json: command[i]}); - - this.writeSteam.write(binaryCommand); - } catch(err) { - return callback(err, null) - } - } - } catch (err) { - if(typeof callback === 'function') callback(err); - } -} - -// Force the closure of the connection -Connection.prototype.close = function() { - // clear out all the listeners - resetHandlers(this, true); - // Add a dummy error listener to catch any weird last moment errors (and ignore them) - this.connection.on("error", function() {}) - // destroy connection - this.connection.destroy(); - if(this.logger != null && this.logger.doDebug){ - this.logger.debug("closed connection", this.connection); - } -} - -// Reset all handlers -var resetHandlers = function(self, clearListeners) { - self.eventHandlers = {error:[], connect:[], close:[], end:[], timeout:[], parseError:[], message:[]}; - - // If we want to clear all the listeners - if(clearListeners && self.connection != null) { - var keys = Object.keys(self.eventHandlers); - // Remove all listeners - for(var i = 0; i < keys.length; i++) { - self.connection.removeAllListeners(keys[i]); - } - } -} - -// -// Handlers -// - -// Connect handler -var connectHandler = function(self) { - return function(data) { - // Set connected - self.connected = true; - // Now that we are connected set the socket timeout - self.connection.setTimeout(self.socketOptions.socketTimeoutMS != null ? self.socketOptions.socketTimeoutMS : self.socketOptions.timeout); - // Emit the connect event with no error - self.emit("connect", null, self); - } -} - -var createDataHandler = exports.Connection.createDataHandler = function(self) { - // We need to handle the parsing of the data - // and emit the messages when there is a complete one - return function(data) { - // Parse until we are done with the data - while(data.length > 0) { - // If we still have bytes to read on the current message - if(self.bytesRead > 0 && self.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; - // Check if the current chunk contains the rest of the message - if(remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(self.buffer, self.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - self.bytesRead = self.bytesRead + data.length; - - // Reset state of buffer - data = new Buffer(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - try { - var emitBuffer = self.buffer; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Emit the buffer - self.emit("message", emitBuffer, self); - } catch(err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if(self.stubBuffer != null && self.stubBuffer.length > 0) { - - // If we have enough bytes to determine the message size let's do it - if(self.stubBuffer.length + data.length > 4) { - // Prepad the data - var newData = new Buffer(self.stubBuffer.length + data.length); - self.stubBuffer.copy(newData, 0); - data.copy(newData, self.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - - } else { - - // Add the the bytes to the stub buffer - var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); - // Copy existing stub buffer - self.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, self.stubBuffer.length); - // Exit parsing loop - data = new Buffer(0); - } - } else { - if(data.length > 4) { - // Retrieve the message size - var sizeOfMessage = binaryutils.decodeUInt32(data, 0); - // If we have a negative sizeOfMessage emit error and return - if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonSize) { - var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ - sizeOfMessage: sizeOfMessage, - bytesRead: self.bytesRead, - stubBuffer: self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage > data.length) { - self.buffer = new Buffer(sizeOfMessage); - // Copy all the data into the buffer - data.copy(self.buffer, 0); - // Update bytes read - self.bytesRead = data.length; - // Update sizeOfMessage - self.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonSize && sizeOfMessage == data.length) { - try { - var emitBuffer = data; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - // Emit the message - self.emit("message", emitBuffer, self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonSize) { - var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:0, - buffer:null, - stubBuffer:null}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - - // Clear out the state of the parser - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else { - try { - var emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - self.emit("message", emitBuffer, self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - if(self.logger != null && self.logger.doError) self.logger.error("parseError", errorObject); - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - - } - } else { - // Create a buffer that contains the space for the non-complete message - self.stubBuffer = new Buffer(data.length) - // Copy the data to the stub buffer - data.copy(self.stubBuffer, 0); - // Exit parsing loop - data = new Buffer(0); - } - } - } - } - } -} - -var endHandler = function(self) { - return function() { - // Set connected to false - self.connected = false; - // Emit end event - self.emit("end", {err: 'connection received Fin packet from [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } -} - -var timeoutHandler = function(self) { - return function() { - // Set connected to false - self.connected = false; - // Emit timeout event - self.emit("timeout", {err: 'connection to [' + self.socketOptions.host + ':' + self.socketOptions.port + '] timed out'}, self); - } -} - -var drainHandler = function(self) { - return function() { - } -} - -var errorHandler = function(self) { - return function(err) { - self.connection.destroy(); - // Set connected to false - self.connected = false; - // Emit error - self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } -} - -var closeHandler = function(self) { - return function(hadError) { - // If we have an error during the connection phase - if(hadError && !self.connected) { - // Set disconnected - self.connected = false; - // Emit error - self.emit("error", {err: 'failed to connect to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } else { - // Set disconnected - self.connected = false; - // Emit close - self.emit("close", {err: 'connection closed to [' + self.socketOptions.host + ':' + self.socketOptions.port + ']'}, self); - } - } -} - -// Some basic defaults -Connection.DEFAULT_PORT = 27017; - - - - - - - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection_pool.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection_pool.js deleted file mode 100644 index 3d9e7c5dd..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection_pool.js +++ /dev/null @@ -1,295 +0,0 @@ -var utils = require('./connection_utils'), - inherits = require('util').inherits, - net = require('net'), - timers = require('timers'), - EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits, - MongoReply = require("../responses/mongo_reply").MongoReply, - Connection = require("./connection").Connection; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -var ConnectionPool = exports.ConnectionPool = function(host, port, poolSize, bson, socketOptions) { - if(typeof host !== 'string') { - throw new Error("host must be specified [" + host + "]"); - } - - // Set up event emitter - EventEmitter.call(this); - - // Keep all options for the socket in a specific collection allowing the user to specify the - // Wished upon socket connection parameters - this.socketOptions = typeof socketOptions === 'object' ? socketOptions : {}; - this.socketOptions.host = host; - this.socketOptions.port = port; - this.socketOptions.domainSocket = false; - this.bson = bson; - // PoolSize is always + 1 for special reserved "measurment" socket (like ping, stats etc) - this.poolSize = poolSize; - this.minPoolSize = Math.floor(this.poolSize / 2) + 1; - - // Check if the host is a socket - if(host.match(/^\//)) { - this.socketOptions.domainSocket = true; - } else if(typeof port === 'string') { - try { - port = parseInt(port, 10); - } catch(err) { - new Error("port must be specified or valid integer[" + port + "]"); - } - } else if(typeof port !== 'number') { - throw new Error("port must be specified [" + port + "]"); - } - - // Set default settings for the socket options - utils.setIntegerParameter(this.socketOptions, 'timeout', 0); - // Delay before writing out the data to the server - utils.setBooleanParameter(this.socketOptions, 'noDelay', true); - // Delay before writing out the data to the server - utils.setIntegerParameter(this.socketOptions, 'keepAlive', 0); - // Set the encoding of the data read, default is binary == null - utils.setStringParameter(this.socketOptions, 'encoding', null); - // Allows you to set a throttling bufferSize if you need to stop overflows - utils.setIntegerParameter(this.socketOptions, 'bufferSize', 0); - - // Internal structures - this.openConnections = []; - // Assign connection id's - this.connectionId = 0; - - // Current index for selection of pool connection - this.currentConnectionIndex = 0; - // The pool state - this._poolState = 'disconnected'; - // timeout control - this._timeout = false; - // Time to wait between connections for the pool - this._timeToWait = 10; -} - -inherits(ConnectionPool, EventEmitter); - -ConnectionPool.prototype.setMaxBsonSize = function(maxBsonSize) { - if(maxBsonSize == null){ - maxBsonSize = Connection.DEFAULT_MAX_BSON_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxBsonSize = maxBsonSize; - this.openConnections[i].maxBsonSettings.maxBsonSize = maxBsonSize; - } -} - -ConnectionPool.prototype.setMaxMessageSizeBytes = function(maxMessageSizeBytes) { - if(maxMessageSizeBytes == null){ - maxMessageSizeBytes = Connection.DEFAULT_MAX_MESSAGE_SIZE; - } - - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].maxMessageSizeBytes = maxMessageSizeBytes; - this.openConnections[i].maxBsonSettings.maxMessageSizeBytes = maxMessageSizeBytes; - } -} - -// Start a function -var _connect = function(_self) { - // return new function() { - // Create a new connection instance - var connection = new Connection(_self.connectionId++, _self.socketOptions); - // Set logger on pool - connection.logger = _self.logger; - // Connect handler - connection.on("connect", function(err, connection) { - // Add connection to list of open connections - _self.openConnections.push(connection); - // If the number of open connections is equal to the poolSize signal ready pool - if(_self.openConnections.length === _self.poolSize && _self._poolState !== 'disconnected') { - // Set connected - _self._poolState = 'connected'; - // Emit pool ready - _self.emit("poolReady"); - } else if(_self.openConnections.length < _self.poolSize) { - // Wait a little bit of time to let the close event happen if the server closes the connection - // so we don't leave hanging connections around - if(typeof _self._timeToWait == 'number') { - setTimeout(function() { - // If we are still connecting (no close events fired in between start another connection) - if(_self._poolState == 'connecting') { - _connect(_self); - } - }, _self._timeToWait); - } else { - processor(function() { - // If we are still connecting (no close events fired in between start another connection) - if(_self._poolState == 'connecting') { - _connect(_self); - } - }); - } - } - }); - - var numberOfErrors = 0 - - // Error handler - connection.on("error", function(err, connection, error_options) { - numberOfErrors++; - // If we are already disconnected ignore the event - if(_self._poolState != 'disconnected' && _self.listeners("error").length > 0) { - _self.emit("error", err, connection, error_options); - } - - // Close the connection - connection.close(); - // Set pool as disconnected - _self._poolState = 'disconnected'; - // Stop the pool - _self.stop(); - }); - - // Close handler - connection.on("close", function() { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("close").length > 0) { - _self.emit("close"); - } - - // Set disconnected - _self._poolState = 'disconnected'; - // Stop - _self.stop(); - }); - - // Timeout handler - connection.on("timeout", function(err, connection) { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("timeout").length > 0) { - _self.emit("timeout", err); - } - - // Close the connection - connection.close(); - // Set disconnected - _self._poolState = 'disconnected'; - _self.stop(); - }); - - // Parse error, needs a complete shutdown of the pool - connection.on("parseError", function() { - // If we are already disconnected ignore the event - if(_self._poolState !== 'disconnected' && _self.listeners("parseError").length > 0) { - _self.emit("parseError", new Error("parseError occured")); - } - - // Set disconnected - _self._poolState = 'disconnected'; - _self.stop(); - }); - - connection.on("message", function(message) { - _self.emit("message", message); - }); - - // Start connection in the next tick - connection.start(); - // }(); -} - - -// Start method, will throw error if no listeners are available -// Pass in an instance of the listener that contains the api for -// finding callbacks for a given message etc. -ConnectionPool.prototype.start = function() { - var markerDate = new Date().getTime(); - var self = this; - - if(this.listeners("poolReady").length == 0) { - throw "pool must have at least one listener ready that responds to the [poolReady] event"; - } - - // Set pool state to connecting - this._poolState = 'connecting'; - this._timeout = false; - - _connect(self); -} - -// Restart a connection pool (on a close the pool might be in a wrong state) -ConnectionPool.prototype.restart = function() { - // Close all connections - this.stop(false); - // Now restart the pool - this.start(); -} - -// Stop the connections in the pool -ConnectionPool.prototype.stop = function(removeListeners) { - removeListeners = removeListeners == null ? true : removeListeners; - // Set disconnected - this._poolState = 'disconnected'; - - // Clear all listeners if specified - if(removeListeners) { - this.removeAllEventListeners(); - } - - // Close all connections - for(var i = 0; i < this.openConnections.length; i++) { - this.openConnections[i].close(); - } - - // Clean up - this.openConnections = []; -} - -// Check the status of the connection -ConnectionPool.prototype.isConnected = function() { - // return this._poolState === 'connected'; - return this.openConnections.length > 0 && this.openConnections[0].isConnected(); -} - -// Checkout a connection from the pool for usage, or grab a specific pool instance -ConnectionPool.prototype.checkoutConnection = function(id) { - var index = (this.currentConnectionIndex++ % (this.openConnections.length)); - var connection = this.openConnections[index]; - return connection; -} - -ConnectionPool.prototype.getAllConnections = function() { - return this.openConnections; -} - -// Remove all non-needed event listeners -ConnectionPool.prototype.removeAllEventListeners = function() { - this.removeAllListeners("close"); - this.removeAllListeners("error"); - this.removeAllListeners("timeout"); - this.removeAllListeners("connect"); - this.removeAllListeners("end"); - this.removeAllListeners("parseError"); - this.removeAllListeners("message"); - this.removeAllListeners("poolReady"); -} - - - - - - - - - - - - - - - - - - - - - - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection_utils.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection_utils.js deleted file mode 100644 index 591092495..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/connection_utils.js +++ /dev/null @@ -1,23 +0,0 @@ -exports.setIntegerParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "number" && object[field] !== parseInt(object[field], 10)) { - throw "object field [" + field + "] must be a numeric integer value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} - -exports.setBooleanParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "boolean") { - throw "object field [" + field + "] must be a boolean value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} - -exports.setStringParameter = function(object, field, defaultValue) { - if(object[field] == null) { - object[field] = defaultValue; - } else if(typeof object[field] !== "string") { - throw "object field [" + field + "] must be a string value, attempted to set to [" + object[field] + "] type of [" + typeof object[field] + "]"; - } -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/mongos.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/mongos.js deleted file mode 100644 index 47075bd37..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/mongos.js +++ /dev/null @@ -1,524 +0,0 @@ -var ReadPreference = require('./read_preference').ReadPreference - , Base = require('./base').Base - , Server = require('./server').Server - , format = require('util').format - , timers = require('timers') - , inherits = require('util').inherits; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * Mongos constructor provides a connection to a mongos proxy including failover to additional servers - * - * Options - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **ha** {Boolean, default:true}, turn on high availability, attempts to reconnect to down proxies - * - **haInterval** {Number, default:2000}, time between each replicaset status check. - * - * @class Represents a Mongos connection with failover to backup proxies - * @param {Array} list of mongos server objects - * @param {Object} [options] additional options for the mongos connection - */ -var Mongos = function Mongos(servers, options) { - // Set up basic - if(!(this instanceof Mongos)) - return new Mongos(servers, options); - - // Set up event emitter - Base.call(this); - - // Throw error on wrong setup - if(servers == null || !Array.isArray(servers) || servers.length == 0) - throw new Error("At least one mongos proxy must be in the array"); - - // Ensure we have at least an empty options object - this.options = options == null ? {} : options; - // Set default connection pool options - this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {}; - // Enabled ha - this.haEnabled = this.options['ha'] == null ? true : this.options['ha']; - this._haInProgress = false; - // How often are we checking for new servers in the replicaset - this.mongosStatusCheckInterval = this.options['haInterval'] == null ? 1000 : this.options['haInterval']; - // Save all the server connections - this.servers = servers; - // Servers we need to attempt reconnect with - this.downServers = {}; - // Servers that are up - this.upServers = {}; - // Up servers by ping time - this.upServersByUpTime = {}; - // Emit open setup - this.emitOpen = this.options.emitOpen || true; - // Just contains the current lowest ping time and server - this.lowestPingTimeServer = null; - this.lowestPingTime = 0; - // Connection timeout - this._connectTimeoutMS = this.socketOptions.connectTimeoutMS - ? this.socketOptions.connectTimeoutMS - : 1000; - - // Add options to servers - for(var i = 0; i < this.servers.length; i++) { - var server = this.servers[i]; - server._callBackStore = this._callBackStore; - server.auto_reconnect = false; - // Default empty socket options object - var socketOptions = {host: server.host, port: server.port}; - // If a socket option object exists clone it - if(this.socketOptions != null) { - var keys = Object.keys(this.socketOptions); - for(var k = 0; k < keys.length;k++) socketOptions[keys[i]] = this.socketOptions[keys[i]]; - } - - // Set socket options - server.socketOptions = socketOptions; - } -} - -/** - * @ignore - */ -inherits(Mongos, Base); - -/** - * @ignore - */ -Mongos.prototype.isMongos = function() { - return true; -} - -/** - * @ignore - */ -Mongos.prototype.connect = function(db, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - - // Keep reference to parent - this.db = db; - // Set server state to connecting - this._serverState = 'connecting'; - // Number of total servers that need to initialized (known servers) - this._numberOfServersLeftToInitialize = this.servers.length; - // Connect handler - var connectHandler = function(_server) { - return function(err, result) { - self._numberOfServersLeftToInitialize = self._numberOfServersLeftToInitialize - 1; - - // Add the server to the list of servers that are up - if(!err) { - self.upServers[format("%s:%s", _server.host, _server.port)] = _server; - } - - // We are done connecting - if(self._numberOfServersLeftToInitialize == 0) { - // Start ha function if it exists - if(self.haEnabled) { - // Setup the ha process - if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId); - self._replicasetTimeoutId = setInterval(self.mongosCheckFunction, self.mongosStatusCheckInterval); - } - - // Set the mongos to connected - self._serverState = "connected"; - - // Emit the open event - if(self.emitOpen) - self._emitAcrossAllDbInstances(self, null, "open", null, null, null); - - self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null); - // Callback - callback(null, self.db); - } - } - }; - - // Error handler - var errorOrCloseHandler = function(_server) { - return function(err, result) { - // Execute all the callbacks with errors - self.__executeAllCallbacksWithError(err); - // Check if we have the server - var found = false; - - // Get the server name - var server_name = format("%s:%s", _server.host, _server.port); - // Add the downed server - self.downServers[server_name] = _server; - // Remove the current server from the list - delete self.upServers[server_name]; - - // Emit close across all the attached db instances - if(Object.keys(self.upServers).length == 0) { - self._emitAcrossAllDbInstances(self, null, "close", new Error("mongos disconnected, no valid proxies contactable over tcp"), null, null); - } - } - } - - // Mongo function - this.mongosCheckFunction = function() { - // Set as not waiting for check event - self._haInProgress = true; - - // Servers down - var numberOfServersLeft = Object.keys(self.downServers).length; - - // Check downed servers - if(numberOfServersLeft > 0) { - for(var name in self.downServers) { - // Pop a downed server - var downServer = self.downServers[name]; - // Set up the connection options for a Mongos - var options = { - auto_reconnect: false, - returnIsMasterResults: true, - slaveOk: true, - poolSize: downServer.poolSize, - socketOptions: { - connectTimeoutMS: self._connectTimeoutMS, - socketTimeoutMS: self._socketTimeoutMS - } - } - - // Create a new server object - var newServer = new Server(downServer.host, downServer.port, options); - // Setup the connection function - var connectFunction = function(_db, _server, _options, _callback) { - return function() { - // Attempt to connect - _server.connect(_db, _options, function(err, result) { - numberOfServersLeft = numberOfServersLeft - 1; - - if(err) { - return _callback(err, _server); - } else { - // Set the new server settings - _server._callBackStore = self._callBackStore; - - // Add server event handlers - _server.on("close", errorOrCloseHandler(_server)); - _server.on("timeout", errorOrCloseHandler(_server)); - _server.on("error", errorOrCloseHandler(_server)); - - // Get a read connection - var _connection = _server.checkoutReader(); - // Get the start time - var startTime = new Date().getTime(); - - // Execute ping command to mark each server with the expected times - self.db.command({ping:1} - , {failFast:true, connection:_connection}, function(err, result) { - // Get the start time - var endTime = new Date().getTime(); - // Mark the server with the ping time - _server.runtimeStats['pingMs'] = endTime - startTime; - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - // Callback - return _callback(null, _server); - }); - } - }); - } - } - - // Attempt to connect to the database - connectFunction(self.db, newServer, options, function(err, _server) { - // If we have an error - if(err) { - self.downServers[format("%s:%s", _server.host, _server.port)] = _server; - } - - // Connection function - var connectionFunction = function(_auth, _connection, _callback) { - var pending = _auth.length(); - - for(var j = 0; j < pending; j++) { - // Get the auth object - var _auth = _auth.get(j); - // Unpack the parameter - var username = _auth.username; - var password = _auth.password; - var options = { - authMechanism: _auth.authMechanism - , authSource: _auth.authdb - , connection: _connection - }; - - // If we have changed the service name - if(_auth.gssapiServiceName) - options.gssapiServiceName = _auth.gssapiServiceName; - - // Hold any error - var _error = null; - // Authenticate against the credentials - self.db.authenticate(username, password, options, function(err, result) { - _error = err != null ? err : _error; - // Adjust the pending authentication - pending = pending - 1; - // Finished up - if(pending == 0) _callback(_error ? _error : null, _error ? false : true); - }); - } - } - - // Run auths against the connections - if(self.auth.length() > 0) { - var connections = _server.allRawConnections(); - var pendingAuthConn = connections.length; - - // No connections we are done - if(connections.length == 0) { - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - } - } - - // Final error object - var finalError = null; - // Go over all the connections - for(var j = 0; j < connections.length; j++) { - - // Execute against all the connections - connectionFunction(self.auth, connections[j], function(err, result) { - // Pending authentication - pendingAuthConn = pendingAuthConn - 1 ; - - // Save error if any - finalError = err ? err : finalError; - - // If we are done let's finish up - if(pendingAuthConn == 0) { - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - } - - if(!err) { - add_server(self, _server); - } - - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - } - }); - } - } else { - if(!err) { - add_server(self, _server); - } - - // Set ha done - if(numberOfServersLeft == 0) { - self._haInProgress = false; - // Execute any waiting reads - self._commandsStore.execute_writes(); - self._commandsStore.execute_queries(); - } - } - })(); - } - } else { - self._haInProgress = false; - } - } - - // Connect all the server instances - for(var i = 0; i < this.servers.length; i++) { - // Get the connection - var server = this.servers[i]; - server.mongosInstance = this; - // Add server event handlers - server.on("close", errorOrCloseHandler(server)); - server.on("timeout", errorOrCloseHandler(server)); - server.on("error", errorOrCloseHandler(server)); - - // Configuration - var options = { - slaveOk: true, - poolSize: server.poolSize, - socketOptions: { connectTimeoutMS: self._connectTimeoutMS }, - returnIsMasterResults: true - } - - // Connect the instance - server.connect(self.db, options, connectHandler(server)); - } -} - -/** - * @ignore - * Add a server to the list of up servers and sort them by ping time - */ -var add_server = function(self, _server) { - var server_key = format("%s:%s", _server.host, _server.port); - // Push to list of valid server - self.upServers[server_key] = _server; - // Remove the server from the list of downed servers - delete self.downServers[server_key]; - - // Sort the keys by ping time - var keys = Object.keys(self.upServers); - var _upServersSorted = {}; - var _upServers = [] - - // Get all the servers - for(var name in self.upServers) { - _upServers.push(self.upServers[name]); - } - - // Sort all the server - _upServers.sort(function(a, b) { - return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs']; - }); - - // Rebuild the upServer - for(var i = 0; i < _upServers.length; i++) { - _upServersSorted[format("%s:%s", _upServers[i].host, _upServers[i].port)] = _upServers[i]; - } - - // Set the up servers - self.upServers = _upServersSorted; -} - -/** - * @ignore - * Just return the currently picked active connection - */ -Mongos.prototype.allServerInstances = function() { - return this.servers; -} - -/** - * Always ourselves - * @ignore - */ -Mongos.prototype.setReadPreference = function() {} - -/** - * @ignore - */ -Mongos.prototype.allRawConnections = function() { - // Neeed to build a complete list of all raw connections, start with master server - var allConnections = []; - // Get all connected connections - for(var name in this.upServers) { - allConnections = allConnections.concat(this.upServers[name].allRawConnections()); - } - // Return all the conections - return allConnections; -} - -/** - * @ignore - */ -Mongos.prototype.isConnected = function() { - return Object.keys(this.upServers).length > 0; -} - -/** - * @ignore - */ -Mongos.prototype.isAutoReconnect = function() { - return true; -} - -/** - * @ignore - */ -Mongos.prototype.canWrite = Mongos.prototype.isConnected; - -/** - * @ignore - */ -Mongos.prototype.canRead = Mongos.prototype.isConnected; - -/** - * @ignore - */ -Mongos.prototype.isDestroyed = function() { - return this._serverState == 'destroyed'; -} - -/** - * @ignore - */ -Mongos.prototype.checkoutWriter = function() { - // Checkout a writer - var keys = Object.keys(this.upServers); - // console.dir("============================ checkoutWriter :: " + keys.length) - if(keys.length == 0) return null; - // console.log("=============== checkoutWriter :: " + this.upServers[keys[0]].checkoutWriter().socketOptions.port) - return this.upServers[keys[0]].checkoutWriter(); -} - -/** - * @ignore - */ -Mongos.prototype.checkoutReader = function(read) { - // console.log("=============== checkoutReader :: read :: " + read); - // If read is set to null default to primary - read = read || 'primary' - // If we have a read preference object unpack it - if(read != null && typeof read == 'object' && read['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!read.isValid()) throw new Error("Illegal readPreference mode specified, " + read.mode); - } else if(!ReadPreference.isValid(read)) { - throw new Error("Illegal readPreference mode specified, " + read); - } - - // Checkout a writer - var keys = Object.keys(this.upServers); - if(keys.length == 0) return null; - // console.log("=============== checkoutReader :: " + this.upServers[keys[0]].checkoutWriter().socketOptions.port) - // console.dir(this._commandsStore.commands) - return this.upServers[keys[0]].checkoutWriter(); -} - -/** - * @ignore - */ -Mongos.prototype.close = function(callback) { - var self = this; - // Set server status as disconnected - this._serverState = 'destroyed'; - // Number of connections to close - var numberOfConnectionsToClose = self.servers.length; - // If we have a ha process running kill it - if(self._replicasetTimeoutId != null) clearInterval(self._replicasetTimeoutId); - self._replicasetTimeoutId = null; - - // Emit close event - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }); - - // Close all the up servers - for(var name in this.upServers) { - this.upServers[name].close(function(err, result) { - numberOfConnectionsToClose = numberOfConnectionsToClose - 1; - - // Callback if we have one defined - if(numberOfConnectionsToClose == 0 && typeof callback == 'function') { - callback(null); - } - }); - } -} - -/** - * @ignore - * Return the used state - */ -Mongos.prototype._isUsed = function() { - return this._used; -} - -exports.Mongos = Mongos; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/read_preference.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/read_preference.js deleted file mode 100644 index 6845171a3..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/read_preference.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * A class representation of the Read Preference. - * - * Read Preferences - * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). - * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. - * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. - * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. - * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. - * - * @class Represents a Read Preference. - * @param {String} the read preference type - * @param {Object} tags - * @return {ReadPreference} - */ -var ReadPreference = function(mode, tags) { - if(!(this instanceof ReadPreference)) - return new ReadPreference(mode, tags); - this._type = 'ReadPreference'; - this.mode = mode; - this.tags = tags; -} - -/** - * @ignore - */ -ReadPreference.isValid = function(_mode) { - return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED - || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED - || _mode == ReadPreference.NEAREST - || _mode == true || _mode == false); -} - -/** - * @ignore - */ -ReadPreference.prototype.isValid = function(mode) { - var _mode = typeof mode == 'string' ? mode : this.mode; - return ReadPreference.isValid(_mode); -} - -/** - * @ignore - */ -ReadPreference.prototype.toObject = function() { - var object = {mode:this.mode}; - - if(this.tags != null) { - object['tags'] = this.tags; - } - - return object; -} - -/** - * @ignore - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest' - -/** - * @ignore - */ -exports.ReadPreference = ReadPreference; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js deleted file mode 100644 index b89e7bafc..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/ha.js +++ /dev/null @@ -1,407 +0,0 @@ -var DbCommand = require('../../commands/db_command').DbCommand - , format = require('util').format; - -var HighAvailabilityProcess = function(replset, options) { - this.replset = replset; - this.options = options; - this.server = null; - this.state = HighAvailabilityProcess.INIT; - this.selectedIndex = 0; -} - -HighAvailabilityProcess.INIT = 'init'; -HighAvailabilityProcess.RUNNING = 'running'; -HighAvailabilityProcess.STOPPED = 'stopped'; - -HighAvailabilityProcess.prototype.start = function() { - var self = this; - if(this.replset._state - && Object.keys(this.replset._state.addresses).length == 0) { - if(this.server) this.server.close(); - this.state = HighAvailabilityProcess.STOPPED; - return; - } - - if(this.server) this.server.close(); - // Start the running - this._haProcessInProcess = false; - this.state = HighAvailabilityProcess.RUNNING; - - // Get all possible reader servers - var candidate_servers = this.replset._state.getAllReadServers(); - if(candidate_servers.length == 0) { - return; - } - - // Select a candidate server for the connection - var server = candidate_servers[this.selectedIndex % candidate_servers.length]; - this.selectedIndex = this.selectedIndex + 1; - - // Unpack connection options - var connectTimeoutMS = self.options.connectTimeoutMS || 10000; - var socketTimeoutMS = self.options.socketTimeoutMS || 30000; - - // Just ensure we don't have a full cycle dependency - var Db = require('../../db').Db - var Server = require('../server').Server; - - // Set up a new server instance - var newServer = new Server(server.host, server.port, { - auto_reconnect: false - , returnIsMasterResults: true - , poolSize: 1 - , socketOptions: { - connectTimeoutMS: connectTimeoutMS, - socketTimeoutMS: socketTimeoutMS, - keepAlive: 100 - } - , ssl: this.options.ssl - , sslValidate: this.options.sslValidate - , sslCA: this.options.sslCA - , sslCert: this.options.sslCert - , sslKey: this.options.sslKey - , sslPass: this.options.sslPass - }); - - // Create new dummy db for app - self.db = new Db('local', newServer, {w:1}); - - // Set up the event listeners - newServer.once("error", _handle(this, newServer)); - newServer.once("close", _handle(this, newServer)); - newServer.once("timeout", _handle(this, newServer)); - newServer.name = format("%s:%s", server.host, server.port); - - // Let's attempt a connection over here - newServer.connect(self.db, function(err, result, _server) { - if(self.state == HighAvailabilityProcess.STOPPED) { - _server.close(); - } - - if(err) { - // Close the server - _server.close(); - // Check if we can even do HA (is there anything running) - if(Object.keys(self.replset._state.addresses).length == 0) { - return; - } - - // Let's boot the ha timeout settings - setTimeout(function() { - self.start(); - }, self.options.haInterval); - } else { - self.server = _server; - // Let's boot the ha timeout settings - setTimeout(_timeoutHandle(self), self.options.haInterval); - } - }); -} - -HighAvailabilityProcess.prototype.stop = function() { - this.state = HighAvailabilityProcess.STOPPED; - if(this.server) this.server.close(); -} - -var _timeoutHandle = function(self) { - return function() { - if(self.state == HighAvailabilityProcess.STOPPED) { - // Stop all server instances - for(var name in self.replset._state.addresses) { - self.replset._state.addresses[name].close(); - delete self.replset._state.addresses[name]; - } - - // Finished pinging - return; - } - - // If the server is connected - if(self.server.isConnected() && !self._haProcessInProcess) { - // Start HA process - self._haProcessInProcess = true; - // Execute is master command - self.db._executeQueryCommand(DbCommand.createIsMasterCommand(self.db), - {failFast:true, connection: self.server.checkoutReader()} - , function(err, res) { - if(err) { - self.server.close(); - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // Master document - var master = res.documents[0]; - var hosts = master.hosts || []; - var reconnect_servers = []; - var state = self.replset._state; - - // We are in recovery mode, let's remove the current server - if(!master.ismaster - && !master.secondary - && state.addresses[master.me]) { - self.server.close(); - state.addresses[master.me].close(); - delete state.secondaries[master.me]; - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // For all the hosts let's check that we have connections - for(var i = 0; i < hosts.length; i++) { - var host = hosts[i]; - // Check if we need to reconnect to a server - if(state.addresses[host] == null) { - reconnect_servers.push(host); - } else if(state.addresses[host] && !state.addresses[host].isConnected()) { - state.addresses[host].close(); - delete state.secondaries[host]; - reconnect_servers.push(host); - } - - if((master.primary && state.master == null) - || (master.primary && state.master.name != master.primary)) { - - // Locate the primary and set it - if(state.addresses[master.primary]) { - if(state.master) state.master.close(); - delete state.secondaries[master.primary]; - state.master = state.addresses[master.primary]; - } - - // Set up the changes - if(state.master != null && state.master.isMasterDoc != null) { - state.master.isMasterDoc.ismaster = true; - state.master.isMasterDoc.secondary = false; - } else if(state.master != null) { - state.master.isMasterDoc = master; - state.master.isMasterDoc.ismaster = true; - state.master.isMasterDoc.secondary = false; - } - - // Execute any waiting commands (queries or writes) - self.replset._commandsStore.execute_queries(); - self.replset._commandsStore.execute_writes(); - } - } - - // Let's reconnect to any server needed - if(reconnect_servers.length > 0) { - _reconnect_servers(self, reconnect_servers); - } else { - self._haProcessInProcess = false - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - }); - } else if(!self.server.isConnected()) { - setTimeout(function() { - return self.start(); - }, self.options.haInterval); - } else { - setTimeout(_timeoutHandle(self), self.options.haInterval); - } - } -} - -var _reconnect_servers = function(self, reconnect_servers) { - if(reconnect_servers.length == 0) { - self._haProcessInProcess = false - return setTimeout(_timeoutHandle(self), self.options.haInterval); - } - - // Unpack connection options - var connectTimeoutMS = self.options.connectTimeoutMS || 10000; - var socketTimeoutMS = self.options.socketTimeoutMS || 30000; - - // Server class - var Db = require('../../db').Db - var Server = require('../server').Server; - // Get the host - var host = reconnect_servers.shift(); - // Split it up - var _host = host.split(":")[0]; - var _port = parseInt(host.split(":")[1], 10); - - // Set up a new server instance - var newServer = new Server(_host, _port, { - auto_reconnect: false - , returnIsMasterResults: true - , poolSize: self.options.poolSize - , socketOptions: { - connectTimeoutMS: connectTimeoutMS, - socketTimeoutMS: socketTimeoutMS - } - , ssl: self.options.ssl - , sslValidate: self.options.sslValidate - , sslCA: self.options.sslCA - , sslCert: self.options.sslCert - , sslKey: self.options.sslKey - , sslPass: self.options.sslPass - }); - - // Create new dummy db for app - var db = new Db('local', newServer, {w:1}); - var state = self.replset._state; - - // Set up the event listeners - newServer.once("error", _repl_set_handler("error", self.replset, newServer)); - newServer.once("close", _repl_set_handler("close", self.replset, newServer)); - newServer.once("timeout", _repl_set_handler("timeout", self.replset, newServer)); - - // Set shared state - newServer.name = host; - newServer._callBackStore = self.replset._callBackStore; - newServer.replicasetInstance = self.replset; - newServer.enableRecordQueryStats(self.replset.recordQueryStats); - - // Let's attempt a connection over here - newServer.connect(db, function(err, result, _server) { - if(self.state == HighAvailabilityProcess.STOPPED) { - _server.close(); - } - - // If we connected let's check what kind of server we have - if(!err) { - _apply_auths(self, db, _server, function(err, result) { - if(err) { - _server.close(); - // Process the next server - return setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - } - var doc = _server.isMasterDoc; - // Fire error on any unknown callbacks for this server - self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err); - - if(doc.ismaster) { - if(state.secondaries[doc.me]) { - delete state.secondaries[doc.me]; - } - - // Override any server in list of addresses - state.addresses[doc.me] = _server; - // Set server as master - state.master = _server; - // Execute any waiting writes - self.replset._commandsStore.execute_writes(); - } else if(doc.secondary) { - state.secondaries[doc.me] = _server; - // Override any server in list of addresses - state.addresses[doc.me] = _server; - // Execute any waiting reads - self.replset._commandsStore.execute_queries(); - } else { - _server.close(); - } - - // Set any tags on the instance server - _server.name = doc.me; - _server.tags = doc.tags; - // Process the next server - setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - }); - } else { - _server.close(); - self.replset.__executeAllServerSpecificErrorCallbacks(_server.socketOptions.host, _server.socketOptions.port, err); - - setTimeout(function() { - _reconnect_servers(self, reconnect_servers); - }, self.options.haInterval); - } - }); -} - -var _apply_auths = function(self, _db, _server, _callback) { - if(self.replset.auth.length() == 0) return _callback(null); - // Apply any authentication needed - if(self.replset.auth.length() > 0) { - var pending = self.replset.auth.length(); - var connections = _server.allRawConnections(); - var pendingAuthConn = connections.length; - - // Connection function - var connectionFunction = function(_auth, _connection, __callback) { - var pending = _auth.length(); - - for(var j = 0; j < pending; j++) { - // Get the auth object - var _auth = _auth.get(j); - // Unpack the parameter - var username = _auth.username; - var password = _auth.password; - var options = { - authMechanism: _auth.authMechanism - , authSource: _auth.authdb - , connection: _connection - }; - - // If we have changed the service name - if(_auth.gssapiServiceName) - options.gssapiServiceName = _auth.gssapiServiceName; - - // Hold any error - var _error = null; - - // Authenticate against the credentials - _db.authenticate(username, password, options, function(err, result) { - _error = err != null ? err : _error; - // Adjust the pending authentication - pending = pending - 1; - // Finished up - if(pending == 0) __callback(_error ? _error : null, _error ? false : true); - }); - } - } - - // Final error object - var finalError = null; - // Iterate over all the connections - for(var i = 0; i < connections.length; i++) { - connectionFunction(self.replset.auth, connections[i], function(err, result) { - // Pending authentication - pendingAuthConn = pendingAuthConn - 1 ; - - // Save error if any - finalError = err ? err : finalError; - - // If we are done let's finish up - if(pendingAuthConn == 0) { - _callback(null); - } - }); - } - } -} - -var _handle = function(self, server) { - return function(err) { - server.close(); - } -} - -var _repl_set_handler = function(event, self, server) { - var ReplSet = require('./repl_set').ReplSet; - - return function(err, doc) { - server.close(); - - // The event happened to a primary - // Remove it from play - if(self._state.isPrimary(server)) { - self._state.master == null; - self._serverState = ReplSet.REPLSET_READ_ONLY; - } else if(self._state.isSecondary(server)) { - delete self._state.secondaries[server.name]; - } - - // Unpack variables - var host = server.socketOptions.host; - var port = server.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } -} - -exports.HighAvailabilityProcess = HighAvailabilityProcess; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js deleted file mode 100644 index a5658e3b0..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/options.js +++ /dev/null @@ -1,126 +0,0 @@ -var PingStrategy = require('./strategies/ping_strategy').PingStrategy - , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy - , ReadPreference = require('../read_preference').ReadPreference; - -var Options = function(options) { - options = options || {}; - this._options = options; - this.ha = options.ha || true; - this.haInterval = options.haInterval || 2000; - this.reconnectWait = options.reconnectWait || 1000; - this.retries = options.retries || 30; - this.rs_name = options.rs_name; - this.socketOptions = options.socketOptions || {}; - this.readPreference = options.readPreference; - this.readSecondary = options.read_secondary; - this.poolSize = options.poolSize == null ? 5 : options.poolSize; - this.strategy = options.strategy || 'ping'; - this.secondaryAcceptableLatencyMS = options.secondaryAcceptableLatencyMS || 15; - this.connectArbiter = options.connectArbiter || false; - this.connectWithNoPrimary = options.connectWithNoPrimary || false; - this.logger = options.logger; - this.ssl = options.ssl || false; - this.sslValidate = options.sslValidate || false; - this.sslCA = options.sslCA; - this.sslCert = options.sslCert; - this.sslKey = options.sslKey; - this.sslPass = options.sslPass; - this.emitOpen = options.emitOpen || true; -} - -Options.prototype.init = function() { - if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) { - throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate"); - } - - // Make sure strategy is one of the two allowed - if(this.strategy != null && (this.strategy != 'ping' && this.strategy != 'statistical' && this.strategy != 'none')) - throw new Error("Only ping or statistical strategies allowed"); - - if(this.strategy == null) this.strategy = 'ping'; - - // Set logger if strategy exists - if(this.strategyInstance) this.strategyInstance.logger = this.logger; - - // Unpack read Preference - var readPreference = this.readPreference; - // Validate correctness of Read preferences - if(readPreference != null) { - if(readPreference != ReadPreference.PRIMARY && readPreference != ReadPreference.PRIMARY_PREFERRED - && readPreference != ReadPreference.SECONDARY && readPreference != ReadPreference.SECONDARY_PREFERRED - && readPreference != ReadPreference.NEAREST && typeof readPreference != 'object' && readPreference['_type'] != 'ReadPreference') { - throw new Error("Illegal readPreference mode specified, " + readPreference); - } - - this.readPreference = readPreference; - } else { - this.readPreference = null; - } - - // Ensure read_secondary is set correctly - if(this.readSecondary != null) - this.readSecondary = this.readPreference == ReadPreference.PRIMARY - || this.readPreference == false - || this.readPreference == null ? false : true; - - // Ensure correct slave set - if(this.readSecondary) this.slaveOk = true; - - // Set up logger if any set - this.logger = this.logger != null - && (typeof this.logger.debug == 'function') - && (typeof this.logger.error == 'function') - && (typeof this.logger.debug == 'function') - ? this.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Connection timeout - this.connectTimeoutMS = this.socketOptions.connectTimeoutMS - ? this.socketOptions.connectTimeoutMS - : 1000; - - // Socket connection timeout - this.socketTimeoutMS = this.socketOptions.socketTimeoutMS - ? this.socketOptions.socketTimeoutMS - : 30000; -} - -Options.prototype.decorateAndClean = function(servers, callBackStore) { - var self = this; - - // var de duplicate list - var uniqueServers = {}; - // De-duplicate any servers in the seed list - for(var i = 0; i < servers.length; i++) { - var server = servers[i]; - // If server does not exist set it - if(uniqueServers[server.host + ":" + server.port] == null) { - uniqueServers[server.host + ":" + server.port] = server; - } - } - - // Let's set the deduplicated list of servers - var finalServers = []; - // Add the servers - for(var key in uniqueServers) { - finalServers.push(uniqueServers[key]); - } - - finalServers.forEach(function(server) { - // Ensure no server has reconnect on - server.options.auto_reconnect = false; - // Set up ssl options - server.ssl = self.ssl; - server.sslValidate = self.sslValidate; - server.sslCA = self.sslCA; - server.sslCert = self.sslCert; - server.sslKey = self.sslKey; - server.sslPass = self.sslPass; - server.poolSize = self.poolSize; - // Set callback store - server._callBackStore = callBackStore; - }); - - return finalServers; -} - -exports.Options = Options; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js deleted file mode 100644 index 3254df912..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set.js +++ /dev/null @@ -1,799 +0,0 @@ -var ReadPreference = require('../read_preference').ReadPreference - , DbCommand = require('../../commands/db_command').DbCommand - , inherits = require('util').inherits - , format = require('util').format - , timers = require('timers') - , Server = require('../server').Server - , utils = require('../../utils') - , PingStrategy = require('./strategies/ping_strategy').PingStrategy - , StatisticsStrategy = require('./strategies/statistics_strategy').StatisticsStrategy - , Options = require('./options').Options - , ReplSetState = require('./repl_set_state').ReplSetState - , HighAvailabilityProcess = require('./ha').HighAvailabilityProcess - , Base = require('../base').Base; - -const STATE_STARTING_PHASE_1 = 0; -const STATE_PRIMARY = 1; -const STATE_SECONDARY = 2; -const STATE_RECOVERING = 3; -const STATE_FATAL_ERROR = 4; -const STATE_STARTING_PHASE_2 = 5; -const STATE_UNKNOWN = 6; -const STATE_ARBITER = 7; -const STATE_DOWN = 8; -const STATE_ROLLBACK = 9; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../../utils').processor(); - -/** - * ReplSet constructor provides replicaset functionality - * - * Options - * - **ha** {Boolean, default:true}, turn on high availability. - * - **haInterval** {Number, default:2000}, time between each replicaset status check. - * - **reconnectWait** {Number, default:1000}, time to wait in miliseconds before attempting reconnect. - * - **retries** {Number, default:30}, number of times to attempt a replicaset reconnect. - * - **rs_name** {String}, the name of the replicaset to connect to. - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strategy** {String, default:'ping'}, selection strategy for reads choose between (ping, statistical and none, default is ping) - * - **secondaryAcceptableLatencyMS** {Number, default:15}, sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * - **connectWithNoPrimary** {Boolean, default:false}, sets if the driver should connect even if no primary is available - * - **connectArbiter** {Boolean, default:false}, sets if the driver should connect to arbiters or not. - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **poolSize** {Number, default:5}, number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support) - * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * - * @class Represents a - Replicaset Configuration - * @param {Array} list of server objects participating in the replicaset. - * @param {Object} [options] additional options for the replicaset connection. - */ -var ReplSet = exports.ReplSet = function(servers, options) { - // Set up basic - if(!(this instanceof ReplSet)) - return new ReplSet(servers, options); - - // Set up event emitter - Base.call(this); - - // Ensure we have a list of servers - if(!Array.isArray(servers)) throw Error("The parameter must be an array of servers and contain at least one server"); - // Ensure no Mongos's - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) throw new Error("list of servers must be of type Server"); - } - - // Save the options - this.options = new Options(options); - // Ensure basic validation of options - this.options.init(); - - // Server state - this._serverState = ReplSet.REPLSET_DISCONNECTED; - // Add high availability process - this._haProcess = new HighAvailabilityProcess(this, this.options); - - - // Let's iterate over all the provided server objects and decorate them - this.servers = this.options.decorateAndClean(servers, this._callBackStore); - // Throw error if no seed servers - if(this.servers.length == 0) throw new Error("No valid seed servers in the array"); - - // Let's set up our strategy object for picking secondaries - if(this.options.strategy == 'ping') { - // Create a new instance - this.strategyInstance = new PingStrategy(this, this.options.secondaryAcceptableLatencyMS); - } else if(this.options.strategy == 'statistical') { - // Set strategy as statistical - this.strategyInstance = new StatisticsStrategy(this); - // Add enable query information - this.enableRecordQueryStats(true); - } - - this.emitOpen = this.options.emitOpen || true; - // Set up a clean state - this._state = new ReplSetState(); - // Current round robin selected server - this._currentServerChoice = 0; - // Ensure up the server callbacks - for(var i = 0; i < this.servers.length; i++) { - this.servers[i]._callBackStore = this._callBackStore; - this.servers[i].name = format("%s:%s", this.servers[i].host, this.servers[i].port) - this.servers[i].replicasetInstance = this; - this.servers[i].options.auto_reconnect = false; - this.servers[i].inheritReplSetOptionsFrom(this); - } -} - -/** - * @ignore - */ -inherits(ReplSet, Base); - -// Replicaset states -ReplSet.REPLSET_CONNECTING = 'connecting'; -ReplSet.REPLSET_DISCONNECTED = 'disconnected'; -ReplSet.REPLSET_CONNECTED = 'connected'; -ReplSet.REPLSET_RECONNECTING = 'reconnecting'; -ReplSet.REPLSET_DESTROYED = 'destroyed'; -ReplSet.REPLSET_READ_ONLY = 'readonly'; - -ReplSet.prototype.isAutoReconnect = function() { - return true; -} - -ReplSet.prototype.canWrite = function() { - return this._state.master && this._state.master.isConnected(); -} - -ReplSet.prototype.canRead = function(read) { - if((read == ReadPreference.PRIMARY - || read == null || read == false) && (this._state.master == null || !this._state.master.isConnected())) return false; - return Object.keys(this._state.secondaries).length > 0; -} - -/** - * @ignore - */ -ReplSet.prototype.enableRecordQueryStats = function(enable) { - // Set the global enable record query stats - this.recordQueryStats = enable; - - // Enable all the servers - for(var i = 0; i < this.servers.length; i++) { - this.servers[i].enableRecordQueryStats(enable); - } -} - -/** - * @ignore - */ -ReplSet.prototype.setReadPreference = function(preference) { - this.options.readPreference = preference; -} - -ReplSet.prototype.connect = function(parent, options, callback) { - if(this._serverState != ReplSet.REPLSET_DISCONNECTED) - return callback(new Error("in process of connection")); - - // If no callback throw - if(!(typeof callback == 'function')) - throw new Error("cannot call ReplSet.prototype.connect with no callback function"); - - var self = this; - // Save db reference - this.options.db = parent; - // Set replicaset as connecting - this._serverState = ReplSet.REPLSET_CONNECTING - // Copy all the servers to our list of seeds - var candidateServers = this.servers.slice(0); - // Pop the first server - var server = candidateServers.pop(); - server.name = format("%s:%s", server.host, server.port); - // Set up the options - var opts = { - returnIsMasterResults: true, - eventReceiver: server - } - - // Register some event listeners - this.once("fullsetup", function(err, db, replset) { - // Set state to connected - self._serverState = ReplSet.REPLSET_CONNECTED; - // Stop any process running - if(self._haProcess) self._haProcess.stop(); - // Start the HA process - self._haProcess.start(); - - // Emit fullsetup - processor(function() { - if(self.emitOpen) - self._emitAcrossAllDbInstances(self, null, "open", null, null, null); - - self._emitAcrossAllDbInstances(self, null, "fullsetup", null, null, null); - }); - - // If we have a strategy defined start it - if(self.strategyInstance) { - self.strategyInstance.start(); - } - - // Finishing up the call - callback(err, db, replset); - }); - - // Errors - this.once("connectionError", function(err, result) { - callback(err, result); - }); - - // Attempt to connect to the server - server.connect(this.options.db, opts, _connectHandler(this, candidateServers, server)); -} - -ReplSet.prototype.close = function(callback) { - var self = this; - // Set as destroyed - this._serverState = ReplSet.REPLSET_DESTROYED; - // Stop the ha - this._haProcess.stop(); - - // If we have a strategy stop it - if(this.strategyInstance) { - this.strategyInstance.stop(); - } - - // Kill all servers available - for(var name in this._state.addresses) { - this._state.addresses[name].close(); - } - - // Clean out the state - this._state = new ReplSetState(); - - // Emit close event - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }); - - // Callback - if(typeof callback == 'function') - return callback(null, null); -} - -/** - * Creates a new server for the `replset` based on `host`. - * - * @param {String} host - host:port pair (localhost:27017) - * @param {ReplSet} replset - the ReplSet instance - * @return {Server} - * @ignore - */ -var createServer = function(self, host, options) { - // copy existing socket options to new server - var socketOptions = {} - if(options.socketOptions) { - var keys = Object.keys(options.socketOptions); - for(var k = 0; k < keys.length; k++) { - socketOptions[keys[k]] = options.socketOptions[keys[k]]; - } - } - - var parts = host.split(/:/); - if(1 === parts.length) { - parts[1] = Connection.DEFAULT_PORT; - } - - socketOptions.host = parts[0]; - socketOptions.port = parseInt(parts[1], 10); - - var serverOptions = { - readPreference: options.readPreference, - socketOptions: socketOptions, - poolSize: options.poolSize, - logger: options.logger, - auto_reconnect: false, - ssl: options.ssl, - sslValidate: options.sslValidate, - sslCA: options.sslCA, - sslCert: options.sslCert, - sslKey: options.sslKey, - sslPass: options.sslPass - } - - var server = new Server(socketOptions.host, socketOptions.port, serverOptions); - // Set up shared state - server._callBackStore = self._callBackStore; - server.replicasetInstance = self; - server.enableRecordQueryStats(self.recordQueryStats); - // Set up event handlers - server.on("close", _handler("close", self, server)); - server.on("error", _handler("error", self, server)); - server.on("timeout", _handler("timeout", self, server)); - return server; -} - -var _handler = function(event, self, server) { - return function(err, doc) { - // The event happened to a primary - // Remove it from play - if(self._state.isPrimary(server)) { - var current_master = self._state.master; - self._state.master = null; - self._serverState = ReplSet.REPLSET_READ_ONLY; - - if(current_master != null) { - // Unpack variables - var host = current_master.socketOptions.host; - var port = current_master.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } - } else if(self._state.isSecondary(server)) { - delete self._state.secondaries[server.name]; - } - - // If there is no more connections left and the setting is not destroyed - // set to disconnected - if(Object.keys(self._state.addresses).length == 0 - && self._serverState != ReplSet.REPLSET_DESTROYED) { - self._serverState = ReplSet.REPLSET_DISCONNECTED; - - // Emit close across all the attached db instances - self._dbStore.emit("close", new Error("replicaset disconnected, no valid servers contactable over tcp"), null, true); - } - - // Unpack variables - var host = server.socketOptions.host; - var port = server.socketOptions.port; - - // Fire error on any unknown callbacks - self.__executeAllServerSpecificErrorCallbacks(host, port, err); - } -} - -var locateNewServers = function(self, state, candidateServers, ismaster) { - // Retrieve the host - var hosts = ismaster.hosts; - // In candidate servers - var inCandidateServers = function(name, candidateServers) { - for(var i = 0; i < candidateServers.length; i++) { - if(candidateServers[i].name == name) return true; - } - - return false; - } - - // New servers - var newServers = []; - if(Array.isArray(hosts)) { - // Let's go over all the hosts - for(var i = 0; i < hosts.length; i++) { - if(!state.contains(hosts[i]) - && !inCandidateServers(hosts[i], candidateServers)) { - newServers.push(createServer(self, hosts[i], self.options)); - } - } - } - - // Return list of possible new servers - return newServers; -} - -var _connectHandler = function(self, candidateServers, instanceServer) { - return function(err, doc) { - // If we have an error add to the list - if(err) { - self._state.errors[instanceServer.name] = instanceServer; - } else { - delete self._state.errors[instanceServer.name]; - } - - if(!err) { - var ismaster = doc.documents[0] - - // Error the server if - if(!ismaster.ismaster - && !ismaster.secondary) { - self._state.errors[instanceServer.name] = instanceServer; - } - } - - - // No error let's analyse the ismaster command - if(!err && self._state.errors[instanceServer.name] == null) { - var ismaster = doc.documents[0] - - // If no replicaset name exists set the current one - if(self.options.rs_name == null) { - self.options.rs_name = ismaster.setName; - } - - // If we have a member that is not part of the set let's finish up - if(typeof ismaster.setName == 'string' && ismaster.setName != self.options.rs_name) { - return self.emit("connectionError", new Error("Replicaset name " + ismaster.setName + " does not match specified name " + self.options.rs_name)); - } - - // Add the error handlers - instanceServer.on("close", _handler("close", self, instanceServer)); - instanceServer.on("error", _handler("error", self, instanceServer)); - instanceServer.on("timeout", _handler("timeout", self, instanceServer)); - - // Set any tags on the instance server - instanceServer.name = ismaster.me; - instanceServer.tags = ismaster.tags; - - // Add the server to the list - self._state.addServer(instanceServer, ismaster); - - // Check if we have more servers to add (only check when done with initial set) - if(candidateServers.length == 0) { - // Get additional new servers that are not currently in set - var new_servers = locateNewServers(self, self._state, candidateServers, ismaster); - - // Locate any new servers that have not errored out yet - for(var i = 0; i < new_servers.length; i++) { - if(self._state.errors[new_servers[i].name] == null) { - candidateServers.push(new_servers[i]) - } - } - } - } - - // If the candidate server list is empty and no valid servers - if(candidateServers.length == 0 && - !self._state.hasValidServers()) { - return self.emit("connectionError", new Error("No valid replicaset instance servers found")); - } else if(candidateServers.length == 0) { - if(!self.options.connectWithNoPrimary && (self._state.master == null || !self._state.master.isConnected())) { - return self.emit("connectionError", new Error("No primary found in set")); - } - return self.emit("fullsetup", null, self.options.db, self); - } - - // Let's connect the next server - var nextServer = candidateServers.pop(); - - // Set up the options - var opts = { - returnIsMasterResults: true, - eventReceiver: nextServer - } - - // Attempt to connect to the server - nextServer.connect(self.options.db, opts, _connectHandler(self, candidateServers, nextServer)); - } -} - -ReplSet.prototype.isDestroyed = function() { - return this._serverState == ReplSet.REPLSET_DESTROYED; -} - -ReplSet.prototype.isConnected = function(read) { - var isConnected = false; - - if(read == null || read == ReadPreference.PRIMARY || read == false) - isConnected = this._state.master != null && this._state.master.isConnected(); - - if((read == ReadPreference.PRIMARY_PREFERRED || read == ReadPreference.SECONDARY_PREFERRED || read == ReadPreference.NEAREST) - && ((this._state.master != null && this._state.master.isConnected()) - || (this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0))) { - isConnected = true; - } else if(read == ReadPreference.SECONDARY) { - isConnected = this._state && this._state.secondaries && Object.keys(this._state.secondaries).length > 0; - } - - // No valid connection return false - return isConnected; -} - -ReplSet.prototype.isMongos = function() { - return false; -} - -ReplSet.prototype.checkoutWriter = function() { - if(this._state.master) return this._state.master.checkoutWriter(); - return new Error("no writer connection available"); -} - -ReplSet.prototype.processIsMaster = function(_server, _ismaster) { - // Server in recovery mode, remove it from available servers - if(!_ismaster.ismaster && !_ismaster.secondary) { - // Locate the actual server - var server = this._state.addresses[_server.name]; - // Close the server, simulating the closing of the connection - // to get right removal semantics - if(server) server.close(); - // Execute any callback errors - _handler(null, this, server)(new Error("server is in recovery mode")); - } -} - -ReplSet.prototype.allRawConnections = function() { - var connections = []; - - for(var name in this._state.addresses) { - connections = connections.concat(this._state.addresses[name].allRawConnections()); - } - - return connections; -} - -/** - * @ignore - */ -ReplSet.prototype.allServerInstances = function() { - var self = this; - // If no state yet return empty - if(!self._state) return []; - // Close all the servers (concatenate entire list of servers first for ease) - var allServers = self._state.master != null ? [self._state.master] : []; - - // Secondary keys - var keys = Object.keys(self._state.secondaries); - // Add all secondaries - for(var i = 0; i < keys.length; i++) { - allServers.push(self._state.secondaries[keys[i]]); - } - - // Return complete list of all servers - return allServers; -} - -/** - * @ignore - */ -ReplSet.prototype.checkoutReader = function(readPreference, tags) { - var connection = null; - - // If we have a read preference object unpack it - if(typeof readPreference == 'object' && readPreference['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!readPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + readPreference.mode); - // Set the tag - tags = readPreference.tags; - readPreference = readPreference.mode; - } else if(typeof readPreference == 'object' && readPreference['_type'] != 'ReadPreference') { - return new Error("read preferences must be either a string or an instance of ReadPreference"); - } - - // Set up our read Preference, allowing us to override the readPreference - var finalReadPreference = readPreference != null ? readPreference : this.options.readPreference; - - // Ensure we unpack a reference - if(finalReadPreference != null && typeof finalReadPreference == 'object' && finalReadPreference['_type'] == 'ReadPreference') { - // Validate if the object is using a valid mode - if(!finalReadPreference.isValid()) throw new Error("Illegal readPreference mode specified, " + finalReadPreference.mode); - // Set the tag - tags = finalReadPreference.tags; - readPreference = finalReadPreference.mode; - } - - // Finalize the read preference setup - finalReadPreference = finalReadPreference == true ? ReadPreference.SECONDARY_PREFERRED : finalReadPreference; - finalReadPreference = finalReadPreference == null ? ReadPreference.PRIMARY : finalReadPreference; - - // If we are reading from a primary - if(finalReadPreference == 'primary') { - // If we provide a tags set send an error - if(typeof tags == 'object' && tags != null) { - return new Error("PRIMARY cannot be combined with tags"); - } - - // If we provide a tags set send an error - if(this._state.master == null) { - return new Error("No replica set primary available for query with ReadPreference PRIMARY"); - } - - // Checkout a writer - return this.checkoutWriter(); - } - - // If we have specified to read from a secondary server grab a random one and read - // from it, otherwise just pass the primary connection - if((this.options.readSecondary || finalReadPreference == ReadPreference.SECONDARY_PREFERRED || finalReadPreference == ReadPreference.SECONDARY) && Object.keys(this._state.secondaries).length > 0) { - // If we have tags, look for servers matching the specific tag - if(this.strategyInstance != null) { - // Only pick from secondaries - var _secondaries = []; - for(var key in this._state.secondaries) { - _secondaries.push(this._state.secondaries[key]); - } - - if(finalReadPreference == ReadPreference.SECONDARY) { - // Check out the nearest from only the secondaries - connection = this.strategyInstance.checkoutConnection(tags, _secondaries); - } else { - connection = this.strategyInstance.checkoutConnection(tags, _secondaries); - // No candidate servers that match the tags, error - if(connection == null || connection instanceof Error) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - return new Error("No replica set members available for query"); - } - } - } - } else if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - return new Error("No replica set members available for query"); - } - } else { - connection = _roundRobin(this, tags); - } - } else if(finalReadPreference == ReadPreference.PRIMARY_PREFERRED) { - // Check if there is a primary available and return that if possible - connection = this.checkoutWriter(); - // If no connection available checkout a secondary - if(connection == null || connection instanceof Error) { - // If we have tags, look for servers matching the specific tag - if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - return new Error("No replica set members available for query"); - } - } else { - connection = _roundRobin(this, tags); - } - } - } else if(finalReadPreference == ReadPreference.SECONDARY_PREFERRED) { - // If we have tags, look for servers matching the specific tag - if(this.strategyInstance != null) { - connection = this.strategyInstance.checkoutConnection(tags); - - // No candidate servers that match the tags, error - if(connection == null || connection instanceof Error) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } - } - } else if(tags != null && typeof tags == 'object') { - // Get connection - connection = _pickFromTags(this, tags);// = function(self, readPreference, tags) { - // No candidate servers that match the tags, error - if(connection == null) { - // No secondary server avilable, attemp to checkout a primary server - connection = this.checkoutWriter(); - // If no connection return an error - if(connection == null || connection instanceof Error) { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } - } - } - } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance != null) { - connection = this.strategyInstance.checkoutConnection(tags); - } else if(finalReadPreference == ReadPreference.NEAREST && this.strategyInstance == null) { - return new Error("A strategy for calculating nearness must be enabled such as ping or statistical"); - } else if(finalReadPreference == ReadPreference.SECONDARY && Object.keys(this._state.secondaries).length == 0) { - if(tags != null && typeof tags == 'object') { - var preferenceName = finalReadPreference == ReadPreference.SECONDARY ? 'secondary' : finalReadPreference; - return new Error("No replica set member available for query with ReadPreference " + preferenceName + " and tags " + JSON.stringify(tags)); - } else { - return new Error("No replica set secondary available for query with ReadPreference SECONDARY"); - } - } else { - connection = this.checkoutWriter(); - } - - // Return the connection - return connection; -} - -/** - * @ignore - */ -var _pickFromTags = function(self, tags) { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Match all the servers that match the provdided tags - var keys = Object.keys(self._state.secondaries); - var candidateServers = []; - - for(var i = 0; i < keys.length; i++) { - var server = self._state.secondaries[keys[i]]; - // If we have tags match - if(server.tags != null) { - var matching = true; - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - candidateServers.push(server); - } - } - } - - // If we have a candidate server return - if(candidateServers.length > 0) { - if(self.strategyInstance) return self.strategyInstance.checkoutConnection(tags, candidateServers); - // Set instance to return - return candidateServers[Math.floor(Math.random() * candidateServers.length)].checkoutReader(); - } - } - - // No connection found - return null; -} - -/** - * Pick a secondary using round robin - * - * @ignore - */ -function _roundRobin (replset, tags) { - var keys = Object.keys(replset._state.secondaries); - // Update index - replset._currentServerChoice = replset._currentServerChoice + 1; - // Pick a server - var key = keys[replset._currentServerChoice % keys.length]; - - var conn = null != replset._state.secondaries[key] - ? replset._state.secondaries[key].checkoutReader() - : null; - - // If connection is null fallback to first available secondary - if(null == conn) { - conn = pickFirstConnectedSecondary(replset, tags); - } - - return conn; -} - -/** - * @ignore - */ -var pickFirstConnectedSecondary = function pickFirstConnectedSecondary(self, tags) { - var keys = Object.keys(self._state.secondaries); - var connection; - - // Find first available reader if any - for(var i = 0; i < keys.length; i++) { - connection = self._state.secondaries[keys[i]].checkoutReader(); - if(connection) return connection; - } - - // If we still have a null, read from primary if it's not secondary only - if(self._readPreference == ReadPreference.SECONDARY_PREFERRED) { - connection = self._state.master.checkoutReader(); - if(connection) return connection; - } - - var preferenceName = self._readPreference == ReadPreference.SECONDARY_PREFERRED - ? 'secondary' - : self._readPreference; - - return new Error("No replica set member available for query with ReadPreference " - + preferenceName + " and tags " + JSON.stringify(tags)); -} - -/** - * Get list of secondaries - * @ignore - */ -Object.defineProperty(ReplSet.prototype, "secondaries", {enumerable: true - , get: function() { - return utils.objectToArray(this._state.secondaries); - } -}); - -/** - * Get list of secondaries - * @ignore - */ -Object.defineProperty(ReplSet.prototype, "arbiters", {enumerable: true - , get: function() { - return utils.objectToArray(this._state.arbiters); - } -}); - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js deleted file mode 100644 index 6f9e14327..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/repl_set_state.js +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Interval state object constructor - * - * @ignore - */ -var ReplSetState = function ReplSetState () { - this.errorMessages = []; - this.secondaries = {}; - this.addresses = {}; - this.arbiters = {}; - this.passives = {}; - this.members = []; - this.errors = {}; - this.setName = null; - this.master = null; -} - -ReplSetState.prototype.hasValidServers = function() { - var validServers = []; - if(this.master && this.master.isConnected()) return true; - - if(this.secondaries) { - var keys = Object.keys(this.secondaries) - for(var i = 0; i < keys.length; i++) { - if(this.secondaries[keys[i]].isConnected()) - return true; - } - } - - return false; -} - -ReplSetState.prototype.getAllReadServers = function() { - var candidate_servers = []; - for(var name in this.addresses) { - candidate_servers.push(this.addresses[name]); - } - - // Return all possible read candidates - return candidate_servers; -} - -ReplSetState.prototype.addServer = function(server, master) { - server.name = master.me; - - if(master.ismaster) { - this.master = server; - this.addresses[server.name] = server; - } else if(master.secondary) { - this.secondaries[server.name] = server; - this.addresses[server.name] = server; - } else if(master.arbiters) { - this.arbiters[server.name] = server; - this.addresses[server.name] = server; - } -} - -ReplSetState.prototype.contains = function(host) { - return this.addresses[host] != null; -} - -ReplSetState.prototype.isPrimary = function(server) { - return this.master && this.master.name == server.name; -} - -ReplSetState.prototype.isSecondary = function(server) { - return this.secondaries[server.name] != null; -} - -exports.ReplSetState = ReplSetState; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js deleted file mode 100644 index 76990e2e0..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/ping_strategy.js +++ /dev/null @@ -1,333 +0,0 @@ -var Server = require("../../server").Server - , format = require('util').format; - -// The ping strategy uses pings each server and records the -// elapsed time for the server so it can pick a server based on lowest -// return time for the db command {ping:true} -var PingStrategy = exports.PingStrategy = function(replicaset, secondaryAcceptableLatencyMS) { - this.replicaset = replicaset; - this.secondaryAcceptableLatencyMS = secondaryAcceptableLatencyMS; - this.state = 'disconnected'; - this.pingInterval = 5000; - // Class instance - this.Db = require("../../../db").Db; - // Active db connections - this.dbs = {}; - // Current server index - this.index = 0; - // Logger api - this.Logger = null; -} - -// Starts any needed code -PingStrategy.prototype.start = function(callback) { - // already running? - if ('connected' == this.state) return; - - this.state = 'connected'; - - // Start ping server - this._pingServer(callback); -} - -// Stops and kills any processes running -PingStrategy.prototype.stop = function(callback) { - // Stop the ping process - this.state = 'disconnected'; - - // Stop all the server instances - for(var key in this.dbs) { - this.dbs[key].close(); - } - - // optional callback - callback && callback(null, null); -} - -PingStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) { - // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS - // Create a list of candidat servers, containing the primary if available - var candidateServers = []; - var self = this; - - // If we have not provided a list of candidate servers use the default setup - if(!Array.isArray(secondaryCandidates)) { - candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : []; - // Add all the secondaries - var keys = Object.keys(this.replicaset._state.secondaries); - for(var i = 0; i < keys.length; i++) { - candidateServers.push(this.replicaset._state.secondaries[keys[i]]) - } - } else { - candidateServers = secondaryCandidates; - } - - // Final list of eligable server - var finalCandidates = []; - - // If we have tags filter by tags - if(tags != null && typeof tags == 'object') { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Remove any that are not tagged correctly - for(var i = 0; i < candidateServers.length; i++) { - var server = candidateServers[i]; - // If we have tags match - if(server.tags != null) { - var matching = true; - - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - finalCandidates.push(server); - } - } - } - } - } else { - // Final array candidates - var finalCandidates = candidateServers; - } - - // Sort by ping time - finalCandidates.sort(function(a, b) { - return a.runtimeStats['pingMs'] > b.runtimeStats['pingMs']; - }); - - if(0 === finalCandidates.length) - return new Error("No replica set members available for query"); - - // find lowest server with a ping time - var lowest = finalCandidates.filter(function (server) { - return undefined != server.runtimeStats.pingMs; - })[0]; - - if(!lowest) { - lowest = finalCandidates[0]; - } - - // convert to integer - var lowestPing = lowest.runtimeStats.pingMs | 0; - - // determine acceptable latency - var acceptable = lowestPing + this.secondaryAcceptableLatencyMS; - - // remove any server responding slower than acceptable - var len = finalCandidates.length; - while(len--) { - if(finalCandidates[len].runtimeStats['pingMs'] > acceptable) { - finalCandidates.splice(len, 1); - } - } - - if(self.logger && self.logger.debug) { - self.logger.debug("Ping strategy selection order for tags", tags); - finalCandidates.forEach(function(c) { - self.logger.debug(format("%s:%s = %s ms", c.host, c.port, c.runtimeStats['pingMs']), null); - }) - } - - // If no candidates available return an error - if(finalCandidates.length == 0) - return new Error("No replica set members available for query"); - - // Ensure no we don't overflow - this.index = this.index % finalCandidates.length - // Pick a random acceptable server - var connection = finalCandidates[this.index].checkoutReader(); - // Point to next candidate (round robin style) - this.index = this.index + 1; - - if(self.logger && self.logger.debug) { - if(connection) - self.logger.debug("picked server %s:%s", connection.socketOptions.host, connection.socketOptions.port); - } - - return connection; -} - -PingStrategy.prototype._pingServer = function(callback) { - var self = this; - - // Ping server function - var pingFunction = function() { - // Our state changed to disconnected or destroyed return - if(self.state == 'disconnected' || self.state == 'destroyed') return; - // If the replicaset is destroyed return - if(self.replicaset.isDestroyed() || self.replicaset._serverState == 'disconnected') return - - // Create a list of all servers we can send the ismaster command to - var allServers = self.replicaset._state.master != null ? [self.replicaset._state.master] : []; - - // Secondary keys - var keys = Object.keys(self.replicaset._state.secondaries); - // Add all secondaries - for(var i = 0; i < keys.length; i++) { - allServers.push(self.replicaset._state.secondaries[keys[i]]); - } - - // Number of server entries - var numberOfEntries = allServers.length; - - // We got keys - for(var i = 0; i < allServers.length; i++) { - - // We got a server instance - var server = allServers[i]; - - // Create a new server object, avoid using internal connections as they might - // be in an illegal state - new function(serverInstance) { - var _db = self.dbs[serverInstance.host + ":" + serverInstance.port]; - // If we have a db - if(_db != null) { - // Startup time of the command - var startTime = Date.now(); - - // Execute ping command in own scope - var _ping = function(__db, __serverInstance) { - // Execute ping on this connection - __db.executeDbCommand({ping:1}, {failFast:true}, function(err) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime; - } - - __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Process the ismaster for the server - if(result && result.documents && self.replicaset.processIsMaster) { - self.replicaset.processIsMaster(__serverInstance, result.documents[0]); - } - - // Done with the pinging - done(); - }); - }); - }; - // Ping - _ping(_db, serverInstance); - } else { - var connectTimeoutMS = self.replicaset.options.socketOptions - ? self.replicaset.options.socketOptions.connectTimeoutMS : 0 - - // Create a new master connection - var _server = new Server(serverInstance.host, serverInstance.port, { - auto_reconnect: false, - returnIsMasterResults: true, - slaveOk: true, - poolSize: 1, - socketOptions: { connectTimeoutMS: connectTimeoutMS }, - ssl: self.replicaset.ssl, - sslValidate: self.replicaset.sslValidate, - sslCA: self.replicaset.sslCA, - sslCert: self.replicaset.sslCert, - sslKey: self.replicaset.sslKey, - sslPass: self.replicaset.sslPass - }); - - // Create Db instance - var _db = new self.Db('local', _server, { safe: true }); - _db.on("close", function() { - delete self.dbs[this.serverConfig.host + ":" + this.serverConfig.port]; - }) - - var _ping = function(__db, __serverInstance) { - if(self.state == 'disconnected') { - self.stop(); - return; - } - - __db.open(function(err, db) { - if(self.state == 'disconnected' && __db != null) { - return __db.close(); - } - - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Save instance - self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port] = __db; - - // Startup time of the command - var startTime = Date.now(); - - // Execute ping on this connection - __db.executeDbCommand({ping:1}, {failFast:true}, function(err) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - if(null != __serverInstance.runtimeStats && __serverInstance.isConnected()) { - __serverInstance.runtimeStats['pingMs'] = Date.now() - startTime; - } - - __db.executeDbCommand({ismaster:1}, {failFast:true}, function(err, result) { - if(err) { - delete self.dbs[__db.serverConfig.host + ":" + __db.serverConfig.port]; - __db.close(); - return done(); - } - - // Process the ismaster for the server - if(result && result.documents && self.replicaset.processIsMaster) { - self.replicaset.processIsMaster(__serverInstance, result.documents[0]); - } - - // Done with the pinging - done(); - }); - }); - }); - }; - - // Ping the server - _ping(_db, serverInstance); - } - - function done() { - // Adjust the number of checks - numberOfEntries--; - - // If we are done with all results coming back trigger ping again - if(0 === numberOfEntries && 'connected' == self.state) { - setTimeout(pingFunction, self.pingInterval); - } - } - }(server); - } - } - - // Start pingFunction - pingFunction(); - - callback && callback(null); -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js deleted file mode 100644 index f9b8c4643..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/repl_set/strategies/statistics_strategy.js +++ /dev/null @@ -1,80 +0,0 @@ -// The Statistics strategy uses the measure of each end-start time for each -// query executed against the db to calculate the mean, variance and standard deviation -// and pick the server which the lowest mean and deviation -var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) { - this.replicaset = replicaset; - // Logger api - this.Logger = null; -} - -// Starts any needed code -StatisticsStrategy.prototype.start = function(callback) { - callback && callback(null, null); -} - -StatisticsStrategy.prototype.stop = function(callback) { - callback && callback(null, null); -} - -StatisticsStrategy.prototype.checkoutConnection = function(tags, secondaryCandidates) { - // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS - // Create a list of candidat servers, containing the primary if available - var candidateServers = []; - - // If we have not provided a list of candidate servers use the default setup - if(!Array.isArray(secondaryCandidates)) { - candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : []; - // Add all the secondaries - var keys = Object.keys(this.replicaset._state.secondaries); - for(var i = 0; i < keys.length; i++) { - candidateServers.push(this.replicaset._state.secondaries[keys[i]]) - } - } else { - candidateServers = secondaryCandidates; - } - - // Final list of eligable server - var finalCandidates = []; - - // If we have tags filter by tags - if(tags != null && typeof tags == 'object') { - // If we have an array or single tag selection - var tagObjects = Array.isArray(tags) ? tags : [tags]; - // Iterate over all tags until we find a candidate server - for(var _i = 0; _i < tagObjects.length; _i++) { - // Grab a tag object - var tagObject = tagObjects[_i]; - // Matching keys - var matchingKeys = Object.keys(tagObject); - // Remove any that are not tagged correctly - for(var i = 0; i < candidateServers.length; i++) { - var server = candidateServers[i]; - // If we have tags match - if(server.tags != null) { - var matching = true; - - // Ensure we have all the values - for(var j = 0; j < matchingKeys.length; j++) { - if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) { - matching = false; - break; - } - } - - // If we have a match add it to the list of matching servers - if(matching) { - finalCandidates.push(server); - } - } - } - } - } else { - // Final array candidates - var finalCandidates = candidateServers; - } - - // If no candidates available return an error - if(finalCandidates.length == 0) return new Error("No replica set members available for query"); - // Pick a random server - return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader(); -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/server.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/server.js deleted file mode 100644 index f80f6f628..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/server.js +++ /dev/null @@ -1,919 +0,0 @@ -var Connection = require('./connection').Connection, - ReadPreference = require('./read_preference').ReadPreference, - DbCommand = require('../commands/db_command').DbCommand, - MongoReply = require('../responses/mongo_reply').MongoReply, - ConnectionPool = require('./connection_pool').ConnectionPool, - EventEmitter = require('events').EventEmitter, - Base = require('./base').Base, - format = require('util').format, - utils = require('../utils'), - timers = require('timers'), - inherits = require('util').inherits; - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * Class representing a single MongoDB Server connection - * - * Options - * - **readPreference** {String, default:null}, set's the read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST) - * - **ssl** {Boolean, default:false}, use ssl connection (needs to have a mongod server with ssl support) - * - **sslValidate** {Boolean, default:false}, validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCA** {Array, default:null}, Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslCert** {Buffer/String, default:null}, String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslKey** {Buffer/String, default:null}, String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * - **sslPass** {Buffer/String, default:null}, String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * - **poolSize** {Number, default:5}, number of connections in the connection pool, set to 5 as default for legacy reasons. - * - **socketOptions** {Object, default:null}, an object containing socket options to use (noDelay:(boolean), keepAlive:(number), connectTimeoutMS:(number), socketTimeoutMS:(number)) - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **auto_reconnect** {Boolean, default:false}, reconnect on error. - * - **disableDriverBSONSizeCheck** {Boolean, default:false}, force the server to error if the BSON message is to big - * - * @class Represents a Server connection. - * @param {String} host the server host - * @param {Number} port the server port - * @param {Object} [options] optional options for insert command - */ -function Server(host, port, options) { - // Set up Server instance - if(!(this instanceof Server)) return new Server(host, port, options); - - // Set up event emitter - Base.call(this); - - // Ensure correct values - if(port != null && typeof port == 'object') { - options = port; - port = Connection.DEFAULT_PORT; - } - - var self = this; - this.host = host; - this.port = port; - this.options = options == null ? {} : options; - this.internalConnection; - this.internalMaster = false; - this.connected = false; - this.poolSize = this.options.poolSize == null ? 5 : this.options.poolSize; - this.disableDriverBSONSizeCheck = this.options.disableDriverBSONSizeCheck != null ? this.options.disableDriverBSONSizeCheck : false; - this._used = false; - this.replicasetInstance = null; - - // Emit open setup - this.emitOpen = this.options.emitOpen || true; - // Set ssl as connection method - this.ssl = this.options.ssl == null ? false : this.options.ssl; - // Set ssl validation - this.sslValidate = this.options.sslValidate == null ? false : this.options.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.sslCA = Array.isArray(this.options.sslCA) ? this.options.sslCA : null; - // Certificate to present to the server - this.sslCert = this.options.sslCert; - // Certificate private key if in separate file - this.sslKey = this.options.sslKey; - // Password to unlock private key - this.sslPass = this.options.sslPass; - // Set server name - this.name = format("%s:%s", host, port); - - // Ensure we are not trying to validate with no list of certificates - if(this.sslValidate && (!Array.isArray(this.sslCA) || this.sslCA.length == 0)) { - throw new Error("The driver expects an Array of CA certificates in the sslCA parameter when enabling sslValidate"); - } - - // Get the readPreference - var readPreference = this.options['readPreference']; - // If readPreference is an object get the mode string - var validateReadPreference = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference; - // Read preference setting - if(validateReadPreference != null) { - if(validateReadPreference != ReadPreference.PRIMARY && validateReadPreference != ReadPreference.SECONDARY && validateReadPreference != ReadPreference.NEAREST - && validateReadPreference != ReadPreference.SECONDARY_PREFERRED && validateReadPreference != ReadPreference.PRIMARY_PREFERRED) { - throw new Error("Illegal readPreference mode specified, " + validateReadPreference); - } - - // Set read Preference - this._readPreference = readPreference; - } else { - this._readPreference = null; - } - - // Contains the isMaster information returned from the server - this.isMasterDoc; - - // Set default connection pool options - this.socketOptions = this.options.socketOptions != null ? this.options.socketOptions : {}; - if(this.disableDriverBSONSizeCheck) this.socketOptions.disableDriverBSONSizeCheck = this.disableDriverBSONSizeCheck; - - // Set ssl up if it's defined - if(this.ssl) { - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = this.sslCert; - // Set certificate to present - this.socketOptions.sslKey = this.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = this.sslPass; - } - - // Set up logger if any set - this.logger = this.options.logger != null - && (typeof this.options.logger.debug == 'function') - && (typeof this.options.logger.error == 'function') - && (typeof this.options.logger.log == 'function') - ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[], timeout:[]}; - // Internal state of server connection - this._serverState = 'disconnected'; - // Contains state information about server connection - this._state = {'runtimeStats': {'queryStats':new RunningStats()}}; - // Do we record server stats or not - this.recordQueryStats = false; -}; - -/** - * @ignore - */ -inherits(Server, Base); - -// -// Deprecated, USE ReadPreferences class -// -Server.READ_PRIMARY = ReadPreference.PRIMARY; -Server.READ_SECONDARY = ReadPreference.SECONDARY_PREFERRED; -Server.READ_SECONDARY_ONLY = ReadPreference.SECONDARY; - -/** - * Always ourselves - * @ignore - */ -Server.prototype.setReadPreference = function(readPreference) { - this._readPreference = readPreference; -} - -/** - * @ignore - */ -Server.prototype.isMongos = function() { - return this.isMasterDoc != null && this.isMasterDoc['msg'] == "isdbgrid" ? true : false; -} - -/** - * @ignore - */ -Server.prototype._isUsed = function() { - return this._used; -} - -/** - * @ignore - */ -Server.prototype.close = function(callback) { - // Set server status as disconnected - this._serverState = 'destroyed'; - // Remove all local listeners - this.removeAllListeners(); - - if(this.connectionPool != null) { - // Remove all the listeners on the pool so it does not fire messages all over the place - this.connectionPool.removeAllEventListeners(); - // Close the connection if it's open - this.connectionPool.stop(true); - } - - // Emit close event - if(this.db && !this.isSetMember()) { - var self = this; - processor(function() { - self._emitAcrossAllDbInstances(self, null, "close", null, null, true) - }) - } - - // Peform callback if present - if(typeof callback === 'function') callback(null); -}; - -Server.prototype.isDestroyed = function() { - return this._serverState == 'destroyed'; -} - -/** - * @ignore - */ -Server.prototype.isConnected = function() { - return this.connectionPool != null && this.connectionPool.isConnected(); -} - -/** - * @ignore - */ -Server.prototype.canWrite = Server.prototype.isConnected; -Server.prototype.canRead = Server.prototype.isConnected; - -Server.prototype.isAutoReconnect = function() { - if(this.isSetMember()) return false; - return this.options.auto_reconnect != null ? this.options.auto_reconnect : true; -} - -/** - * @ignore - */ -Server.prototype.allServerInstances = function() { - return [this]; -} - -/** - * @ignore - */ -Server.prototype.isSetMember = function() { - return this.replicasetInstance != null || this.mongosInstance != null; -} - -/** - * Assigns a replica set to this `server`. - * - * @param {ReplSet} replset - * @ignore - */ -Server.prototype.assignReplicaSet = function (replset) { - this.replicasetInstance = replset; - this.inheritReplSetOptionsFrom(replset); - this.enableRecordQueryStats(replset.recordQueryStats); -} - -/** - * Takes needed options from `replset` and overwrites - * our own options. - * - * @param {ReplSet} replset - * @ignore - */ -Server.prototype.inheritReplSetOptionsFrom = function (replset) { - this.socketOptions = {}; - this.socketOptions.connectTimeoutMS = replset.options.socketOptions.connectTimeoutMS || 30000; - - if(replset.options.ssl) { - // Set ssl on - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = replset.options.sslValidate == null ? false : replset.options.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(replset.options.sslCA) ? replset.options.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = replset.options.sslCert; - // Set certificate to present - this.socketOptions.sslKey = replset.options.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = replset.options.sslPass; - } - - // If a socket option object exists clone it - if(utils.isObject(replset.options.socketOptions)) { - var keys = Object.keys(replset.options.socketOptions); - for(var i = 0; i < keys.length; i++) - this.socketOptions[keys[i]] = replset.options.socketOptions[keys[i]]; - } -} - -/** - * Opens this server connection. - * - * @ignore - */ -Server.prototype.connect = function(dbInstance, options, callback) { - if('function' === typeof options) callback = options, options = {}; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - var self = this; - // Save the options - this.options = options; - - // Currently needed to work around problems with multiple connections in a pool with ssl - // TODO fix if possible - if(this.ssl == true) { - // Set up socket options for ssl - this.socketOptions.ssl = true; - // Set ssl validation - this.socketOptions.sslValidate = this.sslValidate == null ? false : this.sslValidate; - // Set the ssl certificate authority (array of Buffer/String keys) - this.socketOptions.sslCA = Array.isArray(this.sslCA) ? this.sslCA : null; - // Set certificate to present - this.socketOptions.sslCert = this.sslCert; - // Set certificate to present - this.socketOptions.sslKey = this.sslKey; - // Password to unlock private key - this.socketOptions.sslPass = this.sslPass; - } - - // Let's connect - var server = this; - // Let's us override the main receiver of events - var eventReceiver = options.eventReceiver != null ? options.eventReceiver : this; - // Save reference to dbInstance - this.db = dbInstance; // `db` property matches ReplSet and Mongos - this.dbInstances = [dbInstance]; - - // Force connection pool if there is one - if(server.connectionPool) server.connectionPool.stop(); - // Set server state to connecting - this._serverState = 'connecting'; - - if(server.connectionPool != null) { - // Remove all the listeners on the pool so it does not fire messages all over the place - this.connectionPool.removeAllEventListeners(); - // Close the connection if it's open - this.connectionPool.stop(true); - } - - this.connectionPool = new ConnectionPool(this.host, this.port, this.poolSize, dbInstance.bson, this.socketOptions); - var connectionPool = this.connectionPool; - // If ssl is not enabled don't wait between the pool connections - if(this.ssl == null || !this.ssl) connectionPool._timeToWait = null; - // Set logger on pool - connectionPool.logger = this.logger; - connectionPool.bson = dbInstance.bson; - - // Set basic parameters passed in - var returnIsMasterResults = options.returnIsMasterResults == null ? false : options.returnIsMasterResults; - - // Create a default connect handler, overriden when using replicasets - var connectCallback = function(_server) { - return function(err, reply) { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - - // Assign the server - _server = _server != null ? _server : server; - - // If something close down the connection and removed the callback before - // proxy killed connection etc, ignore the erorr as close event was isssued - if(err != null && internalCallback == null) return; - // Internal callback - if(err != null) return internalCallback(err, null, _server); - _server.master = reply.documents[0].ismaster == 1 ? true : false; - _server.connectionPool.setMaxBsonSize(reply.documents[0].maxBsonObjectSize); - _server.connectionPool.setMaxMessageSizeBytes(reply.documents[0].maxMessageSizeBytes); - // Set server state to connEcted - _server._serverState = 'connected'; - // Set server as connected - _server.connected = true; - // Save document returned so we can query it - _server.isMasterDoc = reply.documents[0]; - - if(self.emitOpen) { - _server._emitAcrossAllDbInstances(_server, eventReceiver, "open", null, returnIsMasterResults ? reply : null, null); - self.emitOpen = false; - } else { - _server._emitAcrossAllDbInstances(_server, eventReceiver, "reconnect", null, returnIsMasterResults ? reply : null, null); - } - - // If we have it set to returnIsMasterResults - if(returnIsMasterResults) { - internalCallback(null, reply, _server); - } else { - internalCallback(null, dbInstance, _server); - } - } - }; - - // Let's us override the main connect callback - var connectHandler = options.connectHandler == null ? connectCallback(server) : options.connectHandler; - - // Set up on connect method - connectionPool.on("poolReady", function() { - // Create db command and Add the callback to the list of callbacks by the request id (mapping outgoing messages to correct callbacks) - var db_command = DbCommand.NcreateIsMasterCommand(dbInstance, dbInstance.databaseName); - // Check out a reader from the pool - var connection = connectionPool.checkoutConnection(); - // Register handler for messages - server._registerHandler(db_command, false, connection, connectHandler); - // Write the command out - connection.write(db_command); - }) - - // Set up item connection - connectionPool.on("message", function(message) { - // Attempt to parse the message - try { - // Create a new mongo reply - var mongoReply = new MongoReply() - // Parse the header - mongoReply.parseHeader(message, connectionPool.bson) - - // If message size is not the same as the buffer size - // something went terribly wrong somewhere - if(mongoReply.messageLength != message.length) { - // Emit the error - if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", new Error("bson length is different from message length"), server); - // Remove all listeners - server.removeAllListeners(); - } else { - var startDate = new Date().getTime(); - - // Callback instance - var callbackInfo = server._findHandler(mongoReply.responseTo.toString()); - - // The command executed another request, log the handler again under that request id - if(mongoReply.requestId > 0 && mongoReply.cursorId.toString() != "0" - && callbackInfo && callbackInfo.info && callbackInfo.info.exhaust) { - server._reRegisterHandler(mongoReply.requestId, callbackInfo); - } - // Parse the body - mongoReply.parseBody(message, connectionPool.bson, callbackInfo.info.raw, function(err) { - if(err != null) { - // If pool connection is already closed - if(server._serverState === 'disconnected') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // Remove all listeners and close the connection pool - server.removeAllListeners(); - connectionPool.stop(true); - - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(new Error("connection closed due to parseError"), null, server); - } else if(server.isSetMember()) { - if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", new Error("connection closed due to parseError"), server); - } else { - if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", new Error("connection closed due to parseError"), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(new Error("connection closed due to parseError")); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true); - } - // Short cut - return; - } - - // Let's record the stats info if it's enabled - if(server.recordQueryStats == true && server._state['runtimeStats'] != null - && server._state.runtimeStats['queryStats'] instanceof RunningStats) { - // Add data point to the running statistics object - server._state.runtimeStats.queryStats.push(new Date().getTime() - callbackInfo.info.start); - } - - // Dispatch the call - server._callHandler(mongoReply.responseTo, mongoReply, null); - - // If we have an error about the server not being master or primary - if((mongoReply.responseFlag & (1 << 1)) != 0 - && mongoReply.documents[0].code - && mongoReply.documents[0].code == 13436) { - server.close(); - } - }); - } - } catch (err) { - // Throw error in next tick - processor(function() { - throw err; - }) - } - }); - - // Handle timeout - connectionPool.on("timeout", function(err) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(err, null, server); - } else if(server.isSetMember()) { - if(server.listeners("timeout") && server.listeners("timeout").length > 0) server.emit("timeout", err, server); - } else { - if(eventReceiver.listeners("timeout") && eventReceiver.listeners("timeout").length > 0) eventReceiver.emit("timeout", err, server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(err); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "timeout", err, server, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - // Handle errors - connectionPool.on("error", function(message, connection, error_options) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - - // Set server state to disconnected - server._serverState = 'disconnected'; - // Error message - var error_message = new Error(message && message.err ? message.err : message); - // Error message coming from ssl - if(error_options && error_options.ssl) error_message.ssl = true; - - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(error_message, null, server); - } else if(server.isSetMember()) { - if(server.listeners("error") && server.listeners("error").length > 0) server.emit("error", error_message, server); - } else { - if(eventReceiver.listeners("error") && eventReceiver.listeners("error").length > 0) eventReceiver.emit("error", error_message, server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(error_message); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "error", error_message, server, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - // Handle close events - connectionPool.on("close", function() { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback == 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(new Error("connection closed"), null, server); - } else if(server.isSetMember()) { - if(server.listeners("close") && server.listeners("close").length > 0) server.emit("close", new Error("connection closed"), server); - } else { - if(eventReceiver.listeners("close") && eventReceiver.listeners("close").length > 0) eventReceiver.emit("close", new Error("connection closed"), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(new Error("connection closed")); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "close", server, null, true); - } - - // If we have autoConnect enabled let's fire up an attempt to reconnect - if(server.isAutoReconnect() - && !server.isSetMember() - && (server._serverState != 'destroyed') - && !server._reconnectInProgreess) { - - // Set the number of retries - server._reconnect_retries = server.db.numberOfRetries; - // Attempt reconnect - server._reconnectInProgreess = true; - setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - }); - - /** - * @ignore - */ - var __attemptReconnect = function(server) { - return function() { - // Attempt reconnect - server.connect(server.db, server.options, function(err, result) { - server._reconnect_retries = server._reconnect_retries - 1; - - if(err) { - // Retry - if(server._reconnect_retries == 0 || server._serverState == 'destroyed') { - server._serverState = 'connected'; - server._reconnectInProgreess = false - // Fire all callback errors - return server.__executeAllCallbacksWithError(new Error("failed to reconnect to server")); - } else { - return setTimeout(__attemptReconnect(server), server.db.retryMiliSeconds); - } - } else { - // Set as authenticating (isConnected will be false) - server._serverState = 'authenticating'; - // Apply any auths, we don't try to catch any errors here - // as there are nowhere to simply propagate them to - self._apply_auths(server.db, function(err, result) { - server._serverState = 'connected'; - server._reconnectInProgreess = false; - server._commandsStore.execute_queries(); - server._commandsStore.execute_writes(); - }); - } - }); - } - } - - // If we have a parser error we are in an unknown state, close everything and emit - // error - connectionPool.on("parseError", function(message) { - // If pool connection is already closed - if(server._serverState === 'disconnected' - || server._serverState === 'destroyed') return; - // Set server state to disconnected - server._serverState = 'disconnected'; - // If we have a callback return the error - if(typeof callback === 'function') { - // ensure no callbacks get called twice - var internalCallback = callback; - callback = null; - // Perform callback - internalCallback(new Error("connection closed due to parseError"), null, server); - } else if(server.isSetMember()) { - if(server.listeners("parseError") && server.listeners("parseError").length > 0) server.emit("parseError", new Error("connection closed due to parseError"), server); - } else { - if(eventReceiver.listeners("parseError") && eventReceiver.listeners("parseError").length > 0) eventReceiver.emit("parseError", new Error("connection closed due to parseError"), server); - } - - // If we are a single server connection fire errors correctly - if(!server.isSetMember()) { - // Fire all callback errors - server.__executeAllCallbacksWithError(new Error("connection closed due to parseError")); - // Emit error - server._emitAcrossAllDbInstances(server, eventReceiver, "parseError", server, null, true); - } - }); - - // Boot up connection poole, pass in a locator of callbacks - connectionPool.start(); -} - -/** - * @ignore - */ -Server.prototype.allRawConnections = function() { - return this.connectionPool.getAllConnections(); -} - -/** - * Check if a writer can be provided - * @ignore - */ -var canCheckoutWriter = function(self, read) { - // We cannot write to an arbiter or secondary server - if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) { - return new Error("Cannot write to an arbiter"); - } if(self.isMasterDoc && self.isMasterDoc['secondary'] == true) { - return new Error("Cannot write to a secondary"); - } else if(read == true && self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) { - return new Error("Cannot read from primary when secondary only specified"); - } else if(!self.isMasterDoc) { - return new Error("Cannot determine state of server"); - } - - // Return no error - return null; -} - -/** - * @ignore - */ -Server.prototype.checkoutWriter = function(read) { - if(read == true) return this.connectionPool.checkoutConnection(); - // Check if are allowed to do a checkout (if we try to use an arbiter f.ex) - var result = canCheckoutWriter(this, read); - // If the result is null check out a writer - if(result == null && this.connectionPool != null) { - return this.connectionPool.checkoutConnection(); - } else if(result == null) { - return null; - } else { - return result; - } -} - -/** - * Check if a reader can be provided - * @ignore - */ -var canCheckoutReader = function(self) { - // We cannot write to an arbiter or secondary server - if(self.isMasterDoc && self.isMasterDoc['arbiterOnly'] == true) { - return new Error("Cannot write to an arbiter"); - } else if(self._readPreference != null) { - // If the read preference is Primary and the instance is not a master return an error - if((self._readPreference == ReadPreference.PRIMARY) && self.isMasterDoc && self.isMasterDoc['ismaster'] != true) { - return new Error("Read preference is Server.PRIMARY and server is not master"); - } else if(self._readPreference == ReadPreference.SECONDARY && self.isMasterDoc && self.isMasterDoc['ismaster'] == true) { - return new Error("Cannot read from primary when secondary only specified"); - } - } else if(!self.isMasterDoc) { - return new Error("Cannot determine state of server"); - } - - // Return no error - return null; -} - -/** - * @ignore - */ -Server.prototype.checkoutReader = function(read) { - // Check if are allowed to do a checkout (if we try to use an arbiter f.ex) - var result = canCheckoutReader(this); - // If the result is null check out a writer - if(result == null && this.connectionPool != null) { - return this.connectionPool.checkoutConnection(); - } else if(result == null) { - return null; - } else { - return result; - } -} - -/** - * @ignore - */ -Server.prototype.enableRecordQueryStats = function(enable) { - this.recordQueryStats = enable; -} - -/** - * Internal statistics object used for calculating average and standard devitation on - * running queries - * @ignore - */ -var RunningStats = function() { - var self = this; - this.m_n = 0; - this.m_oldM = 0.0; - this.m_oldS = 0.0; - this.m_newM = 0.0; - this.m_newS = 0.0; - - // Define getters - Object.defineProperty(this, "numDataValues", { enumerable: true - , get: function () { return this.m_n; } - }); - - Object.defineProperty(this, "mean", { enumerable: true - , get: function () { return (this.m_n > 0) ? this.m_newM : 0.0; } - }); - - Object.defineProperty(this, "variance", { enumerable: true - , get: function () { return ((this.m_n > 1) ? this.m_newS/(this.m_n - 1) : 0.0); } - }); - - Object.defineProperty(this, "standardDeviation", { enumerable: true - , get: function () { return Math.sqrt(this.variance); } - }); - - Object.defineProperty(this, "sScore", { enumerable: true - , get: function () { - var bottom = this.mean + this.standardDeviation; - if(bottom == 0) return 0; - return ((2 * this.mean * this.standardDeviation)/(bottom)); - } - }); -} - -/** - * @ignore - */ -RunningStats.prototype.push = function(x) { - // Update the number of samples - this.m_n = this.m_n + 1; - // See Knuth TAOCP vol 2, 3rd edition, page 232 - if(this.m_n == 1) { - this.m_oldM = this.m_newM = x; - this.m_oldS = 0.0; - } else { - this.m_newM = this.m_oldM + (x - this.m_oldM) / this.m_n; - this.m_newS = this.m_oldS + (x - this.m_oldM) * (x - this.m_newM); - - // set up for next iteration - this.m_oldM = this.m_newM; - this.m_oldS = this.m_newS; - } -} - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "autoReconnect", { enumerable: true - , get: function () { - return this.options['auto_reconnect'] == null ? false : this.options['auto_reconnect']; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "connection", { enumerable: true - , get: function () { - return this.internalConnection; - } - , set: function(connection) { - this.internalConnection = connection; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "master", { enumerable: true - , get: function () { - return this.internalMaster; - } - , set: function(value) { - this.internalMaster = value; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "primary", { enumerable: true - , get: function () { - return this; - } -}); - -/** - * Getter for query Stats - * @ignore - */ -Object.defineProperty(Server.prototype, "queryStats", { enumerable: true - , get: function () { - return this._state.runtimeStats.queryStats; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Server.prototype, "runtimeStats", { enumerable: true - , get: function () { - return this._state.runtimeStats; - } -}); - -/** - * Get Read Preference method - * @ignore - */ -Object.defineProperty(Server.prototype, "readPreference", { enumerable: true - , get: function () { - if(this._readPreference == null && this.readSecondary) { - return Server.READ_SECONDARY; - } else if(this._readPreference == null && !this.readSecondary) { - return Server.READ_PRIMARY; - } else { - return this._readPreference; - } - } -}); - -/** - * @ignore - */ -exports.Server = Server; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/url_parser.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/url_parser.js deleted file mode 100644 index 347aee040..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/connection/url_parser.js +++ /dev/null @@ -1,251 +0,0 @@ -var fs = require('fs'), - ReadPreference = require('./read_preference').ReadPreference; - -exports.parse = function(url, options) { - // Ensure we have a default options object if none set - options = options || {}; - // Variables - var connection_part = ''; - var auth_part = ''; - var query_string_part = ''; - var dbName = 'admin'; - - // Must start with mongodb - if(url.indexOf("mongodb://") != 0) - throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); - // If we have a ? mark cut the query elements off - if(url.indexOf("?") != -1) { - query_string_part = url.substr(url.indexOf("?") + 1); - connection_part = url.substring("mongodb://".length, url.indexOf("?")) - } else { - connection_part = url.substring("mongodb://".length); - } - - // Check if we have auth params - if(connection_part.indexOf("@") != -1) { - auth_part = connection_part.split("@")[0]; - connection_part = connection_part.split("@")[1]; - } - - // Check if the connection string has a db - if(connection_part.indexOf(".sock") != -1) { - if(connection_part.indexOf(".sock/") != -1) { - dbName = connection_part.split(".sock/")[1]; - connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); - } - } else if(connection_part.indexOf("/") != -1) { - dbName = connection_part.split("/")[1]; - connection_part = connection_part.split("/")[0]; - } - - // Result object - var object = {}; - - // Pick apart the authentication part of the string - var authPart = auth_part || ''; - var auth = authPart.split(':', 2); - if(options['uri_decode_auth']){ - auth[0] = decodeURIComponent(auth[0]); - if(auth[1]){ - auth[1] = decodeURIComponent(auth[1]); - } - } - - // Add auth to final object if we have 2 elements - if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; - - // Variables used for temporary storage - var hostPart; - var urlOptions; - var servers; - var serverOptions = {socketOptions: {}}; - var dbOptions = {read_preference_tags: []}; - var replSetServersOptions = {socketOptions: {}}; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = {}; - - // Let's check if we are using a domain socket - if(url.match(/\.sock/)) { - // Split out the socket part - var domainSocket = url.substring( - url.indexOf("mongodb://") + "mongodb://".length - , url.lastIndexOf(".sock") + ".sock".length); - // Clean out any auth stuff if any - if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; - servers = [{domain_socket: domainSocket}]; - } else { - // Split up the db - hostPart = connection_part; - // Parse all server results - servers = hostPart.split(',').map(function(h) { - var hostPort = h.split(':', 2); - var _host = hostPort[0] || 'localhost'; - var _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; - - // Return the mapped object - return {host: _host, port: _port}; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if(!opt) return; - var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; - // Options implementations - switch(name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = (value == 'true'); - dbOptions.slaveOk = (value == 'true'); - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = (value == 'true'); - break; - case 'minPoolSize': - throw new Error("minPoolSize not supported"); - case 'maxIdleTimeMS': - throw new Error("maxIdleTimeMS not supported"); - case 'waitQueueMultiple': - throw new Error("waitQueueMultiple not supported"); - case 'waitQueueTimeoutMS': - throw new Error("waitQueueTimeoutMS not supported"); - case 'uuidRepresentation': - throw new Error("uuidRepresentation not supported"); - case 'ssl': - if(value == 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - break; - } - serverOptions.ssl = (value == 'true'); - replSetServersOptions.ssl = (value == 'true'); - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = (value == 'true'); - break; - case 'fsync': - dbOptions.fsync = (value == 'true'); - break; - case 'journal': - dbOptions.journal = (value == 'true'); - break; - case 'safe': - dbOptions.safe = (value == 'true'); - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = (value == 'true'); - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if(value == 'GSSAPI') { - // If no password provided decode only the principal - if(object.auth == null) { - var urlDecodeAuthPart = decodeURIComponent(authPart); - if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); - object.auth = {user: urlDecodeAuthPart, password: null}; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } - - // Only support GSSAPI or MONGODB-CR for now - if(value != 'GSSAPI' - && value != 'MONGODB-CR' - && value != 'PLAIN') - throw new Error("only GSSAPI, PLAIN or MONGODB-CR is supported by authMechanism"); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'wtimeoutMS': - dbOptions.wtimeoutMS = parseInt(value, 10); - break; - case 'readPreference': - if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); - dbOptions.read_preference = value; - break; - case 'readPreferenceTags': - // Contains the tag object - var tagObject = {}; - if(value == null || value == '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - var tags = value.split(/\,/); - for(var i = 0; i < tags.length; i++) { - var parts = tags[i].trim().split(/\:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - break; - default: - break; - } - }); - - // No tags: should be null (not []) - if(dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if((dbOptions.w == -1 || dbOptions.w == 0) && ( - dbOptions.journal == true - || dbOptions.fsync == true - || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") - - // If no read preference set it to primary - if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; - - // Add servers to result - object.servers = servers; - // Returned parsed object - return object; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/cursor.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/cursor.js deleted file mode 100644 index 7beca6027..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/cursor.js +++ /dev/null @@ -1,952 +0,0 @@ -var QueryCommand = require('./commands/query_command').QueryCommand, - GetMoreCommand = require('./commands/get_more_command').GetMoreCommand, - KillCursorCommand = require('./commands/kill_cursor_command').KillCursorCommand, - Long = require('bson').Long, - ReadPreference = require('./connection/read_preference').ReadPreference, - CursorStream = require('./cursorstream'), - timers = require('timers'), - utils = require('./utils'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Constructor for a cursor object that handles all the operations on query result - * using find. This cursor object is unidirectional and cannot traverse backwards. Clients should not be creating a cursor directly, - * but use find to acquire a cursor. (INTERNAL TYPE) - * - * Options - * - **skip** {Number} skip number of documents to skip. - * - **limit** {Number}, limit the number of results to return. -1 has a special meaning and is used by Db.eval. A value of 1 will also be treated as if it were -1. - * - **sort** {Array | Object}, set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * - **hint** {Object}, hint force the query to use a specific index. - * - **explain** {Boolean}, explain return the explaination of the query. - * - **snapshot** {Boolean}, snapshot Snapshot mode assures no duplicates are returned. - * - **timeout** {Boolean}, timeout allow the query to timeout. - * - **tailable** {Boolean}, tailable allow the cursor to be tailable. - * - **awaitdata** {Boolean}, awaitdata allow the cursor to wait for data, only applicable for tailable cursor. - * - **batchSize** {Number}, batchSize the number of the subset of results to request the database to return for every request. This should initially be greater than 1 otherwise the database will automatically close the cursor. The batch size can be set to 1 with cursorInstance.batchSize after performing the initial query to the database. - * - **raw** {Boolean}, raw return all query documents as raw buffers (default false). - * - **read** {Boolean}, read specify override of read from source (primary/secondary). - * - **returnKey** {Boolean}, returnKey only return the index key. - * - **maxScan** {Number}, maxScan limit the number of items to scan. - * - **min** {Number}, min set index bounds. - * - **max** {Number}, max set index bounds. - * - **showDiskLoc** {Boolean}, showDiskLoc show disk location of results. - * - **comment** {String}, comment you can put a $comment field on a query to make looking in the profiler logs simpler. - * - **numberOfRetries** {Number}, numberOfRetries if using awaidata specifies the number of times to retry on timeout. - * - **dbName** {String}, dbName override the default dbName. - * - **tailableRetryInterval** {Number}, tailableRetryInterval specify the miliseconds between getMores on tailable cursor. - * - **exhaust** {Boolean}, exhaust have the server send all the documents at once as getMore packets. - * - **partial** {Boolean}, partial have the sharded system return a partial result from mongos. - * - * @class Represents a Cursor. - * @param {Db} db the database object to work with. - * @param {Collection} collection the collection to query. - * @param {Object} selector the query selector. - * @param {Object} fields an object containing what fields to include or exclude from objects returned. - * @param {Object} [options] additional options for the collection. -*/ -function Cursor(db, collection, selector, fields, options) { - this.db = db; - this.collection = collection; - this.selector = selector; - this.fields = fields; - options = !options ? {} : options; - - this.skipValue = options.skip == null ? 0 : options.skip; - this.limitValue = options.limit == null ? 0 : options.limit; - this.sortValue = options.sort; - this.hint = options.hint; - this.explainValue = options.explain; - this.snapshot = options.snapshot; - this.timeout = options.timeout == null ? true : options.timeout; - this.tailable = options.tailable; - this.awaitdata = options.awaitdata; - this.numberOfRetries = options.numberOfRetries == null ? 5 : options.numberOfRetries; - this.currentNumberOfRetries = this.numberOfRetries; - this.batchSizeValue = options.batchSize == null ? 0 : options.batchSize; - this.raw = options.raw == null ? false : options.raw; - this.read = options.read == null ? ReadPreference.PRIMARY : options.read; - this.returnKey = options.returnKey; - this.maxScan = options.maxScan; - this.min = options.min; - this.max = options.max; - this.showDiskLoc = options.showDiskLoc; - this.comment = options.comment; - this.tailableRetryInterval = options.tailableRetryInterval || 100; - this.exhaust = options.exhaust || false; - this.partial = options.partial || false; - this.slaveOk = options.slaveOk || false; - - this.totalNumberOfRecords = 0; - this.items = []; - this.cursorId = Long.fromInt(0); - - // This name - this.dbName = options.dbName; - - // State variables for the cursor - this.state = Cursor.INIT; - // Keep track of the current query run - this.queryRun = false; - this.getMoreTimer = false; - - // If we are using a specific db execute against it - if(this.dbName != null) { - this.collectionName = this.dbName + "." + this.collection.collectionName; - } else { - this.collectionName = (this.db.databaseName ? this.db.databaseName + "." : '') + this.collection.collectionName; - } -}; - -/** - * Resets this cursor to its initial state. All settings like the query string, - * tailable, batchSizeValue, skipValue and limits are preserved. - * - * @return {Cursor} returns itself with rewind applied. - * @api public - */ -Cursor.prototype.rewind = function() { - var self = this; - - if (self.state != Cursor.INIT) { - if (self.state != Cursor.CLOSED) { - self.close(function() {}); - } - - self.numberOfReturned = 0; - self.totalNumberOfRecords = 0; - self.items = []; - self.cursorId = Long.fromInt(0); - self.state = Cursor.INIT; - self.queryRun = false; - } - - return self; -}; - - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * - * @param {Function} callback This will be called after executing this method successfully. The first parameter will contain the Error object if an error occured, or null otherwise. The second parameter will contain an array of BSON deserialized objects as a result of the query. - * @return {null} - * @api public - */ -Cursor.prototype.toArray = function(callback) { - var self = this; - - if(!callback) { - throw new Error('callback is mandatory'); - } - - if(this.tailable) { - callback(new Error("Tailable cursor cannot be converted to array"), null); - } else if(this.state != Cursor.CLOSED) { - // return toArrayExhaust(self, callback); - // If we are using exhaust we can't use the quick fire method - if(self.exhaust) return toArrayExhaust(self, callback); - // Quick fire using trampoline to avoid nextTick - self.nextObject({noReturn: true}, function(err, result) { - if(err) return callback(utils.toError(err), null); - if(self.cursorId.toString() == "0") { - self.state = Cursor.CLOSED; - return callback(null, self.items); - } - - // Let's issue getMores until we have no more records waiting - getAllByGetMore(self, function(err, done) { - self.state = Cursor.CLOSED; - if(err) return callback(utils.toError(err), null); - // Let's release the internal list - var items = self.items; - self.items = null; - // Return all the items - callback(null, items); - }); - }) - - } else { - callback(new Error("Cursor is closed"), null); - } -} - -var toArrayExhaust = function(self, callback) { - var items = []; - - self.each(function(err, item) { - if(err != null) { - return callback(utils.toError(err), null); - } - - if(item != null && Array.isArray(items)) { - items.push(item); - } else { - var resultItems = items; - items = null; - self.items = []; - callback(null, resultItems); - } - }); -} - -var getAllByGetMore = function(self, callback) { - getMore(self, {noReturn: true}, function(err, result) { - if(err) return callback(utils.toError(err)); - if(result == null) return callback(null, null); - if(self.cursorId.toString() == "0") return callback(null, null); - getAllByGetMore(self, callback); - }) -} - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * - * @param {Function} callback this will be called for while iterating every document of the query result. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the document. - * @return {null} - * @api public - */ -Cursor.prototype.each = function(callback) { - var self = this; - var fn; - - if (!callback) { - throw new Error('callback is mandatory'); - } - - if(this.state != Cursor.CLOSED) { - // If we are using exhaust we can't use the quick fire method - if(self.exhaust) return eachExhaust(self, callback); - // Quick fire using trampoline to avoid nextTick - if(this.items.length > 0) { - // Trampoline all the entries - while(fn = loop(self, callback)) fn(self, callback); - // Call each again - self.each(callback); - } else { - self.nextObject(function(err, item) { - - if(err) { - self.state = Cursor.CLOSED; - return callback(utils.toError(err), item); - } - - if(item == null) return callback(null, null); - callback(null, item); - self.each(callback); - }) - } - } else { - callback(new Error("Cursor is closed"), null); - } -} - -// Special for exhaust command as we don't initiate the actual result sets -// the server just sends them as they arrive meaning we need to get the IO event -// loop happen so we can receive more data from the socket or we return to early -// after the first fetch and loose all the incoming getMore's automatically issued -// from the server. -var eachExhaust = function(self, callback) { - //FIX: stack overflow (on deep callback) (cred: https://github.com/limp/node-mongodb-native/commit/27da7e4b2af02035847f262b29837a94bbbf6ce2) - processor(function(){ - // Fetch the next object until there is no more objects - self.nextObject(function(err, item) { - if(err != null) return callback(err, null); - if(item != null) { - callback(null, item); - eachExhaust(self, callback); - } else { - // Close the cursor if done - self.state = Cursor.CLOSED; - callback(err, null); - } - }); - }); -} - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -var loop = function(self, callback) { - // No more items we are done - if(self.items.length == 0) return; - // Get the next document - var doc = self.items.shift(); - // Callback - callback(null, doc); - // Loop - return loop; -} - -/** - * Determines how many result the query for this cursor will return - * - * @param {Boolean} applySkipLimit if set to true will apply the skip and limits set on the cursor. Defaults to false. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the number of results or null if an error occured. - * @return {null} - * @api public - */ -Cursor.prototype.count = function(applySkipLimit, callback) { - if(typeof applySkipLimit == 'function') { - callback = applySkipLimit; - applySkipLimit = false; - } - - var options = {}; - if(applySkipLimit) { - if(typeof this.skipValue == 'number') options.skip = this.skipValue; - if(typeof this.limitValue == 'number') options.limit = this.limitValue; - } - - // Call count command - this.collection.count(this.selector, options, callback); -}; - -/** - * Sets the sort parameter of this cursor to the given value. - * - * This method has the following method signatures: - * (keyOrList, callback) - * (keyOrList, direction, callback) - * - * @param {String|Array|Object} keyOrList This can be a string or an array. If passed as a string, the string will be the field to sort. If passed an array, each element will represent a field to be sorted and should be an array that contains the format [string, direction]. - * @param {String|Number} direction this determines how the results are sorted. "asc", "ascending" or 1 for asceding order while "desc", "desceding or -1 for descending order. Note that the strings are case insensitive. - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.sort = function(keyOrList, direction, callback) { - callback = callback || function(){}; - if(typeof direction === "function") { callback = direction; direction = null; } - - if(this.tailable) { - callback(new Error("Tailable cursor doesn't support sorting"), null); - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - callback(new Error("Cursor is closed"), null); - } else { - var order = keyOrList; - - if(direction != null) { - order = [[keyOrList, direction]]; - } - - this.sortValue = order; - callback(null, this); - } - return this; -}; - -/** - * Sets the limit parameter of this cursor to the given value. - * - * @param {Number} limit the new limit. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the limit given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.limit = function(limit, callback) { - if(this.tailable) { - if(callback) { - callback(new Error("Tailable cursor doesn't support limit"), null); - } else { - throw new Error("Tailable cursor doesn't support limit"); - } - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - if(callback) { - callback(new Error("Cursor is closed"), null); - } else { - throw new Error("Cursor is closed"); - } - } else { - if(limit != null && limit.constructor != Number) { - if(callback) { - callback(new Error("limit requires an integer"), null); - } else { - throw new Error("limit requires an integer"); - } - } else { - this.limitValue = limit; - if(callback) return callback(null, this); - } - } - - return this; -}; - -/** - * Sets the read preference for the cursor - * - * @param {String} the read preference for the cursor, one of Server.READ_PRIMARY, Server.READ_SECONDARY, Server.READ_SECONDARY_ONLY - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the read preference given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.setReadPreference = function(readPreference, tags, callback) { - if(typeof tags == 'function') callback = tags; - - var _mode = readPreference != null && typeof readPreference == 'object' ? readPreference.mode : readPreference; - - if(this.queryRun == true || this.state == Cursor.CLOSED) { - if(callback == null) throw new Error("Cannot change read preference on executed query or closed cursor"); - callback(new Error("Cannot change read preference on executed query or closed cursor")); - } else if(_mode != null && _mode != 'primary' - && _mode != 'secondaryOnly' && _mode != 'secondary' - && _mode != 'nearest' && _mode != 'primaryPreferred' && _mode != 'secondaryPreferred') { - if(callback == null) throw new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported"); - callback(new Error("only readPreference of primary, secondary, secondaryPreferred, primaryPreferred or nearest supported")); - } else { - this.read = readPreference; - if(callback != null) callback(null, this); - } - - return this; -} - -/** - * Sets the skip parameter of this cursor to the given value. - * - * @param {Number} skip the new skip value. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the skip value given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.skip = function(skip, callback) { - callback = callback || function(){}; - - if(this.tailable) { - callback(new Error("Tailable cursor doesn't support skip"), null); - } else if(this.queryRun == true || this.state == Cursor.CLOSED) { - callback(new Error("Cursor is closed"), null); - } else { - if(skip != null && skip.constructor != Number) { - callback(new Error("skip requires an integer"), null); - } else { - this.skipValue = skip; - callback(null, this); - } - } - - return this; -}; - -/** - * Sets the batch size parameter of this cursor to the given value. - * - * @param {Number} batchSize the new batch size. - * @param {Function} [callback] this optional callback will be called after executing this method. The first parameter will contain an error object when the batchSize given is not a valid number or when the cursor is already closed while the second parameter will contain a reference to this object upon successful execution. - * @return {Cursor} an instance of this object. - * @api public - */ -Cursor.prototype.batchSize = function(batchSize, callback) { - if(this.state == Cursor.CLOSED) { - if(callback != null) { - return callback(new Error("Cursor is closed"), null); - } else { - throw new Error("Cursor is closed"); - } - } else if(batchSize != null && batchSize.constructor != Number) { - if(callback != null) { - return callback(new Error("batchSize requires an integer"), null); - } else { - throw new Error("batchSize requires an integer"); - } - } else { - this.batchSizeValue = batchSize; - if(callback != null) return callback(null, this); - } - - return this; -}; - -/** - * The limit used for the getMore command - * - * @return {Number} The number of records to request per batch. - * @ignore - * @api private - */ -var limitRequest = function(self) { - var requestedLimit = self.limitValue; - var absLimitValue = Math.abs(self.limitValue); - var absBatchValue = Math.abs(self.batchSizeValue); - - if(absLimitValue > 0) { - if (absBatchValue > 0) { - requestedLimit = Math.min(absLimitValue, absBatchValue); - } - } else { - requestedLimit = self.batchSizeValue; - } - - return requestedLimit; -}; - - -/** - * Generates a QueryCommand object using the parameters of this cursor. - * - * @return {QueryCommand} The command object - * @ignore - * @api private - */ -var generateQueryCommand = function(self) { - // Unpack the options - var queryOptions = QueryCommand.OPTS_NONE; - if(!self.timeout) { - queryOptions |= QueryCommand.OPTS_NO_CURSOR_TIMEOUT; - } - - if(self.tailable != null) { - queryOptions |= QueryCommand.OPTS_TAILABLE_CURSOR; - self.skipValue = self.limitValue = 0; - - // if awaitdata is set - if(self.awaitdata != null) { - queryOptions |= QueryCommand.OPTS_AWAIT_DATA; - } - } - - if(self.exhaust) { - queryOptions |= QueryCommand.OPTS_EXHAUST; - } - - // Unpack the read preference to set slave ok correctly - var read = self.read instanceof ReadPreference ? self.read.mode : self.read; - - // if(self.read == 'secondary') - if(read == ReadPreference.PRIMARY_PREFERRED - || read == ReadPreference.SECONDARY - || read == ReadPreference.SECONDARY_PREFERRED - || read == ReadPreference.NEAREST) { - queryOptions |= QueryCommand.OPTS_SLAVE; - } - - // Override slaveOk from the user - if(self.slaveOk) { - queryOptions |= QueryCommand.OPTS_SLAVE; - } - - if(self.partial) { - queryOptions |= QueryCommand.OPTS_PARTIAL; - } - - // limitValue of -1 is a special case used by Db#eval - var numberToReturn = self.limitValue == -1 ? -1 : limitRequest(self); - - // Check if we need a special selector - if(self.sortValue != null || self.explainValue != null || self.hint != null || self.snapshot != null - || self.returnKey != null || self.maxScan != null || self.min != null || self.max != null - || self.showDiskLoc != null || self.comment != null) { - - // Build special selector - var specialSelector = {'$query':self.selector}; - if(self.sortValue != null) specialSelector['orderby'] = utils.formattedOrderClause(self.sortValue); - if(self.hint != null && self.hint.constructor == Object) specialSelector['$hint'] = self.hint; - if(self.snapshot != null) specialSelector['$snapshot'] = true; - if(self.returnKey != null) specialSelector['$returnKey'] = self.returnKey; - if(self.maxScan != null) specialSelector['$maxScan'] = self.maxScan; - if(self.min != null) specialSelector['$min'] = self.min; - if(self.max != null) specialSelector['$max'] = self.max; - if(self.showDiskLoc != null) specialSelector['$showDiskLoc'] = self.showDiskLoc; - if(self.comment != null) specialSelector['$comment'] = self.comment; - // If we have explain set only return a single document with automatic cursor close - if(self.explainValue != null) { - numberToReturn = (-1)*Math.abs(numberToReturn); - specialSelector['$explain'] = true; - } - - // Return the query - return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, specialSelector, self.fields); - } else { - return new QueryCommand(self.db, self.collectionName, queryOptions, self.skipValue, numberToReturn, self.selector, self.fields); - } -}; - -/** - * @return {Object} Returns an object containing the sort value of this cursor with - * the proper formatting that can be used internally in this cursor. - * @ignore - * @api private - */ -Cursor.prototype.formattedOrderClause = function() { - return utils.formattedOrderClause(this.sortValue); -}; - -/** - * Converts the value of the sort direction into its equivalent numerical value. - * - * @param sortDirection {String|number} Range of acceptable values: - * 'ascending', 'descending', 'asc', 'desc', 1, -1 - * - * @return {number} The equivalent numerical value - * @throws Error if the given sortDirection is invalid - * @ignore - * @api private - */ -Cursor.prototype.formatSortValue = function(sortDirection) { - return utils.formatSortValue(sortDirection); -}; - -/** - * Gets the next document from the cursor. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results. - * @api public - */ -Cursor.prototype.nextObject = function(options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - if(self.state == Cursor.INIT) { - var cmd; - try { - cmd = generateQueryCommand(self); - } catch (err) { - return callback(err, null); - } - - var queryOptions = {exhaust: self.exhaust, raw:self.raw, read:self.read, connection:self.connection}; - // Execute command - var commandHandler = function(err, result) { - // If on reconnect, the command got given a different connection, switch - // the whole cursor to it. - self.connection = queryOptions.connection; - self.state = Cursor.OPEN; - if(err != null && result == null) return callback(utils.toError(err), null); - - if(err == null && (result == null || result.documents == null || !Array.isArray(result.documents))) { - return self.close(function() {callback(new Error("command failed to return results"), null);}); - } - - if(err == null && result && result.documents[0] && result.documents[0]['$err']) { - return self.close(function() {callback(utils.toError(result.documents[0]['$err']), null);}); - } - - self.queryRun = true; - self.state = Cursor.OPEN; // Adjust the state of the cursor - self.cursorId = result.cursorId; - self.totalNumberOfRecords = result.numberReturned; - - // Add the new documents to the list of items, using forloop to avoid - // new array allocations and copying - for(var i = 0; i < result.documents.length; i++) { - self.items.push(result.documents[i]); - } - - // If we have noReturn set just return (not modifying the internal item list) - // used for toArray - if(options.noReturn) { - return callback(null, true); - } - - // Ignore callbacks until the cursor is dead for exhausted - if(self.exhaust && result.cursorId.toString() == "0") { - self.nextObject(callback); - } else if(self.exhaust == false || self.exhaust == null) { - self.nextObject(callback); - } - }; - - // If we have no connection set on this cursor check one out - if(self.connection == null) { - try { - self.connection = self.db.serverConfig.checkoutReader(this.read); - // Add to the query options - queryOptions.connection = self.connection; - } catch(err) { - return callback(utils.toError(err), null); - } - } - - // Execute the command - self.db._executeQueryCommand(cmd, queryOptions, commandHandler); - // Set the command handler to null - commandHandler = null; - } else if(self.items.length) { - callback(null, self.items.shift()); - } else if(self.cursorId.greaterThan(Long.fromInt(0))) { - getMore(self, callback); - } else { - // Force cursor to stay open - return self.close(function() {callback(null, null);}); - } -} - -/** - * Gets more results from the database if any. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an error object on error while the second parameter will contain a document from the returned result or null if there are no more results. - * @ignore - * @api private - */ -var getMore = function(self, options, callback) { - var limit = 0; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - if(self.state == Cursor.GET_MORE) return callback(null, null); - - // Set get more in progress - self.state = Cursor.GET_MORE; - - // Set options - if (!self.tailable && self.limitValue > 0) { - limit = self.limitValue - self.totalNumberOfRecords; - if (limit < 1) { - self.close(function() {callback(null, null);}); - return; - } - } - - try { - var getMoreCommand = new GetMoreCommand( - self.db - , self.collectionName - , limitRequest(self) - , self.cursorId - ); - - // Set up options - var command_options = {read: self.read, raw: self.raw, connection:self.connection }; - - // Execute the command - self.db._executeQueryCommand(getMoreCommand, command_options, function(err, result) { - var cbValue; - - // Get more done - self.state = Cursor.OPEN; - - if(err != null) { - self.state = Cursor.CLOSED; - return callback(utils.toError(err), null); - } - - // Ensure we get a valid result - if(!result || !result.documents) { - self.state = Cursor.CLOSED; - return callback(utils.toError("command failed to return results"), null) - } - - // If the QueryFailure flag is set - if((result.responseFlag & (1 << 1)) != 0) { - self.state = Cursor.CLOSED; - return callback(utils.toError("QueryFailure flag set on getmore command"), null); - } - - try { - var isDead = 1 === result.responseFlag && result.cursorId.isZero(); - - self.cursorId = result.cursorId; - self.totalNumberOfRecords += result.numberReturned; - - // Determine if there's more documents to fetch - if(result.numberReturned > 0) { - if (self.limitValue > 0) { - var excessResult = self.totalNumberOfRecords - self.limitValue; - - if (excessResult > 0) { - result.documents.splice(-1 * excessResult, excessResult); - } - } - - // Reset the tries for awaitdata if we are using it - self.currentNumberOfRetries = self.numberOfRetries; - // Get the documents - for(var i = 0; i < result.documents.length; i++) { - self.items.push(result.documents[i]); - } - - // Don's shift a document out as we need it for toArray - if(options.noReturn) { - cbValue = true; - } else { - cbValue = self.items.shift(); - } - } else if(self.tailable && !isDead && self.awaitdata) { - // Excute the tailable cursor once more, will timeout after ~4 sec if awaitdata used - self.currentNumberOfRetries = self.currentNumberOfRetries - 1; - if(self.currentNumberOfRetries == 0) { - self.close(function() { - callback(new Error("tailable cursor timed out"), null); - }); - } else { - getMore(self, callback); - } - } else if(self.tailable && !isDead) { - self.getMoreTimer = setTimeout(function() { getMore(self, callback); }, self.tailableRetryInterval); - } else { - self.close(function() {callback(null, null); }); - } - - result = null; - } catch(err) { - callback(utils.toError(err), null); - } - if (cbValue != null) callback(null, cbValue); - }); - - getMoreCommand = null; - } catch(err) { - // Get more done - self.state = Cursor.OPEN; - - var handleClose = function() { - callback(utils.toError(err), null); - }; - - self.close(handleClose); - handleClose = null; - } -} - -/** - * Gets a detailed information about how the query is performed on this cursor and how - * long it took the database to process it. - * - * @param {Function} callback this will be called after executing this method. The first parameter will always be null while the second parameter will be an object containing the details. - * @api public - */ -Cursor.prototype.explain = function(callback) { - var limit = (-1)*Math.abs(this.limitValue); - - // Create a new cursor and fetch the plan - var cursor = new Cursor(this.db, this.collection, this.selector, this.fields, { - skip: this.skipValue - , limit:limit - , sort: this.sortValue - , hint: this.hint - , explain: true - , snapshot: this.snapshot - , timeout: this.timeout - , tailable: this.tailable - , batchSize: this.batchSizeValue - , slaveOk: this.slaveOk - , raw: this.raw - , read: this.read - , returnKey: this.returnKey - , maxScan: this.maxScan - , min: this.min - , max: this.max - , showDiskLoc: this.showDiskLoc - , comment: this.comment - , awaitdata: this.awaitdata - , numberOfRetries: this.numberOfRetries - , dbName: this.dbName - }); - - // Fetch the explaination document - cursor.nextObject(function(err, item) { - if(err != null) return callback(utils.toError(err), null); - // close the cursor - cursor.close(function(err, result) { - if(err != null) return callback(utils.toError(err), null); - callback(null, item); - }); - }); -}; - -/** - * Returns a Node ReadStream interface for this cursor. - * - * Options - * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting. - * - * @return {CursorStream} returns a stream object. - * @api public - */ -Cursor.prototype.stream = function stream(options) { - return new CursorStream(this, options); -} - -/** - * Close the cursor. - * - * @param {Function} callback this will be called after executing this method. The first parameter will always contain null while the second parameter will contain a reference to this cursor. - * @return {null} - * @api public - */ -Cursor.prototype.close = function(callback) { - var self = this - this.getMoreTimer && clearTimeout(this.getMoreTimer); - // Close the cursor if not needed - if(this.cursorId instanceof Long && this.cursorId.greaterThan(Long.fromInt(0))) { - try { - var command = new KillCursorCommand(this.db, [this.cursorId]); - // Added an empty callback to ensure we don't throw any null exceptions - this.db._executeQueryCommand(command, {read:self.read, raw:self.raw, connection:self.connection}); - } catch(err) {} - } - - // Null out the connection - self.connection = null; - // Reset cursor id - this.cursorId = Long.fromInt(0); - // Set to closed status - this.state = Cursor.CLOSED; - - if(callback) { - callback(null, self); - self.items = []; - } - - return this; -}; - -/** - * Check if the cursor is closed or open. - * - * @return {Boolean} returns the state of the cursor. - * @api public - */ -Cursor.prototype.isClosed = function() { - return this.state == Cursor.CLOSED ? true : false; -}; - -/** - * Init state - * - * @classconstant INIT - **/ -Cursor.INIT = 0; - -/** - * Cursor open - * - * @classconstant OPEN - **/ -Cursor.OPEN = 1; - -/** - * Cursor closed - * - * @classconstant CLOSED - **/ -Cursor.CLOSED = 2; - -/** - * Cursor performing a get more - * - * @classconstant OPEN - **/ -Cursor.GET_MORE = 3; - -/** - * @ignore - * @api private - */ -exports.Cursor = Cursor; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/cursorstream.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/cursorstream.js deleted file mode 100644 index 90b425b96..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/cursorstream.js +++ /dev/null @@ -1,164 +0,0 @@ -var timers = require('timers'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Module dependecies. - */ -var Stream = require('stream').Stream; - -/** - * CursorStream - * - * Returns a stream interface for the **cursor**. - * - * Options - * - **transform** {Function} function of type function(object) { return transformed }, allows for transformation of data before emitting. - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - **close** {function() {}} the end event triggers when there is no more documents available. - * - * @class Represents a CursorStream. - * @param {Cursor} cursor a cursor object that the stream wraps. - * @return {Stream} - */ -function CursorStream(cursor, options) { - if(!(this instanceof CursorStream)) return new CursorStream(cursor); - options = options ? options : {}; - - Stream.call(this); - - this.readable = true; - this.paused = false; - this._cursor = cursor; - this._destroyed = null; - this.options = options; - - // give time to hook up events - var self = this; - process.nextTick(function() { - self._init(); - }); -} - -/** - * Inherit from Stream - * @ignore - * @api private - */ -CursorStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - */ -CursorStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - */ -CursorStream.prototype.paused; - -/** - * Initialize the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._init = function () { - if (this._destroyed) return; - this._next(); -} - -/** - * Pull the next document from the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._next = function () { - if(this.paused || this._destroyed) return; - - var self = this; - // Get the next object - processor(function() { - if(self.paused || self._destroyed) return; - - self._cursor.nextObject(function (err, doc) { - self._onNextObject(err, doc); - }); - }); -} - -/** - * Handle each document as its returned from the cursor. - * @ignore - * @api private - */ -CursorStream.prototype._onNextObject = function (err, doc) { - if(err) return this.destroy(err); - - // when doc is null we hit the end of the cursor - if(!doc && (this._cursor.state == 1 || this._cursor.state == 2)) { - this.emit('end') - return this.destroy(); - } else if(doc) { - var data = typeof this.options.transform == 'function' ? this.options.transform(doc) : doc; - this.emit('data', data); - this._next(); - } -} - -/** - * Pauses the stream. - * - * @api public - */ -CursorStream.prototype.pause = function () { - this.paused = true; -} - -/** - * Resumes the stream. - * - * @api public - */ -CursorStream.prototype.resume = function () { - var self = this; - - // Don't do anything if we are not paused - if(!this.paused) return; - if(!this._cursor.state == 3) return; - - process.nextTick(function() { - self.paused = false; - // Only trigger more fetching if the cursor is open - self._next(); - }) -} - -/** - * Destroys the stream, closing the underlying - * cursor. No more events will be emitted. - * - * @api public - */ -CursorStream.prototype.destroy = function (err) { - if (this._destroyed) return; - this._destroyed = true; - this.readable = false; - - this._cursor.close(); - - if(err) { - this.emit('error', err); - } - - this.emit('close'); -} - -// TODO - maybe implement the raw option to pass binary? -//CursorStream.prototype.setEncoding = function () { -//} - -module.exports = exports = CursorStream; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/db.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/db.js deleted file mode 100644 index 7dc2e47d3..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/db.js +++ /dev/null @@ -1,1954 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var QueryCommand = require('./commands/query_command').QueryCommand - , DbCommand = require('./commands/db_command').DbCommand - , MongoReply = require('./responses/mongo_reply').MongoReply - , Admin = require('./admin').Admin - , Collection = require('./collection').Collection - , Server = require('./connection/server').Server - , ReplSet = require('./connection/repl_set/repl_set').ReplSet - , ReadPreference = require('./connection/read_preference').ReadPreference - , Mongos = require('./connection/mongos').Mongos - , Cursor = require('./cursor').Cursor - , EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , crypto = require('crypto') - , timers = require('timers') - , utils = require('./utils') - , mongodb_cr_authenticate = require('./auth/mongodb_cr.js').authenticate - , mongodb_gssapi_authenticate = require('./auth/mongodb_gssapi.js').authenticate - , mongodb_sspi_authenticate = require('./auth/mongodb_sspi.js').authenticate - , mongodb_plain_authenticate = require('./auth/mongodb_plain.js').authenticate; - -var hasKerberos = false; -// Check if we have a the kerberos library -try { - require('kerberos'); - hasKerberos = true; -} catch(err) {} - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('./utils').processor(); - -/** - * Create a new Db instance. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **native_parser** {Boolean, default:false}, use c++ bson parser. - * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **serializeFunctions** {Boolean, default:false}, serialize functions. - * - **raw** {Boolean, default:false}, peform operations using raw bson buffers. - * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution. - * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries. - * - **numberOfRetries** {Number, default:5}, number of retries off connection. - * - **logger** {Object, default:null}, an object representing a logger that you want to use, needs to support functions debug, log, error **({error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}})**. - * - **slaveOk** {Number, default:null}, force setting of SlaveOk flag on queries (only use when explicitly connecting to a secondary server). - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @class Represents a Db - * @param {String} databaseName name of the database. - * @param {Object} serverConfig server config object. - * @param {Object} [options] additional options for the collection. - */ -function Db(databaseName, serverConfig, options) { - if(!(this instanceof Db)) return new Db(databaseName, serverConfig, options); - EventEmitter.call(this); - - var self = this; - this.databaseName = databaseName; - this.serverConfig = serverConfig; - this.options = options == null ? {} : options; - // State to check against if the user force closed db - this._applicationClosed = false; - // Fetch the override flag if any - var overrideUsedFlag = this.options['override_used_flag'] == null ? false : this.options['override_used_flag']; - - // Verify that nobody is using this config - if(!overrideUsedFlag && this.serverConfig != null && typeof this.serverConfig == 'object' && this.serverConfig._isUsed && this.serverConfig._isUsed()) { - throw new Error("A Server or ReplSet instance cannot be shared across multiple Db instances"); - } else if(!overrideUsedFlag && typeof this.serverConfig == 'object'){ - // Set being used - this.serverConfig._used = true; - } - - // Allow slaveOk override - this.slaveOk = this.options["slave_ok"] == null ? false : this.options["slave_ok"]; - this.slaveOk = this.options["slaveOk"] == null ? this.slaveOk : this.options["slaveOk"]; - - // Ensure we have a valid db name - validateDatabaseName(databaseName); - - // Contains all the connections for the db - try { - this.native_parser = this.options.native_parser; - // The bson lib - var bsonLib = this.bsonLib = this.options.native_parser ? require('bson').BSONNative : require('bson').BSONPure; - // Fetch the serializer object - var BSON = bsonLib.BSON; - - // Create a new instance - this.bson = new BSON([bsonLib.Long, bsonLib.ObjectID, bsonLib.Binary, bsonLib.Code, bsonLib.DBRef, bsonLib.Symbol, bsonLib.Double, bsonLib.Timestamp, bsonLib.MaxKey, bsonLib.MinKey]); - this.bson.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs; - - // Backward compatibility to access types - this.bson_deserializer = bsonLib; - this.bson_serializer = bsonLib; - - // Add any overrides to the serializer and deserializer - this.bson_deserializer.promoteLongs = this.options.promoteLongs == null ? true : this.options.promoteLongs; - } catch (err) { - // If we tried to instantiate the native driver - var msg = "Native bson parser not compiled, please compile " - + "or avoid using native_parser=true"; - throw Error(msg); - } - - // Internal state of the server - this._state = 'disconnected'; - - this.pkFactory = this.options.pk == null ? bsonLib.ObjectID : this.options.pk; - this.forceServerObjectId = this.options.forceServerObjectId != null ? this.options.forceServerObjectId : false; - - // Added safe - this.safe = this.options.safe == null ? false : this.options.safe; - - // If we have not specified a "safe mode" we just print a warning to the console - if(this.options.safe == null && this.options.w == null && this.options.journal == null && this.options.fsync == null) { - console.log("========================================================================================"); - console.log("= Please ensure that you set the default write concern for the database by setting ="); - console.log("= one of the options ="); - console.log("= ="); - console.log("= w: (value of > -1 or the string 'majority'), where < 1 means ="); - console.log("= no write acknowlegement ="); - console.log("= journal: true/false, wait for flush to journal before acknowlegement ="); - console.log("= fsync: true/false, wait for flush to file system before acknowlegement ="); - console.log("= ="); - console.log("= For backward compatibility safe is still supported and ="); - console.log("= allows values of [true | false | {j:true} | {w:n, wtimeout:n} | {fsync:true}] ="); - console.log("= the default value is false which means the driver receives does not ="); - console.log("= return the information of the success/error of the insert/update/remove ="); - console.log("= ="); - console.log("= ex: new Db(new Server('localhost', 27017), {safe:false}) ="); - console.log("= ="); - console.log("= http://www.mongodb.org/display/DOCS/getLastError+Command ="); - console.log("= ="); - console.log("= The default of no acknowlegement will change in the very near future ="); - console.log("= ="); - console.log("= This message will disappear when the default safe is set on the driver Db ="); - console.log("========================================================================================"); - } - - // Internal states variables - this.notReplied ={}; - this.isInitializing = true; - this.openCalled = false; - - // Command queue, keeps a list of incoming commands that need to be executed once the connection is up - this.commands = []; - - // Set up logger - this.logger = this.options.logger != null - && (typeof this.options.logger.debug == 'function') - && (typeof this.options.logger.error == 'function') - && (typeof this.options.logger.log == 'function') - ? this.options.logger : {error:function(message, object) {}, log:function(message, object) {}, debug:function(message, object) {}}; - - // Associate the logger with the server config - this.serverConfig.logger = this.logger; - if(this.serverConfig.strategyInstance) this.serverConfig.strategyInstance.logger = this.logger; - this.tag = new Date().getTime(); - // Just keeps list of events we allow - this.eventHandlers = {error:[], parseError:[], poolReady:[], message:[], close:[]}; - - // Controls serialization options - this.serializeFunctions = this.options.serializeFunctions != null ? this.options.serializeFunctions : false; - - // Raw mode - this.raw = this.options.raw != null ? this.options.raw : false; - - // Record query stats - this.recordQueryStats = this.options.recordQueryStats != null ? this.options.recordQueryStats : false; - - // If we have server stats let's make sure the driver objects have it enabled - if(this.recordQueryStats == true) { - this.serverConfig.enableRecordQueryStats(true); - } - - // Retry information - this.retryMiliSeconds = this.options.retryMiliSeconds != null ? this.options.retryMiliSeconds : 1000; - this.numberOfRetries = this.options.numberOfRetries != null ? this.options.numberOfRetries : 60; - - // Set default read preference if any - this.readPreference = this.options.readPreference; - - // Set read preference on serverConfig if none is set - // but the db one was - if(this.serverConfig.options.readPreference == null - && this.readPreference != null) { - this.serverConfig.setReadPreference(this.readPreference); - } - - // Ensure we keep a reference to this db - this.serverConfig._dbStore.add(this); -}; - -/** - * @ignore - */ -function validateDatabaseName(databaseName) { - if(typeof databaseName !== 'string') throw new Error("database name must be a string"); - if(databaseName.length === 0) throw new Error("database name cannot be the empty string"); - if(databaseName == '$external') return; - - var invalidChars = [" ", ".", "$", "/", "\\"]; - for(var i = 0; i < invalidChars.length; i++) { - if(databaseName.indexOf(invalidChars[i]) != -1) throw new Error("database names cannot contain the character '" + invalidChars[i] + "'"); - } -} - -/** - * @ignore - */ -inherits(Db, EventEmitter); - -/** - * Initialize the database connection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the index information or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.open = function(callback) { - var self = this; - - // Check that the user has not called this twice - if(this.openCalled) { - // Close db - this.close(); - // Throw error - throw new Error("db object already connecting, open cannot be called multiple times"); - } - - // If we have a specified read preference - if(this.readPreference != null) this.serverConfig.setReadPreference(this.readPreference); - - // Set that db has been opened - this.openCalled = true; - - // Set the status of the server - self._state = 'connecting'; - - // Set up connections - if(self.serverConfig instanceof Server || self.serverConfig instanceof ReplSet || self.serverConfig instanceof Mongos) { - // Ensure we have the original options passed in for the server config - var connect_options = {}; - for(var name in self.serverConfig.options) { - connect_options[name] = self.serverConfig.options[name] - } - connect_options.firstCall = true; - - // Attempt to connect - self.serverConfig.connect(self, connect_options, function(err, result) { - if(err != null) { - // Set that db has been closed - self.openCalled = false; - // Return error from connection - return callback(err, null); - } - // Set the status of the server - self._state = 'connected'; - // If we have queued up commands execute a command to trigger replays - if(self.commands.length > 0) _execute_queued_command(self); - // Callback - process.nextTick(function() { - try { - callback(null, self); - } catch(err) { - self.close(); - throw err; - } - }); - }); - } else { - try { - callback(Error("Server parameter must be of type Server, ReplSet or Mongos"), null); - } catch(err) { - self.close(); - throw err; - } - } -}; - -/** - * Create a new Db instance sharing the current socket connections. - * - * @param {String} dbName the name of the database we want to use. - * @return {Db} a db instance using the new database. - * @api public - */ -Db.prototype.db = function(dbName) { - // Copy the options and add out internal override of the not shared flag - var options = {}; - for(var key in this.options) { - options[key] = this.options[key]; - } - - // Add override flag - options['override_used_flag'] = true; - // Check if the db already exists and reuse if it's the case - var db = this.serverConfig._dbStore.fetch(dbName); - - // Create a new instance - if(!db) { - db = new Db(dbName, this.serverConfig, options); - } - - // Return the db object - return db; -} - -/** - * Close the current db connection, including all the child db instances. Emits close event if no callback is provided. - * - * @param {Boolean} [forceClose] connection can never be reused. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.close = function(forceClose, callback) { - var self = this; - // Ensure we force close all connections - this._applicationClosed = false; - - if(typeof forceClose == 'function') { - callback = forceClose; - } else if(typeof forceClose == 'boolean') { - this._applicationClosed = forceClose; - } - - this.serverConfig.close(function(err, result) { - // You can reuse the db as everything is shut down - self.openCalled = false; - // If we have a callback call it - if(callback) callback(err, result); - }); -}; - -/** - * Access the Admin database - * - * @param {Function} [callback] returns the results. - * @return {Admin} the admin db object. - * @api public - */ -Db.prototype.admin = function(callback) { - if(callback == null) return new Admin(this); - callback(null, new Admin(this)); -}; - -/** - * Returns a cursor to all the collection information. - * - * @param {String} [collectionName] the collection name we wish to retrieve the information from. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the options or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.collectionsInfo = function(collectionName, callback) { - if(callback == null && typeof collectionName == 'function') { callback = collectionName; collectionName = null; } - // Create selector - var selector = {}; - // If we are limiting the access to a specific collection name - if(collectionName != null) selector.name = this.databaseName + "." + collectionName; - - // Return Cursor - // callback for backward compatibility - if(callback) { - callback(null, new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector)); - } else { - return new Cursor(this, new Collection(this, DbCommand.SYSTEM_NAMESPACE_COLLECTION), selector); - } -}; - -/** - * Get the list of all collection names for the specified db - * - * Options - * - **namesOnly** {String, default:false}, Return only the full collection namespace. - * - * @param {String} [collectionName] the collection name we wish to filter by. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collection names or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.collectionNames = function(collectionName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - collectionName = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Ensure no breaking behavior - if(collectionName != null && typeof collectionName == 'object') { - options = collectionName; - collectionName = null; - } - - // Let's make our own callback to reuse the existing collections info method - self.collectionsInfo(collectionName, function(err, cursor) { - if(err != null) return callback(err, null); - - cursor.toArray(function(err, documents) { - if(err != null) return callback(err, null); - - // List of result documents that have been filtered - var filtered_documents = documents.filter(function(document) { - return !(document.name.indexOf(self.databaseName) == -1 || document.name.indexOf('$') != -1); - }); - - // If we are returning only the names - if(options.namesOnly) { - filtered_documents = filtered_documents.map(function(document) { return document.name }); - } - - // Return filtered items - callback(null, filtered_documents); - }); - }); -}; - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can - * can use it without a callback in the following way. var collection = db.collection('mycollection'); - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strict**, (Boolean, default:false) returns an error if the collection does not exist - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName the collection name we wish to access. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collection or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.collection = function(collectionName, options, callback) { - var self = this; - if(typeof options === "function") { callback = options; options = {}; } - // Execute safe - - if(options && (options.strict)) { - self.collectionNames(collectionName, function(err, collections) { - if(err != null) return callback(err, null); - - if(collections.length == 0) { - return callback(new Error("Collection " + collectionName + " does not exist. Currently in safe mode."), null); - } else { - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - return callback(err, null); - } - return callback(null, collection); - } - }); - } else { - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - if(callback == null) { - throw err; - } else { - return callback(err, null); - } - } - - // If we have no callback return collection object - return callback == null ? collection : callback(null, collection); - } -}; - -/** - * Fetch all collections for the current db. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the collections or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.collections = function(callback) { - var self = this; - // Let's get the collection names - self.collectionNames(function(err, documents) { - if(err != null) return callback(err, null); - var collections = []; - documents.forEach(function(document) { - collections.push(new Collection(self, document.name.replace(self.databaseName + ".", ''), self.pkFactory)); - }); - // Return the collection objects - callback(null, collections); - }); -}; - -/** - * Evaluate javascript on the server - * - * Options - * - **nolock** {Boolean, default:false}, Tell MongoDB not to block on the evaulation of the javascript. - * - * @param {Code} code javascript to execute on server. - * @param {Object|Array} [parameters] the parameters for the call. - * @param {Object} [options] the options - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from eval or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.eval = function(code, parameters, options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - var finalCode = code; - var finalParameters = []; - // If not a code object translate to one - if(!(finalCode instanceof this.bsonLib.Code)) { - finalCode = new this.bsonLib.Code(finalCode); - } - - // Ensure the parameters are correct - if(parameters != null && parameters.constructor != Array && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if(parameters != null && parameters.constructor == Array && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - var selector = {'$eval':finalCode, 'args':finalParameters}; - // Check if the nolock parameter is passed in - if(options['nolock']) { - selector['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = ReadPreference.PRIMARY; - - // Execute the eval - this.collection(DbCommand.SYSTEM_COMMAND_COLLECTION).findOne(selector, options, function(err, result) { - if(err) return callback(err); - - if(result && result.ok == 1) { - callback(null, result.retval); - } else if(result) { - callback(new Error("eval failed: " + result.errmsg), null); return; - } else { - callback(err, result); - } - }); -}; - -/** - * Dereference a dbref, against a db - * - * @param {DBRef} dbRef db reference object we wish to resolve. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dereference or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.dereference = function(dbRef, callback) { - var db = this; - // If we have a db reference then let's get the db first - if(dbRef.db != null) db = this.db(dbRef.db); - // Fetch the collection and find the reference - var collection = db.collection(dbRef.namespace); - collection.findOne({'_id':dbRef.oid}, function(err, result) { - callback(err, result); - }); -}; - -/** - * Logout user from server, fire off on all connections and remove all auth info - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from logout or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.logout = function(options, callback) { - var self = this; - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Number of connections we need to logout from - var numberOfConnections = this.serverConfig.allRawConnections().length; - - // Let's generate the logout command object - var logoutCommand = DbCommand.logoutCommand(self, {logout:1}, options); - self._executeQueryCommand(logoutCommand, {onAll:true}, function(err, result) { - // Count down - numberOfConnections = numberOfConnections - 1; - // Work around the case where the number of connections are 0 - if(numberOfConnections <= 0 && typeof callback == 'function') { - var internalCallback = callback; - callback = null; - - // Remove the db from auths - self.serverConfig.auth.remove(self.databaseName); - - // Handle error result - utils.handleSingleCommandResultReturn(true, false, internalCallback)(err, result); - } - }); -} - -/** - * Authenticate a user against the server. - * authMechanism - * Options - * - **authSource** {String}, The database that the credentials are for, - * different from the name of the current DB, for example admin - * - **authMechanism** {String, default:MONGODB-CR}, The authentication mechanism to use, GSSAPI or MONGODB-CR - * - * @param {String} username username. - * @param {String} password password. - * @param {Object} [options] the options - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from authentication or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.authenticate = function(username, password, options, callback) { - var self = this; - - if(typeof callback === 'undefined') { - callback = options; - options = {}; - } - - // Set default mechanism - if(!options.authMechanism) { - options.authMechanism = 'MONGODB-CR'; - } else if(options.authMechanism != 'GSSAPI' - && options.authMechanism != 'MONGODB-CR' - && options.authMechanism != 'PLAIN') { - return callback(new Error("only GSSAPI, PLAIN or MONGODB-CR is supported by authMechanism")); - } - - // the default db to authenticate against is 'this' - // if authententicate is called from a retry context, it may be another one, like admin - var authdb = options.authdb ? options.authdb : self.databaseName; - authdb = options.authSource ? options.authSource : authdb; - - // Callback - var _callback = function(err, result) { - if(self.listeners("authenticated").length > 9) { - self.emit("authenticated", err, result); - } - - // Return to caller - callback(err, result); - } - - // If classic auth delegate to auth command - if(options.authMechanism == 'MONGODB-CR') { - mongodb_cr_authenticate(self, username, password, authdb, options, _callback); - } else if(options.authMechanism == 'PLAIN') { - mongodb_plain_authenticate(self, username, password, options, _callback); - } else if(options.authMechanism == 'GSSAPI') { - // - // Kerberos library is not installed, throw and error - if(hasKerberos == false) { - console.log("========================================================================================"); - console.log("= Please make sure that you install the Kerberos library to use GSSAPI ="); - console.log("= ="); - console.log("= npm install -g kerberos ="); - console.log("= ="); - console.log("= The Kerberos package is not installed by default for simplicities sake ="); - console.log("= and needs to be global install ="); - console.log("========================================================================================"); - throw new Error("Kerberos library not installed"); - } - - if(process.platform == 'win32') { - mongodb_sspi_authenticate(self, username, password, authdb, options, _callback); - } else { - // We have the kerberos library, execute auth process - mongodb_gssapi_authenticate(self, username, password, authdb, options, _callback); - } - } -}; - -/** - * Add a user to the database. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username username. - * @param {String} password password. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from addUser or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.addUser = function(username, password, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Get the error options - var errorOptions = _getWriteConcern(this, options, callback); - errorOptions.w = errorOptions.w == null ? 1 : errorOptions.w; - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - // Fetch a user collection - var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION); - // Check if we are inserting the first user - collection.count({}, function(err, count) { - // We got an error (f.ex not authorized) - if(err != null) return callback(err, null); - // Check if the user exists and update i - collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { - // We got an error (f.ex not authorized) - if(err != null) return callback(err, null); - // Add command keys - var commandOptions = errorOptions; - commandOptions.dbName = options['dbName']; - commandOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - collection.update({user: username},{$set: {user: username, pwd: userPassword}}, commandOptions, function(err, results) { - if(count == 0 && err) { - callback(null, [{user:username, pwd:userPassword}]); - } else if(err) { - callback(err, null) - } else { - callback(null, [{user:username, pwd:userPassword}]); - } - }); - }); - }); -}; - -/** - * Remove a user from a database - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} username username. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from removeUser or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - // Figure out the safe mode settings - var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe; - // Override with options passed in if applicable - safe = options != null && options['safe'] != null ? options['safe'] : safe; - // Ensure it's at least set to safe - safe = safe == null ? {w: 1} : safe; - - // Fetch a user collection - var collection = this.collection(DbCommand.SYSTEM_USER_COLLECTION); - collection.findOne({user: username}, {dbName: options['dbName']}, function(err, user) { - if(user != null) { - // Add command keys - var commandOptions = safe; - commandOptions.dbName = options['dbName']; - - collection.remove({user: username}, commandOptions, function(err, result) { - callback(err, true); - }); - } else { - callback(err, false); - } - }); -}; - -/** - * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **serializeFunctions** {Boolean, default:false}, serialize functions on the document. - * - **raw** {Boolean, default:false}, perform all operations using raw bson objects. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **capped** {Boolean, default:false}, create a capped collection. - * - **size** {Number}, the size of the capped collection in bytes. - * - **max** {Number}, the maximum number of documents in the capped collection. - * - **autoIndexId** {Boolean, default:true}, create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **strict**, (Boolean, default:false) throws an error if collection already exists - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName the collection name we wish to access. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from createCollection or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.createCollection = function(collectionName, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : null; - var self = this; - - // Figure out the safe mode settings - var safe = self.safe != null && self.safe == false ? {w: 1} : self.safe; - // Override with options passed in if applicable - safe = options != null && options['safe'] != null ? options['safe'] : safe; - // Ensure it's at least set to safe - safe = safe == null ? {w: 1} : safe; - - // Check if we have the name - this.collectionNames(collectionName, function(err, collections) { - if(err != null) return callback(err, null); - - var found = false; - collections.forEach(function(collection) { - if(collection.name == self.databaseName + "." + collectionName) found = true; - }); - - // If the collection exists either throw an exception (if db in safe mode) or return the existing collection - if(found && options && options.strict) { - return callback(new Error("Collection " + collectionName + " already exists. Currently in safe mode."), null); - } else if(found){ - try { - var collection = new Collection(self, collectionName, self.pkFactory, options); - } catch(err) { - return callback(err, null); - } - return callback(null, collection); - } - - // Create a new collection and return it - self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options) - , {read:false, safe:safe} - , utils.handleSingleCommandResultReturn(null, null, function(err, result) { - if(err) return callback(err, null); - // Create collection and return - try { - return callback(null, new Collection(self, collectionName, self.pkFactory, options)); - } catch(err) { - return callback(err, null); - } - })); - }); -}; - -var _getReadConcern = function(self, options) { - if(options.readPreference) return options.readPreference; - if(self.readPreference) return self.readPreference; - return 'primary'; -} - -/** - * Execute a command hash against MongoDB. This lets you acess any commands not available through the api on the server. - * - * @param {Object} selector the command hash to send to the server, ex: {ping:1}. - * @param {Function} callback this will be called after executing this method. The command always return the whole result of the command as the second parameter. - * @return {null} - * @api public - */ -Db.prototype.command = function(selector, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - // Ignore command preference (I know what I'm doing) - var ignoreCommandFilter = options.ignoreCommandFilter ? options.ignoreCommandFilter : false; - - // Set up the options - var cursor = new Cursor(this - , new Collection(this, DbCommand.SYSTEM_COMMAND_COLLECTION), selector, {}, { - limit: -1, timeout: QueryCommand.OPTS_NO_CURSOR_TIMEOUT, dbName: options['dbName'] - }); - - // Set read preference if we set one - var readPreference = options['readPreference'] ? options['readPreference'] : false; - // If we have a connection passed in - cursor.connection = options.connection; - - // Ensure only commands who support read Prefrences are exeuted otherwise override and use Primary - if(readPreference != false && ignoreCommandFilter == false) { - if(selector['group'] || selector['aggregate'] || selector['collStats'] || selector['dbStats'] - || selector['count'] || selector['distinct'] || selector['geoNear'] || selector['geoSearch'] - || selector['geoWalk'] || selector['text'] - || (selector['mapreduce'] && (selector.out == 'inline' || selector.out.inline))) { - // Set the read preference - cursor.setReadPreference(readPreference); - } else { - cursor.setReadPreference(ReadPreference.PRIMARY); - } - } else if(readPreference != false) { - // Force setting the command filter - cursor.setReadPreference(readPreference); - } - - // Get the next result - cursor.nextObject(function(err, result) { - if(err) return callback(err, null); - if(result == null) return callback(new Error("no result returned from command"), null); - callback(null, result); - }); -}; - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @param {String} collectionName the name of the collection we wish to drop. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropCollection or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.dropCollection = function(collectionName, callback) { - var self = this; - callback || (callback = function(){}); - - // Drop the collection - this._executeQueryCommand(DbCommand.createDropCollectionCommand(this, collectionName) - , utils.handleSingleCommandResultReturn(true, false, callback) - ); -}; - -/** - * Rename a collection. - * - * Options - * - **dropTarget** {Boolean, default:false}, drop the target name collection if it previously exists. - * - * @param {String} fromCollection the name of the current collection we wish to rename. - * @param {String} toCollection the new name of the collection. - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from renameCollection or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {} - } - - // Add return new collection - options.new_collection = true; - - // Execute using the collection method - this.collection(fromCollection).rename(toCollection, options, callback); -}; - -/** - * Return last error message for the given connection, note options can be combined. - * - * Options - * - **fsync** {Boolean, default:false}, option forces the database to fsync all files before returning. - * - **j** {Boolean, default:false}, awaits the journal commit before returning, > MongoDB 2.0. - * - **w** {Number}, until a write operation has been replicated to N servers. - * - **wtimeout** {Number}, number of miliseconds to wait before timing out. - * - * Connection Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Object} [connectionOptions] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from lastError or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.lastError = function(options, connectionOptions, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - connectionOptions = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createGetLastErrorCommand(options, this), connectionOptions, function(err, error) { - callback(err, error && error.documents); - }); -}; - -/** - * Legacy method calls. - * - * @ignore - * @api private - */ -Db.prototype.error = Db.prototype.lastError; -Db.prototype.lastStatus = Db.prototype.lastError; - -/** - * Return all errors up to the last time db reset_error_history was called. - * - * Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from previousErrors or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.previousErrors = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createGetPreviousErrorsCommand(this), options, function(err, error) { - callback(err, error.documents); - }); -}; - -/** - * Runs a command on the database. - * @ignore - * @api private - */ -Db.prototype.executeDbCommand = function(command_hash, options, callback) { - if(callback == null) { callback = options; options = {}; } - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, command_hash, options), options, function(err, result) { - if(callback) callback(err, result); - }); -}; - -/** - * Runs a command on the database as admin. - * @ignore - * @api private - */ -Db.prototype.executeDbAdminCommand = function(command_hash, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {} - } - - if(options.readPreference) { - options.read = options.readPreference; - } - - this._executeQueryCommand(DbCommand.createAdminDbCommand(this, command_hash), options, function(err, result) { - if(callback) callback(err, result); - }); -}; - -/** - * Resets the error history of the mongo instance. - * - * Options - * - **connection** {Connection}, fire the getLastError down a specific connection. - * - * @param {Object} [options] returns option results. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from resetErrorHistory or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.resetErrorHistory = function(options, callback) { - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createResetErrorHistoryCommand(this), options, function(err, error) { - if(callback) callback(err, error && error.documents); - }); -}; - -/** - * Creates an index on the collection. - * - * Options -* - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * - * @param {String} collectionName name of the collection to create the index on. - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from createIndex or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Get the error options - var errorOptions = _getWriteConcern(this, options, callback); - // Create command - var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); - // Default command options - var commandOptions = {}; - - // If we have error conditions set handle them - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // Set safe option - commandOptions['safe'] = errorOptions; - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - // Execute insert command - this._executeInsertCommand(command, commandOptions, function(err, result) { - if(err != null) return callback(err, null); - - result = result && result.documents; - if (result[0].err) { - callback(utils.toError(result[0])); - } else { - callback(null, command.documents[0].name); - } - }); - } else if(_hasWriteConcern(errorOptions) && callback == null) { - throw new Error("Cannot use a writeConcern without a provided callback"); - } else { - // Execute insert command - var result = this._executeInsertCommand(command, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(null, null); - } -}; - -/** - * Ensures that an index exists, if it does not it creates it - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **unique** {Boolean, default:false}, creates an unique index. - * - **sparse** {Boolean, default:false}, creates a sparse index. - * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. - * - **dropDups** {Boolean, default:false}, a unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * - **min** {Number}, for geospatial indexes set the lower bound for the co-ordinates. - * - **max** {Number}, for geospatial indexes set the high bound for the co-ordinates. - * - **v** {Number}, specify the format version of the indexes. - * - **expireAfterSeconds** {Number}, allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * - **name** {String}, override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @param {String} collectionName name of the collection to create the index on. - * @param {Object} fieldOrSpec fieldOrSpec that defines the index. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from ensureIndex or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callback) { - var self = this; - - if (typeof callback === 'undefined' && typeof options === 'function') { - callback = options; - options = {}; - } - - if (options == null) { - options = {}; - } - - // Get the error options - var errorOptions = _getWriteConcern(this, options, callback); - // Make sure we don't try to do a write concern without a callback - if(_hasWriteConcern(errorOptions) && callback == null) - throw new Error("Cannot use a writeConcern without a provided callback"); - // Create command - var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); - var index_name = command.documents[0].name; - - // Default command options - var commandOptions = {}; - // Check if the index allready exists - this.indexInformation(collectionName, function(err, collectionInfo) { - if(err != null) return callback(err, null); - - if(!collectionInfo[index_name]) { - // If we have error conditions set handle them - if(_hasWriteConcern(errorOptions) && typeof callback == 'function') { - // Insert options - commandOptions['read'] = false; - // If we have safe set set async to false - if(errorOptions == null) commandOptions['async'] = true; - - // If we have an error option - if(typeof errorOptions == 'object') { - var keys = Object.keys(errorOptions); - for(var i = 0; i < keys.length; i++) { - commandOptions[keys[i]] = errorOptions[keys[i]]; - } - } - - if(typeof callback === 'function' - && commandOptions.w < 1 && !commandOptions.fsync && !commandOptions.journal) { - commandOptions.w = 1; - } - - self._executeInsertCommand(command, commandOptions, function(err, result) { - // Only callback if we have one specified - if(typeof callback === 'function') { - if(err != null) return callback(err, null); - - result = result && result.documents; - if (result[0].err) { - callback(utils.toError(result[0])); - } else { - callback(null, command.documents[0].name); - } - } - }); - } else { - // Execute insert command - var result = self._executeInsertCommand(command, commandOptions); - // If no callback just return - if(!callback) return; - // If error return error - if(result instanceof Error) { - return callback(result); - } - // Otherwise just return - return callback(null, index_name); - } - } else { - if(typeof callback === 'function') return callback(null, index_name); - } - }); -}; - -/** - * Returns the information available on allocated cursors. - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from cursorInfo or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.cursorInfo = function(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - options = args.length ? args.shift() || {} : {}; - - this._executeQueryCommand(DbCommand.createDbSlaveOkCommand(this, {'cursorInfo':1}) - , options - , utils.handleSingleCommandResultReturn(null, null, callback)); -}; - -/** - * Drop an index on a collection. - * - * @param {String} collectionName the name of the collection where the command will drop an index. - * @param {String} indexName name of the index to drop. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropIndex or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.dropIndex = function(collectionName, indexName, callback) { - this._executeQueryCommand(DbCommand.createDropIndexCommand(this, collectionName, indexName) - , utils.handleSingleCommandResultReturn(null, null, callback)); -}; - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * - * @param {String} collectionName the name of the collection. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from reIndex or null if an error occured. - * @api public -**/ -Db.prototype.reIndex = function(collectionName, callback) { - this._executeQueryCommand(DbCommand.createReIndexCommand(this, collectionName) - , utils.handleSingleCommandResultReturn(true, false, callback)); -}; - -/** - * Retrieves this collections index info. - * - * Options - * - **full** {Boolean, default:false}, returns the full raw index information. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {String} collectionName the name of the collection. - * @param {Object} [options] additional options during update. - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from indexInformation or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.indexInformation = function(collectionName, options, callback) { - if(typeof callback === 'undefined') { - if(typeof options === 'undefined') { - callback = collectionName; - collectionName = null; - } else { - callback = options; - } - options = {}; - } - - // If we specified full information - var full = options['full'] == null ? false : options['full']; - // Build selector for the indexes - var selector = collectionName != null ? {ns: (this.databaseName + "." + collectionName)} : {}; - - // Set read preference if we set one - var readPreference = options['readPreference'] ? options['readPreference'] : ReadPreference.PRIMARY; - - // Iterate through all the fields of the index - this.collection(DbCommand.SYSTEM_INDEX_COLLECTION, function(err, collection) { - // Perform the find for the collection - collection.find(selector).setReadPreference(readPreference).toArray(function(err, indexes) { - if(err != null) return callback(err, null); - // Contains all the information - var info = {}; - - // if full defined just return all the indexes directly - if(full) return callback(null, indexes); - - // Process all the indexes - for(var i = 0; i < indexes.length; i++) { - var index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for(var name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - // Return all the indexes - callback(null, info); - }); - }); -}; - -/** - * Drop a database. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from dropDatabase or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.dropDatabase = function(callback) { - this._executeQueryCommand(DbCommand.createDropDatabaseCommand(this) - , utils.handleSingleCommandResultReturn(true, false, callback)); -} - -/** - * Get all the db statistics. - * - * Options - * - **scale** {Number}, divide the returned sizes by scale value. - * - **readPreference** {String}, the preferred read preference ((Server.PRIMARY, Server.PRIMARY_PREFERRED, Server.SECONDARY, Server.SECONDARY_PREFERRED, Server.NEAREST). - * - * @param {Objects} [options] options for the stats command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from stats or null if an error occured. - * @return {null} - * @api public - */ -Db.prototype.stats = function stats(options, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Build command object - var commandObject = { - dbStats:this.collectionName, - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Execute the command - this.command(commandObject, options, callback); -} - -/** - * @ignore - */ -var __executeQueryCommand = function(self, db_command, options, callback) { - // Options unpacking - var read = options['read'] != null ? options['read'] : false; - var raw = options['raw'] != null ? options['raw'] : self.raw; - var onAll = options['onAll'] != null ? options['onAll'] : false; - var specifiedConnection = options['connection'] != null ? options['connection'] : null; - - // Correct read preference to default primary if set to false, null or primary - if(!(typeof read == 'object') && read._type == 'ReadPreference') { - read = (read == null || read == 'primary' || read == false) ? ReadPreference.PRIMARY : read; - if(!ReadPreference.isValid(read)) return callback(new Error("Illegal readPreference mode specified, " + read)); - } else if(typeof read == 'object' && read._type == 'ReadPreference') { - if(!read.isValid()) return callback(new Error("Illegal readPreference mode specified, " + read.mode)); - } - - // If we have a read preference set and we are a mongos pass the read preference on to the mongos instance, - if(self.serverConfig.isMongos() && read != null && read != false) { - db_command.setMongosReadPreference(read); - } - - // If we got a callback object - if(typeof callback === 'function' && !onAll) { - // Override connection if we passed in a specific connection - var connection = specifiedConnection != null ? specifiedConnection : null; - - if(connection instanceof Error) return callback(connection, null); - - // Fetch either a reader or writer dependent on the specified read option if no connection - // was passed in - if(connection == null) { - connection = self.serverConfig.checkoutReader(read); - } - - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error || connection['message'] != null) { - return callback(connection); - } - - // Exhaust Option - var exhaust = options.exhaust || false; - - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command, raw, connection, exhaust, callback); - - // Ensure the connection is valid - if(!connection.isConnected()) { - if(read == ReadPreference.PRIMARY - || read == ReadPreference.PRIMARY_PREFERRED - || (read != null && typeof read == 'object' && read.mode) - || read == null) { - - // Save the command - self.serverConfig._commandsStore.read_from_writer( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } else { - self.serverConfig._commandsStore.read( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } - } - - // Write the message out and handle any errors if there are any - connection.write(db_command, function(err) { - if(err != null) { - // Call the handler with an error - if(Array.isArray(db_command)) - self.serverConfig._callHandler(db_command[0].getRequestId(), null, err); - else - self.serverConfig._callHandler(db_command.getRequestId(), null, err); - } - }); - } else if(typeof callback === 'function' && onAll) { - var connections = self.serverConfig.allRawConnections(); - var numberOfEntries = connections.length; - // Go through all the connections - for(var i = 0; i < connections.length; i++) { - // Fetch a connection - var connection = connections[i]; - - // Ensure we have a valid connection - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error) { - return callback(connection); - } - - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command, raw, connection, callback); - - // Write the message out - connection.write(db_command, function(err) { - // Adjust the number of entries we need to process - numberOfEntries = numberOfEntries - 1; - // Remove listener - if(err != null) { - // Clean up listener and return error - self.serverConfig._removeHandler(db_command.getRequestId()); - } - - // No more entries to process callback with the error - if(numberOfEntries <= 0) { - callback(err); - } - }); - - // Update the db_command request id - db_command.updateRequestId(); - } - } else { - // Fetch either a reader or writer dependent on the specified read option - // var connection = read == null || read == 'primary' || read == false ? self.serverConfig.checkoutWriter(true) : self.serverConfig.checkoutReader(read); - var connection = self.serverConfig.checkoutReader(read); - // Override connection if needed - connection = specifiedConnection != null ? specifiedConnection : connection; - // Ensure we have a valid connection - if(connection == null || connection instanceof Error || connection['message'] != null) return null; - // Write the message out - connection.write(db_command, function(err) { - if(err != null) { - // Emit the error - self.emit("error", err); - } - }); - } -} - -/** - * Execute db query command (not safe) - * @ignore - * @api private - */ -Db.prototype._executeQueryCommand = function(db_command, options, callback) { - var self = this; - - // Unpack the parameters - if (typeof callback === 'undefined') { - callback = options; - options = {}; - } - - // fast fail option used for HA, no retry - var failFast = options['failFast'] != null - ? options['failFast'] - : false; - - // Check if the user force closed the command - if(this._applicationClosed) { - var err = new Error("db closed by application"); - if('function' == typeof callback) { - return callback(err, null); - } else { - throw err; - } - } - - if(this.serverConfig.isDestroyed()) - return callback(new Error("Connection was destroyed by application")); - - // Specific connection - var connection = options.connection; - // Check if the connection is actually live - if(connection - && (!connection.isConnected || !connection.isConnected())) connection = null; - - // Get the configuration - var config = this.serverConfig; - var read = options.read; - - if(!connection && !config.canRead(read) && !config.canWrite() && config.isAutoReconnect()) { - if(read == ReadPreference.PRIMARY - || read == ReadPreference.PRIMARY_PREFERRED - || (read != null && typeof read == 'object' && read.mode) - || read == null) { - - // Save the command - self.serverConfig._commandsStore.read_from_writer( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } else { - self.serverConfig._commandsStore.read( - { type: 'query' - , db_command: db_command - , options: options - , callback: callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } - } else if(!connection && !config.canRead(read) && !config.canWrite() && !config.isAutoReconnect()) { - return callback(new Error("no open connections"), null); - } else { - if(typeof callback == 'function') { - __executeQueryCommand(self, db_command, options, function (err, result, conn) { - callback(err, result, conn); - }); - } else { - __executeQueryCommand(self, db_command, options); - } - } -}; - -/** - * @ignore - */ -var __executeInsertCommand = function(self, db_command, options, callback) { - // Always checkout a writer for this kind of operations - var connection = self.serverConfig.checkoutWriter(); - // Get safe mode - var safe = options['safe'] != null ? options['safe'] : false; - var raw = options['raw'] != null ? options['raw'] : self.raw; - var specifiedConnection = options['connection'] != null ? options['connection'] : null; - // Override connection if needed - connection = specifiedConnection != null ? specifiedConnection : connection; - - // Ensure we have a valid connection - if(typeof callback === 'function') { - // Ensure we have a valid connection - if(connection == null) { - return callback(new Error("no open connections")); - } else if(connection instanceof Error) { - return callback(connection); - } - - var errorOptions = _getWriteConcern(self, options, callback); - if(errorOptions.w > 0 || errorOptions.w == 'majority' || errorOptions.j || errorOptions.journal || errorOptions.fsync) { - // db command is now an array of commands (original command + lastError) - db_command = [db_command, DbCommand.createGetLastErrorCommand(safe, self)]; - // Register the handler in the data structure - self.serverConfig._registerHandler(db_command[1], raw, connection, callback); - } - } - - // If we have no callback and there is no connection - if(connection == null) return null; - if(connection instanceof Error && typeof callback == 'function') return callback(connection, null); - if(connection instanceof Error) return null; - if(connection == null && typeof callback == 'function') return callback(new Error("no primary server found"), null); - - // Ensure we truly are connected - if(!connection.isConnected()) { - return self.serverConfig._commandsStore.write( - { type:'insert' - , 'db_command':db_command - , 'options':options - , 'callback':callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } - - // Write the message out - connection.write(db_command, function(err) { - // Return the callback if it's not a safe operation and the callback is defined - if(typeof callback === 'function' && (safe == null || safe == false)) { - // Perform the callback - callback(err, null); - } else if(typeof callback === 'function') { - // Call the handler with an error - self.serverConfig._callHandler(db_command[1].getRequestId(), null, err); - } else if(typeof callback == 'function' && safe && safe.w == -1) { - // Call the handler with no error - self.serverConfig._callHandler(db_command[1].getRequestId(), null, null); - } else if(!safe || safe.w == -1) { - self.emit("error", err); - } - }); -} - -/** - * Execute an insert Command - * @ignore - * @api private - */ -Db.prototype._executeInsertCommand = function(db_command, options, callback) { - var self = this; - - // Unpack the parameters - if(callback == null && typeof options === 'function') { - callback = options; - options = {}; - } - - // Ensure options are not null - options = options == null ? {} : options; - - // Check if the user force closed the command - if(this._applicationClosed) { - if(typeof callback == 'function') { - return callback(new Error("db closed by application"), null); - } else { - throw new Error("db closed by application"); - } - } - - if(this.serverConfig.isDestroyed()) return callback(new Error("Connection was destroyed by application")); - - // Specific connection - var connection = options.connection; - // Check if the connection is actually live - if(connection - && (!connection.isConnected || !connection.isConnected())) connection = null; - - // Get config - var config = self.serverConfig; - // Check if we are connected - if(!connection && !config.canWrite() && config.isAutoReconnect()) { - self.serverConfig._commandsStore.write( - { type:'insert' - , 'db_command':db_command - , 'options':options - , 'callback':callback - , db: self - , executeQueryCommand: __executeQueryCommand - , executeInsertCommand: __executeInsertCommand - } - ); - } else if(!connection && !config.canWrite() && !config.isAutoReconnect()) { - return callback(new Error("no open connections"), null); - } else { - __executeInsertCommand(self, db_command, options, callback); - } -} - -/** - * Update command is the same - * @ignore - * @api private - */ -Db.prototype._executeUpdateCommand = Db.prototype._executeInsertCommand; -/** - * Remove command is the same - * @ignore - * @api private - */ -Db.prototype._executeRemoveCommand = Db.prototype._executeInsertCommand; - -/** - * Wrap a Mongo error document into an Error instance. - * Deprecated. Use utils.toError instead. - * - * @ignore - * @api private - * @deprecated - */ -Db.prototype.wrap = utils.toError; - -/** - * Default URL - * - * @classconstant DEFAULT_URL - **/ -Db.DEFAULT_URL = 'mongodb://localhost:27017/default'; - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the db instance or null if an error occured. - * @return {null} - * @api public - */ -Db.connect = function(url, options, callback) { - // Ensure correct mapping of the callback - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Ensure same behavior as previous version w:0 - if(url.indexOf("safe") == -1 - && url.indexOf("w") == -1 - && url.indexOf("journal") == -1 && url.indexOf("j") == -1 - && url.indexOf("fsync") == -1) options.w = 0; - - // Avoid circular require problem - var MongoClient = require('./mongo_client.js').MongoClient; - // Attempt to connect - MongoClient.connect.call(MongoClient, url, options, callback); -} - -/** - * State of the db connection - * @ignore - */ -Object.defineProperty(Db.prototype, "state", { enumerable: true - , get: function () { - return this.serverConfig._serverState; - } -}); - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options, callback) { - // Final options - var finalOptions = {w:1}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.options); - } else if(self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.safe); - } else if(typeof self.safe == "boolean") { - finalOptions = {w: (self.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * Legacy support - * - * @ignore - * @api private - */ -exports.connect = Db.connect; -exports.Db = Db; - -/** - * Remove all listeners to the db instance. - * @ignore - * @api private - */ -Db.prototype.removeAllEventListeners = function() { - this.removeAllListeners("close"); - this.removeAllListeners("error"); - this.removeAllListeners("timeout"); - this.removeAllListeners("parseError"); - this.removeAllListeners("poolReady"); - this.removeAllListeners("message"); -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/chunk.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/chunk.js deleted file mode 100644 index 59c6a267a..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/chunk.js +++ /dev/null @@ -1,221 +0,0 @@ -var Binary = require('bson').Binary, - ObjectID = require('bson').ObjectID; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = exports.Chunk = function(file, mongoObject, writeConcern) { - if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var self = this; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || {w:1}; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if(mongoObjectFinal.data == null) { - } else if(typeof mongoObjectFinal.data == "string") { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 'binary', 0); - this.data = new Binary(buffer); - } else if(Array.isArray(mongoObjectFinal.data)) { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data.join(''), 'binary', 0); - this.data = new Binary(buffer); - } else if(mongoObjectFinal.data instanceof Binary || Object.prototype.toString.call(mongoObjectFinal.data) == "[object Binary]") { - this.data = mongoObjectFinal.data; - } else if(Buffer.isBuffer(mongoObjectFinal.data)) { - } else { - throw Error("Illegal chunk format"); - } - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition); - this.internalPosition = this.data.length(); - if(callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length == 0 ? this.length() : length; - - if(this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if ((this.length() - this.internalPosition) >= length) { - var data = null; - if (this.data.buffer != null) { //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { //Native BSON - data = new Buffer(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition == this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(callback) { - var self = this; - - self.file.chunkCollection(function(err, collection) { - if(err) return callback(err); - - collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { - if(err) return callback(err); - - if(self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = {forceServerObjectId:true}; - for(var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.insert(mongoObject, options, function(err, collection) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *
    
    - *        {
    - *          '_id' : , // {number} id for this chunk
    - *          'files_id' : , // {number} foreign key to the file collection
    - *          'n' : , // {number} chunk number
    - *          'data' : , // {bson#Binary} the chunk data itself
    - *        }
    - *        
    - * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - 'files_id': this.file.fileId, - 'n': this.chunkNumber, - 'data': this.data}; - // If we are saving using a specific ObjectId - if(this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, "position", { enumerable: true - , get: function () { - return this.internalPosition; - } - , set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 256; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/grid.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/grid.js deleted file mode 100644 index aa695b723..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/grid.js +++ /dev/null @@ -1,103 +0,0 @@ -var GridStore = require('./gridstore').GridStore, - ObjectID = require('bson').ObjectID; - -/** - * A class representation of a simple Grid interface. - * - * @class Represents the Grid. - * @param {Db} db A database instance to interact with. - * @param {String} [fsName] optional different root collection for GridFS. - * @return {Grid} - */ -function Grid(db, fsName) { - - if(!(this instanceof Grid)) return new Grid(db, fsName); - - this.db = db; - this.fsName = fsName == null ? GridStore.DEFAULT_ROOT_COLLECTION : fsName; -} - -/** - * Puts binary data to the grid - * - * Options - * - **_id** {Any}, unique id for this file - * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * - **metadata** {Object}, arbitrary data the user wants to store. - * - * @param {Buffer} data buffer with Binary Data. - * @param {Object} [options] the options for the files. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.put = function(data, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - options = args.length ? args.shift() : {}; - // If root is not defined add our default one - options['root'] = options['root'] == null ? this.fsName : options['root']; - - // Return if we don't have a buffer object as data - if(!(Buffer.isBuffer(data))) return callback(new Error("Data object must be a buffer object"), null); - // Get filename if we are using it - var filename = options['filename'] || null; - // Get id if we are using it - var id = options['_id'] || null; - // Create gridstore - var gridStore = new GridStore(this.db, id, filename, "w", options); - gridStore.open(function(err, gridStore) { - if(err) return callback(err, null); - - gridStore.write(data, function(err, result) { - if(err) return callback(err, null); - - gridStore.close(function(err, result) { - if(err) return callback(err, null); - callback(null, result); - }) - }) - }) -} - -/** - * Get binary data to the grid - * - * @param {Any} id for file. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.get = function(id, callback) { - // Create gridstore - var gridStore = new GridStore(this.db, id, null, "r", {root:this.fsName}); - gridStore.open(function(err, gridStore) { - if(err) return callback(err, null); - - // Return the data - gridStore.read(function(err, data) { - return callback(err, data) - }); - }) -} - -/** - * Delete file from grid - * - * @param {Any} id for file. - * @param {Function} callback this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -Grid.prototype.delete = function(id, callback) { - // Create gridstore - GridStore.unlink(this.db, id, {root:this.fsName}, function(err, result) { - if(err) return callback(err, false); - return callback(null, true); - }); -} - -exports.Grid = Grid; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js deleted file mode 100644 index edf6c74fa..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/gridstore.js +++ /dev/null @@ -1,1558 +0,0 @@ -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - */ -var Chunk = require('./chunk').Chunk, - DbCommand = require('../commands/db_command').DbCommand, - ObjectID = require('bson').ObjectID, - Buffer = require('buffer').Buffer, - fs = require('fs'), - timers = require('timers'), - util = require('util'), - inherits = util.inherits, - ReadStream = require('./readstream').ReadStream, - Stream = require('stream'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -/** - * A class representation of a file stored in GridFS. - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwriten. - * - **w+"** - write in edit mode. - * - * Options - * - **root** {String}, root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * - **content_type** {String}, mime type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * - **chunk_size** {Number}, size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * - **metadata** {Object}, arbitrary data the user wants to store. - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - * @class Represents the GridStore. - * @param {Db} db A database instance to interact with. - * @param {Any} [id] optional unique id for this file - * @param {String} [filename] optional filename for this file, no unique constrain on the field - * @param {String} mode set the mode for this file. - * @param {Object} options optional properties to specify. - * @return {GridStore} - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - - var self = this; - this.db = db; - - // Call stream constructor - if(typeof Stream == 'function') { - Stream.call(this); - } else { - // 0.4.X backward compatibility fix - Stream.Stream.call(this); - } - - // Handle options - if(typeof options === 'undefined') options = {}; - // Handle mode - if(typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if(typeof mode == 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if(id instanceof ObjectID) { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if(typeof filename == 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? "r" : mode; - this.options = options == null ? {w:1} : options; - - // If we have no write concerns set w:1 as default - if(this.options.w == null - && this.options.j == null - && this.options.fsync == null) this.options.w = 1; - - // Set the root if overridden - this.root = this.options['root'] == null ? exports.GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = this.options.readPreference || 'primary'; - this.writeConcern = _getWriteConcern(this, this.options); - // Set default chunk size - this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; -} - -/** - * Code for the streaming capabilities of the gridstore object - * Most code from Aaron heckmanns project https://github.com/aheckmann/gridfs-stream - * Modified to work on the gridstore object itself - * @ignore - */ -if(typeof Stream == 'function') { - GridStore.prototype = { __proto__: Stream.prototype } -} else { - // Node 0.4.X compatibility code - GridStore.prototype = { __proto__: Stream.Stream.prototype } -} - -// Move pipe to _pipe -GridStore.prototype._pipe = GridStore.prototype.pipe; - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain an **{Error}** object and the second parameter will be null if an error occured. Otherwise, the first parameter will be null and the second will contain the reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.open = function(callback) { - if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ - callback(new Error("Illegal mode " + this.mode), null); - return; - } - - var self = this; - - if((self.mode == "w" || self.mode == "w+") && self.db.serverConfig.primary != null) { - // Get files collection - self.collection(function(err, collection) { - if(err) return callback(err); - - // Put index on filename - collection.ensureIndex([['filename', 1]], function(err, index) { - if(err) return callback(err); - - // Get chunk collection - self.chunkCollection(function(err, chunkCollection) { - if(err) return callback(err); - - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], function(err, index) { - if(err) return callback(err); - _open(self, callback); - }); - }); - }); - }); - } else { - // Open the gridstore - _open(self, callback); - } -}; - -/** - * Hidding the _open function - * @ignore - * @api private - */ -var _open = function(self, callback) { - self.collection(function(err, collection) { - if(err!==null) { - callback(new Error("at collection: "+err), null); - return; - } - - // Create the query - var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; - query = null == self.fileId && this.filename == null ? null : query; - - // Fetch the chunks - if(query != null) { - collection.find(query, {readPreference:self.readPreference}, function(err, cursor) { - if(err) return error(err); - - // Fetch the file - cursor.nextObject(function(err, doc) { - if(err) return error(err); - - // Check if the collection for the files exists otherwise prepare the new one - if(doc != null) { - self.fileId = doc._id; - self.filename = doc.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode != 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; - return error(new Error((self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename) + " does not exist", self)); - } - - // Process the mode of the object - if(self.mode == "r") { - nthChunk(self, 0, function(err, chunk) { - if(err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = self.length; - callback(null, self); - }); - } - }); - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = exports.GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - self.chunkCollection(function(err, collection2) { - if(err) return error(err); - - // No file exists set up write mode - if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.position = self.length; - callback(null, self); - }); - } - }); - } - }); - - // only pass error to callback once - function error (err) { - if(error.err) return; - callback(error.err = err); - } -}; - -/** - * Stores a file from the file system to the GridFS database. - * - * @param {String|Buffer|FileHandle} file the file to store. - * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the the second will contain the reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.writeFile = function (file, callback) { - var self = this; - if (typeof file === 'string') { - fs.open(file, 'r', function (err, fd) { - if(err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function (err, self) { - if(err) return callback(err, self); - - fs.fstat(file, function (err, stats) { - if(err) return callback(err, self); - - var offset = 0; - var index = 0; - var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); - - // Write a chunk - var writeChunk = function() { - fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { - if(err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, {n:index++}, self.writeConcern); - chunk.write(data, function(err, chunk) { - if(err) return callback(err, self); - - chunk.save(function(err, result) { - if(err) return callback(err, self); - - self.position = self.position + data.length; - - // Point to current chunk - self.currentChunk = chunk; - - if(offset >= stats.size) { - fs.close(file); - self.close(function(err, result) { - if(err) return callback(err, self); - return callback(null, self); - }); - } else { - return processor(writeChunk); - } - }); - }); - }); - } - - // Process the first write - processor(writeChunk); - }); - }); -}; - -/** - * Writes some data. This method will work properly only if initialized with mode - * "w" or "w+". - * - * @param string {string} The data to write. - * @param close {boolean=false} opt_argument Closes this file after writing if - * true. - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - * - * @ignore - * @api private - */ -var writeBuffer = function(self, buffer, close, callback) { - if(typeof close === "function") { callback = close; close = null; } - var finalClose = (close == null) ? false : close; - - if(self.mode[0] != "w") { - callback(new Error((self.referenceBy == REFERENCE_BY_ID ? self.toHexString() : self.filename) + " not opened for writing"), null); - } else { - if(self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while(leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - var firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - // If we have left over data write it - if(leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - // Write out all the chunks and then return - for(var i = 0; i < chunksToWrite.length; i++) { - var chunk = chunksToWrite[i]; - chunk.save(function(err, result) { - if(err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if(numberOfChunksToWrite <= 0) { - return callback(null, self); - } - }) - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - * @param callback {function(object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *
    
    - *        {
    - *          '_id' : , // {number} id for this file
    - *          'filename' : , // {string} name for this file
    - *          'contentType' : , // {string} mime type for this file
    - *          'length' : , // {number} size of this file?
    - *          'chunksize' : , // {number} chunk size used by this file
    - *          'uploadDate' : , // {Date}
    - *          'aliases' : , // {array of string}
    - *          'metadata' : , // {string}
    - *        }
    - *        
    - * - * @ignore - * @api private - */ -var buildMongoObject = function(self, callback) { - // // Keeps the final chunk number - // var chunkNumber = 0; - // var previousChunkSize = 0; - // // Get the correct chunk Number, if we have an empty chunk return the previous chunk number - // if(null != self.currentChunk && self.currentChunk.chunkNumber > 0 && self.currentChunk.position == 0) { - // chunkNumber = self.currentChunk.chunkNumber - 1; - // } else { - // chunkNumber = self.currentChunk.chunkNumber; - // previousChunkSize = self.currentChunk.position; - // } - - // // Calcuate the length - // var length = self.currentChunk != null ? (chunkNumber * self.chunkSize + previousChunkSize) : 0; - var mongoObject = { - '_id': self.fileId, - 'filename': self.filename, - 'contentType': self.contentType, - 'length': self.position ? self.position : 0, - 'chunkSize': self.chunkSize, - 'uploadDate': self.uploadDate, - 'aliases': self.aliases, - 'metadata': self.metadata - }; - - var md5Command = {filemd5:self.fileId, root:self.root}; - self.db.command(md5Command, function(err, results) { - mongoObject.md5 = results.md5; - callback(mongoObject); - }); -}; - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @param {Function} callback this will be called after executing this method. Passes an **{Error}** object to the first parameter and null to the second if an error occured. Otherwise, passes null to the first and a reference to this object to the second. - * @return {null} - * @api public - */ -GridStore.prototype.close = function(callback) { - var self = this; - - if(self.mode[0] == "w") { - if(self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save(function(err, chunk) { - if(err && typeof callback == 'function') return callback(err); - - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - // Build the mongo object - if(self.uploadDate != null) { - files.remove({'_id':self.fileId}, {safe:true}, function(err, collection) { - if(err && typeof callback == 'function') return callback(err); - - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(mongoObject) { - files.save(mongoObject, self.writeConcern, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } - } else if(self.mode[0] == "r") { - if(typeof callback == 'function') - callback(null, null); - } else { - if(typeof callback == 'function') - callback(new Error("Illegal mode " + self.mode), null); - } -}; - -/** - * Gets the nth chunk of this file. - * - * @param chunkNumber {number} The nth chunk to retrieve. - * @param callback {function(*, Chunk|object)} This will be called after - * executing this method. null will be passed to the first parameter while - * a new {@link Chunk} instance will be passed to the second parameter if - * the chunk was found or an empty object {} if not. - * - * @ignore - * @api private - */ -var nthChunk = function(self, chunkNumber, callback) { - self.chunkCollection(function(err, collection) { - if(err) return callback(err); - - collection.find({'files_id':self.fileId, 'n':chunkNumber}, {readPreference: self.readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.nextObject(function(err, chunk) { - if(err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); - }); - }); -}; - -/** - * - * @ignore - * @api private - */ -GridStore.prototype._nthChunk = function(chunkNumber, callback) { - nthChunk(this, chunkNumber, callback); -} - -/** - * @return {Number} The last chunk number of this file. - * - * @ignore - * @api private - */ -var lastChunkNumber = function(self) { - return Math.floor(self.length/self.chunkSize); -}; - -/** - * Retrieve this file's chunks collection. - * - * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured. - * @return {null} - * @api public - */ -GridStore.prototype.chunkCollection = function(callback) { - this.db.collection((this.root + ".chunks"), callback); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @param callback {function(*, boolean)} This will be called after this method - * executes. Passes null to the first and true to the second argument. - * - * @ignore - * @api private - */ -var deleteChunks = function(self, callback) { - if(self.fileId != null) { - self.chunkCollection(function(err, collection) { - if(err) return callback(err, false); - collection.remove({'files_id':self.fileId}, {safe:true}, function(err, result) { - if(err) return callback(err, false); - callback(null, true); - }); - }); - } else { - callback(null, true); - } -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @param {Function} callback this will be called after this method executes. Passes null to the first and true to the second argument. - * @return {null} - * @api public - */ -GridStore.prototype.unlink = function(callback) { - var self = this; - deleteChunks(this, function(err) { - if(err!==null) { - err.message = "at deleteChunks: " + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if(err!==null) { - err.message = "at collection: " + err.message; - return callback(err); - } - - collection.remove({'_id':self.fileId}, {safe:true}, function(err) { - callback(err, self); - }); - }); - }); -}; - -/** - * Retrieves the file collection associated with this object. - * - * @param {Function} callback this will be called after executing this method. An exception object will be passed to the first parameter when an error occured or null otherwise. A new **{Collection}** object will be passed to the second parameter if no error occured. - * @return {null} - * @api public - */ -GridStore.prototype.collection = function(callback) { - this.db.collection(this.root + ".files", callback); -}; - -/** - * Reads the data of this file. - * - * @param {String} [separator] the character to be recognized as the newline separator. - * @param {Function} callback This will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character. - * @return {null} - * @api public - */ -GridStore.prototype.readlines = function(separator, callback) { - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - separator = args.length ? args.shift() : "\n"; - - this.read(function(err, data) { - if(err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for(var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -}; - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.rewind = function(callback) { - var self = this; - - if(this.currentChunk.chunkNumber != 0) { - if(this.mode[0] == "w") { - deleteChunks(self, function(err, gridStore) { - if(err) return callback(err); - self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if(err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -}; - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @param {Number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {String|Buffer} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {Function} callback this will be called after this method is executed. null will be passed to the first parameter and a string containing the contents of the buffer concatenated with the contents read from this file will be passed to the second. - * @return {null} - * @api public - */ -GridStore.prototype.read = function(length, buffer, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if(finalLength == 0 && finalBuffer.length == 0) return callback(new Error("File does not exist"), null); - // Else return data - callback(null, finalBuffer); - } else { - var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) return callback(err); - - if(chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if (finalBuffer._index > 0) { - callback(null, finalBuffer) - } else { - callback(new Error("no chunks found for file, possibly corrupt"), null); - } - } - }); - } -} - -/** - * Retrieves the position of the read/write head of this file. - * - * @param {Function} callback This gets called after this method terminates. null is passed to the first parameter and the position is passed to the second. - * @return {null} - * @api public - */ -GridStore.prototype.tell = function(callback) { - callback(null, this.position); -}; - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @param {Number} [position] the position to seek to - * @param {Number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.seek = function(position, seekLocation, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - seekLocation = args.length ? args.shift() : null; - - var seekLocationFinal = seekLocation == null ? exports.GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if(seekLocationFinal == exports.GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if(seekLocationFinal == exports.GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition/self.chunkSize); - if(newChunkNumber != self.currentChunk.chunkNumber) { - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(err, self); - }); - }; - - if(self.mode[0] == 'w') { - self.currentChunk.save(function(err) { - if(err) return callback(err); - seekChunk(); - }); - } else { - seekChunk(); - } - } else { - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(null, self); - } -}; - -/** - * Verify if the file is at EOF. - * - * @return {Boolean} true if the read/write head is at the end of this file. - * @api public - */ -GridStore.prototype.eof = function() { - return this.position == this.length ? true : false; -}; - -/** - * Retrieves a single character from this file. - * - * @param {Function} callback this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {null} - * @api public - */ -GridStore.prototype.getc = function(callback) { - var self = this; - - if(self.eof()) { - callback(null, null); - } else if(self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -}; - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @param {String} string the string to write. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.puts = function(string, callback) { - var finalString = string.match(/\n$/) == null ? string + "\n" : string; - this.write(finalString, callback); -}; - -/** - * Returns read stream based on this GridStore file - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **end** {function() {}} the end event triggers when there is no more documents available. - * - **close** {function() {}} the close event triggers when the stream is closed. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - * @param {Boolean} autoclose if true current GridStore will be closed when EOF and 'close' event will be fired - * @return {null} - * @api public - */ -GridStore.prototype.stream = function(autoclose) { - return new ReadStream(autoclose, this); -}; - -/** -* The collection to be used for holding the files and chunks collection. -* -* @classconstant DEFAULT_ROOT_COLLECTION -**/ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** -* Default file mime type -* -* @classconstant DEFAULT_CONTENT_TYPE -**/ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** -* Seek mode where the given length is absolute. -* -* @classconstant IO_SEEK_SET -**/ -GridStore.IO_SEEK_SET = 0; - -/** -* Seek mode where the given length is an offset to the current read/write head. -* -* @classconstant IO_SEEK_CUR -**/ -GridStore.IO_SEEK_CUR = 1; - -/** -* Seek mode where the given length is an offset to the end of the file. -* -* @classconstant IO_SEEK_END -**/ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * Options - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - * @param {Db} db the database to query. - * @param {String} name the name of the file to look for. - * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {Function} callback this will be called after this method executes. Passes null to the first and passes true to the second if the file exists and false otherwise. - * @return {null} - * @api public - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - // Establish read preference - var readPreference = options.readPreference || 'primary'; - // Fetch collection - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + ".files", function(err, collection) { - if(err) return callback(err); - - // Build query - var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) - ? {'filename':fileIdObject} - : {'_id':fileIdObject}; // Attempt to locate file - - collection.find(query, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.nextObject(function(err, item) { - if(err) return callback(err); - callback(null, item == null ? false : true); - }); - }); - }); -}; - -/** - * Gets the list of files stored in the GridFS. - * - * @param {Db} db the database to query. - * @param {String} [rootCollection] the root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {Function} callback this will be called after this method executes. Passes null to the first and passes an array of strings containing the names of the files. - * @return {null} - * @api public - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - - // Ensure we have correct values - if(rootCollection != null && typeof rootCollection == 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || 'primary'; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection((rootCollectionFinal + ".files"), function(err, collection) { - if(err) return callback(err); - - collection.find({}, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.each(function(err, item) { - if(item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -}; - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @param {Db} db the database to query. - * @param {String} name the name of the file. - * @param {Number} [length] the size of data to read. - * @param {Number} [offset] the offset from the head of the file of which to start reading from. - * @param {Object} [options] the options for the file. - * @param {Function} callback this will be called after this method executes. A string with an error message will be passed to the first parameter when the length and offset combination exceeds the length of the file while an Error object will be passed if other forms of error occured, otherwise, a string is passed. The second parameter will contain the data read if successful or null if an error occured. - * @return {null} - * @api public - */ -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - // Make sure we are not reading out of bounds - if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); - if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); - if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); - - if(offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if(err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -}; - -/** - * Reads the data of this file. - * - * @param {Db} db the database to query. - * @param {String} name the name of the file. - * @param {String} [separator] the character to be recognized as the newline separator. - * @param {Object} [options] file options. - * @param {Function} callback this will be called after this method is executed. The first parameter will be null and the second parameter will contain an array of strings representing the entire data, each element representing a line including the separator character. - * @return {null} - * @api public - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - - var finalSeperator = separator == null ? "\n" : separator; - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -}; - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @param {Db} db the database to interact with. - * @param {String|Array} names the name/names of the files to delete. - * @param {Object} [options] the options for the files. - * @callback {Function} this will be called after this method is executed. The first parameter will contain an Error object if an error occured or null otherwise. The second parameter will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.unlink = function(db, names, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - options = args.length ? args.shift() : null; - - if(names.constructor == Array) { - var tc = 0; - for(var i = 0; i < names.length; i++) { - ++tc; - self.unlink(db, names[i], options, function(result) { - if(--tc == 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, "w", options).open(function(err, gridStore) { - if(err) return callback(err); - deleteChunks(gridStore, function(err, result) { - if(err) return callback(err); - gridStore.collection(function(err, collection) { - if(err) return callback(err); - collection.remove({'_id':gridStore.fileId}, {safe:true}, function(err, collection) { - callback(err, self); - }); - }); - }); - }); - } -}; - -/** - * Returns the current chunksize of the file. - * - * @field chunkSize - * @type {Number} - * @getter - * @setter - * @property return number of bytes in the current chunkSize. - */ -Object.defineProperty(GridStore.prototype, "chunkSize", { enumerable: true - , get: function () { - return this.internalChunkSize; - } - , set: function(value) { - if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } -}); - -/** - * The md5 checksum for this file. - * - * @field md5 - * @type {Number} - * @getter - * @setter - * @property return this files md5 checksum. - */ -Object.defineProperty(GridStore.prototype, "md5", { enumerable: true - , get: function () { - return this.internalMd5; - } -}); - -/** - * GridStore Streaming methods - * Handles the correct return of the writeable stream status - * @ignore - */ -Object.defineProperty(GridStore.prototype, "writable", { enumerable: true - , get: function () { - if(this._writeable == null) { - this._writeable = this.mode != null && this.mode.indexOf("w") != -1; - } - // Return the _writeable - return this._writeable; - } - , set: function(value) { - this._writeable = value; - } -}); - -/** - * Handles the correct return of the readable stream status - * @ignore - */ -Object.defineProperty(GridStore.prototype, "readable", { enumerable: true - , get: function () { - if(this._readable == null) { - this._readable = this.mode != null && this.mode.indexOf("r") != -1; - } - return this._readable; - } - , set: function(value) { - this._readable = value; - } -}); - -GridStore.prototype.paused; - -/** - * Handles the correct setting of encoding for the stream - * @ignore - */ -GridStore.prototype.setEncoding = fs.ReadStream.prototype.setEncoding; - -/** - * Handles the end events - * @ignore - */ -GridStore.prototype.end = function end(data) { - var self = this; - // allow queued data to write before closing - if(!this.writable) return; - this.writable = false; - - if(data) { - this._q.push(data); - } - - this.on('drain', function () { - self.close(function (err) { - if (err) return _error(self, err); - self.emit('close'); - }); - }); - - _flush(self); -} - -/** - * Handles the normal writes to gridstore - * @ignore - */ -var _writeNormal = function(self, data, close, callback) { - // If we have a buffer write it using the writeBuffer method - if(Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - // Wrap the string in a buffer and write - return writeBuffer(self, new Buffer(data, 'binary'), close, callback); - } -} - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @param {String|Buffer} data the data to write. - * @param {Boolean} [close] closes this file after writing if set to true. - * @param {Function} callback this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {null} - * @api public - */ -GridStore.prototype.write = function write(data, close, callback) { - // If it's a normal write delegate the call - if(typeof close == 'function' || typeof callback == 'function') { - return _writeNormal(this, data, close, callback); - } - - // Otherwise it's a stream write - var self = this; - if (!this.writable) { - throw new Error('GridWriteStream is not writable'); - } - - // queue data until we open. - if (!this._opened) { - // Set up a queue to save data until gridstore object is ready - this._q = []; - _openStream(self); - this._q.push(data); - return false; - } - - // Push data to queue - this._q.push(data); - _flush(this); - // Return write successful - return true; -} - -/** - * Handles the destroy part of a stream - * @ignore - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if(!this.writable) return; - this.readable = false; - if(this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -} - -/** - * Handles the destroySoon part of a stream - * @ignore - */ -GridStore.prototype.destroySoon = function destroySoon() { - // as soon as write queue is drained, destroy. - // may call destroy immediately if no data is queued. - if(!this._q.length) { - return this.destroy(); - } - this._destroying = true; -} - -/** - * Handles the pipe part of the stream - * @ignore - */ -GridStore.prototype.pipe = function(destination, options) { - var self = this; - // Open the gridstore - this.open(function(err, result) { - if(err) _errorRead(self, err); - if(!self.readable) return; - // Set up the pipe - self._pipe(destination, options); - // Emit the stream is open - self.emit('open'); - // Read from the stream - _read(self); - }) -} - -/** - * Internal module methods - * @ignore - */ -var _read = function _read(self) { - if (!self.readable || self.paused || self.reading) { - return; - } - - self.reading = true; - var stream = self._stream = self.stream(); - stream.paused = self.paused; - - stream.on('data', function (data) { - if (self._decoder) { - var str = self._decoder.write(data); - if (str.length) self.emit('data', str); - } else { - self.emit('data', data); - } - }); - - stream.on('end', function (data) { - self.emit('end', data); - }); - - stream.on('error', function (data) { - _errorRead(self, data); - }); - - stream.on('close', function (data) { - self.emit('close', data); - }); - - self.pause = function () { - // native doesn't always pause. - // bypass its pause() method to hack it - self.paused = stream.paused = true; - } - - self.resume = function () { - if(!self.paused) return; - - self.paused = false; - stream.resume(); - self.readable = stream.readable; - } - - self.destroy = function () { - self.readable = false; - stream.destroy(); - } -} - -/** - * pause - * @ignore - */ -GridStore.prototype.pause = function pause () { - // Overridden when the GridStore opens. - this.paused = true; -} - -/** - * resume - * @ignore - */ -GridStore.prototype.resume = function resume () { - // Overridden when the GridStore opens. - this.paused = false; -} - -/** - * Internal module methods - * @ignore - */ -var _flush = function _flush(self, _force) { - if (!self._opened) return; - if (!_force && self._flushing) return; - self._flushing = true; - - // write the entire q to gridfs - if (!self._q.length) { - self._flushing = false; - self.emit('drain'); - - if(self._destroying) { - self.destroy(); - } - return; - } - - self.write(self._q.shift(), function (err, store) { - if (err) return _error(self, err); - self.emit('progress', store.position); - _flush(self, true); - }); -} - -var _openStream = function _openStream (self) { - if(self._opening == true) return; - self._opening = true; - - // Open the store - self.open(function (err, gridstore) { - if (err) return _error(self, err); - self._opened = true; - self.emit('open'); - _flush(self); - }); -} - -var _error = function _error(self, err) { - self.destroy(); - self.emit('error', err); -} - -var _errorRead = function _errorRead (self, err) { - self.readable = false; - self.emit('error', err); -} - -/** - * @ignore - */ -var _hasWriteConcern = function(errorOptions) { - return errorOptions == true - || errorOptions.w > 0 - || errorOptions.w == 'majority' - || errorOptions.j == true - || errorOptions.journal == true - || errorOptions.fsync == true -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options, callback) { - // Final options - var finalOptions = {w:1}; - options = options || {}; - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(self.db.safe.w != null || typeof self.db.safe.j == 'boolean' || typeof self.db.safe.journal == 'boolean' || typeof self.db.safe.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.safe); - } else if(self.db.options.w != null || typeof self.db.options.j == 'boolean' || typeof self.db.options.journal == 'boolean' || typeof self.db.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.db.options); - } else if(typeof self.db.safe == "boolean") { - finalOptions = {w: (self.db.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw new Error("No acknowlegement using w < 1 cannot be combined with journal:true or fsync:true"); - - // Return the options - return finalOptions; -} - -/** - * @ignore - * @api private - */ -exports.GridStore = GridStore; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/readstream.js deleted file mode 100644 index 30ea725ed..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/gridfs/readstream.js +++ /dev/null @@ -1,192 +0,0 @@ -var Stream = require('stream').Stream, - timers = require('timers'), - util = require('util'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - * ReadStream - * - * Returns a stream interface for the **file**. - * - * Events - * - **data** {function(item) {}} the data event triggers when a document is ready. - * - **end** {function() {}} the end event triggers when there is no more documents available. - * - **close** {function() {}} the close event triggers when the stream is closed. - * - **error** {function(err) {}} the error event triggers if an error happens. - * - * @class Represents a GridFS File Stream. - * @param {Boolean} autoclose automatically close file when the stream reaches the end. - * @param {GridStore} cursor a cursor object that the stream wraps. - * @return {ReadStream} - */ -function ReadStream(autoclose, gstore) { - if (!(this instanceof ReadStream)) return new ReadStream(autoclose, gstore); - Stream.call(this); - - this.autoclose = !!autoclose; - this.gstore = gstore; - - this.finalLength = gstore.length - gstore.position; - this.completedLength = 0; - this.currentChunkNumber = gstore.currentChunk.chunkNumber; - - this.paused = false; - this.readable = true; - this.pendingChunk = null; - this.executing = false; - - // Calculate the number of chunks - this.numberOfChunks = Math.ceil(gstore.length/gstore.chunkSize); - - // This seek start position inside the current chunk - this.seekStartPosition = gstore.position - (this.currentChunkNumber * gstore.chunkSize); - - var self = this; - processor(function() { - self._execute(); - }); -}; - -/** - * Inherit from Stream - * @ignore - * @api private - */ -ReadStream.prototype.__proto__ = Stream.prototype; - -/** - * Flag stating whether or not this stream is readable. - */ -ReadStream.prototype.readable; - -/** - * Flag stating whether or not this stream is paused. - */ -ReadStream.prototype.paused; - -/** - * @ignore - * @api private - */ -ReadStream.prototype._execute = function() { - if(this.paused === true || this.readable === false) { - return; - } - - var gstore = this.gstore; - var self = this; - // Set that we are executing - this.executing = true; - - var last = false; - var toRead = 0; - - if(gstore.currentChunk.chunkNumber >= (this.numberOfChunks - 1)) { - self.executing = false; - last = true; - } - - // Data setup - var data = null; - - // Read a slice (with seek set if none) - if(this.seekStartPosition > 0 && (gstore.currentChunk.length() - this.seekStartPosition) > 0) { - data = gstore.currentChunk.readSlice(gstore.currentChunk.length() - this.seekStartPosition); - this.seekStartPosition = 0; - } else { - data = gstore.currentChunk.readSlice(gstore.currentChunk.length()); - } - - // Return the data - if(data != null && gstore.currentChunk.chunkNumber == self.currentChunkNumber) { - self.currentChunkNumber = self.currentChunkNumber + 1; - self.completedLength += data.length; - self.pendingChunk = null; - self.emit("data", data); - } - - if(last === true) { - self.readable = false; - self.emit("end"); - - if(self.autoclose === true) { - if(gstore.mode[0] == "w") { - gstore.close(function(err, doc) { - if (err) { - self.emit("error", err); - return; - } - self.readable = false; - self.emit("close", doc); - }); - } else { - self.readable = false; - self.emit("close"); - } - } - } else { - gstore._nthChunk(gstore.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) { - self.readable = false; - self.emit("error", err); - self.executing = false; - return; - } - - self.pendingChunk = chunk; - if(self.paused === true) { - self.executing = false; - return; - } - - gstore.currentChunk = self.pendingChunk; - self._execute(); - }); - } -}; - -/** - * Pauses this stream, then no farther events will be fired. - * - * @ignore - * @api public - */ -ReadStream.prototype.pause = function() { - if(!this.executing) { - this.paused = true; - } -}; - -/** - * Destroys the stream, then no farther events will be fired. - * - * @ignore - * @api public - */ -ReadStream.prototype.destroy = function() { - this.readable = false; - // Emit close event - this.emit("close"); -}; - -/** - * Resumes this stream. - * - * @ignore - * @api public - */ -ReadStream.prototype.resume = function() { - if(this.paused === false || !this.readable) { - return; - } - - this.paused = false; - var self = this; - processor(function() { - self._execute(); - }); -}; - -exports.ReadStream = ReadStream; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/index.js deleted file mode 100644 index 91d28df4f..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/index.js +++ /dev/null @@ -1,69 +0,0 @@ -try { - exports.BSONPure = require('bson').BSONPure; - exports.BSONNative = require('bson').BSONNative; -} catch(err) { - // do nothing -} - -// export the driver version -exports.version = require('../../package').version; - -[ 'commands/base_command' - , 'admin' - , 'collection' - , 'connection/read_preference' - , 'connection/connection' - , 'connection/server' - , 'connection/mongos' - , 'connection/repl_set/repl_set' - , 'mongo_client' - , 'cursor' - , 'db' - , 'mongo_client' - , 'gridfs/grid' - , 'gridfs/chunk' - , 'gridfs/gridstore'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// backwards compat -exports.ReplSetServers = exports.ReplSet; -// Add BSON Classes -exports.Binary = require('bson').Binary; -exports.Code = require('bson').Code; -exports.DBRef = require('bson').DBRef; -exports.Double = require('bson').Double; -exports.Long = require('bson').Long; -exports.MinKey = require('bson').MinKey; -exports.MaxKey = require('bson').MaxKey; -exports.ObjectID = require('bson').ObjectID; -exports.Symbol = require('bson').Symbol; -exports.Timestamp = require('bson').Timestamp; -// Add BSON Parser -exports.BSON = require('bson').BSONPure.BSON; - -// Get the Db object -var Db = require('./db').Db; -// Set up the connect function -var connect = Db.connect; -var obj = connect; -// Map all values to the exports value -for(var name in exports) { - obj[name] = exports[name]; -} - -// Add the pure and native backward compatible functions -exports.pure = exports.native = function() { - return obj; -} - -// Map all values to the exports value -for(var name in exports) { - connect[name] = exports[name]; -} - -// Set our exports to be the connect function -module.exports = connect; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/mongo_client.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/mongo_client.js deleted file mode 100644 index a7372bf39..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/mongo_client.js +++ /dev/null @@ -1,419 +0,0 @@ -var Db = require('./db').Db - , Server = require('./connection/server').Server - , Mongos = require('./connection/mongos').Mongos - , ReplSet = require('./connection/repl_set/repl_set').ReplSet - , ReadPreference = require('./connection/read_preference').ReadPreference - , inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , parse = require('./connection/url_parser').parse; - -/** - * Create a new MongoClient instance. - * - * Options - * - **w**, {Number/String, > -1 || 'majority' || tag name} the write concern for the operation where < 1 is no acknowlegement of write and w >= 1, w = 'majority' or tag acknowledges the write - * - **wtimeout**, {Number, 0} set the timeout for waiting for write concern to finish (combines with w option) - * - **fsync**, (Boolean, default:false) write waits for fsync before returning - * - **journal**, (Boolean, default:false) write waits for journal sync before returning - * - **readPreference** {String}, the prefered read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * - **native_parser** {Boolean, default:false}, use c++ bson parser. - * - **forceServerObjectId** {Boolean, default:false}, force server to create _id fields instead of client. - * - **pkFactory** {Object}, object overriding the basic ObjectID primary key generation. - * - **serializeFunctions** {Boolean, default:false}, serialize functions. - * - **raw** {Boolean, default:false}, peform operations using raw bson buffers. - * - **recordQueryStats** {Boolean, default:false}, record query statistics during execution. - * - **retryMiliSeconds** {Number, default:5000}, number of miliseconds between retries. - * - **numberOfRetries** {Number, default:5}, number of retries off connection. - * - * Deprecated Options - * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. - * - * @class Represents a MongoClient - * @param {Object} serverConfig server config object. - * @param {Object} [options] additional options for the collection. - */ -function MongoClient(serverConfig, options) { - if(serverConfig != null) { - options = options == null ? {} : options; - // If no write concern is set set the default to w:1 - if(options != null && !options.journal && !options.w && !options.fsync) { - options.w = 1; - } - - // The internal db instance we are wrapping - this._db = new Db('test', serverConfig, options); - } -} - -/** - * @ignore - */ -inherits(MongoClient, EventEmitter); - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.connect = function(url, options, callback) { - var self = this; - - if(typeof options == 'function') { - callback = options; - options = {}; - } - - MongoClient.connect(url, options, function(err, db) { - if(err) return callback(err, db); - // Store internal db instance reference - self._db = db; - // Emit open and perform callback - self.emit("open", err, db); - callback(err, db); - }); -} - -/** - * Initialize the database connection. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the connected mongoclient or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.open = function(callback) { - // Self reference - var self = this; - // Open the db - this._db.open(function(err, db) { - if(err) return callback(err, null); - // Emit open event - self.emit("open", err, db); - // Callback - callback(null, self); - }) -} - -/** - * Close the current db connection, including all the child db instances. Emits close event if no callback is provided. - * - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the results from the close method or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.prototype.close = function(callback) { - this._db.close(callback); -} - -/** - * Create a new Db instance sharing the current socket connections. - * - * @param {String} dbName the name of the database we want to use. - * @return {Db} a db instance using the new database. - * @api public - */ -MongoClient.prototype.db = function(dbName) { - return this._db.db(dbName); -} - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Options - * - **uri_decode_auth** {Boolean, default:false} uri decode the user name and password for authentication - * - **db** {Object, default: null} a hash off options to set on the db object, see **Db constructor** - * - **server** {Object, default: null} a hash off options to set on the server objects, see **Server** constructor** - * - **replSet** {Object, default: null} a hash off options to set on the replSet object, see **ReplSet** constructor** - * - **mongos** {Object, default: null} a hash off options to set on the mongos object, see **Mongos** constructor** - * - * @param {String} url connection url for MongoDB. - * @param {Object} [options] optional options for insert command - * @param {Function} callback this will be called after executing this method. The first parameter will contain the Error object if an error occured, or null otherwise. While the second parameter will contain the initialized db object or null if an error occured. - * @return {null} - * @api public - */ -MongoClient.connect = function(url, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Set default empty server options - var serverOptions = options.server || {}; - var mongosOptions = options.mongos || {}; - var replSetServersOptions = options.replSet || options.replSetServers || {}; - var dbOptions = options.db || {}; - - // If callback is null throw an exception - if(callback == null) - throw new Error("no callback function provided"); - - // Parse the string - var object = parse(url, options); - // Merge in any options for db in options object - if(dbOptions) { - for(var name in dbOptions) object.db_options[name] = dbOptions[name]; - } - - // Added the url to the options - object.db_options.url = url; - - // Merge in any options for server in options object - if(serverOptions) { - for(var name in serverOptions) object.server_options[name] = serverOptions[name]; - } - - // Merge in any replicaset server options - if(replSetServersOptions) { - for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; - } - - // Merge in any replicaset server options - if(mongosOptions) { - for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; - } - - // We need to ensure that the list of servers are only either direct members or mongos - // they cannot be a mix of monogs and mongod's - var totalNumberOfServers = object.servers.length; - var totalNumberOfMongosServers = 0; - var totalNumberOfMongodServers = 0; - var serverConfig = null; - var errorServers = {}; - - // Failure modes - if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); - - // If we have no db setting for the native parser try to set the c++ one first - object.db_options.native_parser = _setNativeParser(object.db_options); - // If no auto_reconnect is set, set it to true as default for single servers - if(typeof object.server_options.auto_reconnect != 'boolean') { - object.server_options.auto_reconnect = true; - } - - // If we have more than a server, it could be replicaset or mongos list - // need to verify that it's one or the other and fail if it's a mix - // Connect to all servers and run ismaster - for(var i = 0; i < object.servers.length; i++) { - // Set up socket options - var _server_options = {poolSize:1, socketOptions:{connectTimeoutMS:1000}, auto_reconnect:false}; - - // Ensure we have ssl setup for the servers - if(object.rs_options.ssl) { - _server_options.ssl = object.rs_options.ssl; - _server_options.sslValidate = object.rs_options.sslValidate; - _server_options.sslCA = object.rs_options.sslCA; - _server_options.sslCert = object.rs_options.sslCert; - _server_options.sslKey = object.rs_options.sslKey; - _server_options.sslPass = object.rs_options.sslPass; - } else if(object.server_options.ssl) { - _server_options.ssl = object.server_options.ssl; - _server_options.sslValidate = object.server_options.sslValidate; - _server_options.sslCA = object.server_options.sslCA; - _server_options.sslCert = object.server_options.sslCert; - _server_options.sslKey = object.server_options.sslKey; - _server_options.sslPass = object.server_options.sslPass; - } - - // Set up the Server object - var _server = object.servers[i].domain_socket - ? new Server(object.servers[i].domain_socket, _server_options) - : new Server(object.servers[i].host, object.servers[i].port, _server_options); - - var connectFunction = function(__server) { - // Attempt connect - new Db(object.dbName, __server, {safe:false, native_parser:false}).open(function(err, db) { - // Update number of servers - totalNumberOfServers = totalNumberOfServers - 1; - // If no error do the correct checks - if(!err) { - // Close the connection - db.close(true); - var isMasterDoc = db.serverConfig.isMasterDoc; - // Check what type of server we have - if(isMasterDoc.setName) totalNumberOfMongodServers++; - if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; - } else { - errorServers[__server.host + ":" + __server.port] = __server; - } - - if(totalNumberOfServers == 0) { - // If we have a mix of mongod and mongos, throw an error - if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { - return process.nextTick(function() { - try { - callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - - if(totalNumberOfMongodServers == 0 && object.servers.length == 1) { - var obj = object.servers[0]; - serverConfig = obj.domain_socket ? - new Server(obj.domain_socket, object.server_options) - : new Server(obj.host, obj.port, object.server_options); - } else if(totalNumberOfMongodServers > 0 || totalNumberOfMongosServers > 0) { - var finalServers = object.servers - .filter(function(serverObj) { - return errorServers[serverObj.host + ":" + serverObj.port] == null; - }) - .map(function(serverObj) { - return new Server(serverObj.host, serverObj.port, object.server_options); - }); - // Clean out any error servers - errorServers = {}; - // Set up the final configuration - if(totalNumberOfMongodServers > 0) { - serverConfig = new ReplSet(finalServers, object.rs_options); - } else { - serverConfig = new Mongos(finalServers, object.mongos_options); - } - } - - if(serverConfig == null) { - return process.nextTick(function() { - try { - callback(new Error("Could not locate any valid servers in initial seed list")); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - // Ensure no firing off open event before we are ready - serverConfig.emitOpen = false; - // Set up all options etc and connect to the database - _finishConnecting(serverConfig, object, options, callback) - } - }); - } - - // Wrap the context of the call - connectFunction(_server); - } -} - -var _setNativeParser = function(db_options) { - if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; - - try { - require('bson').BSONNative.BSON; - return true; - } catch(err) { - return false; - } -} - -var _finishConnecting = function(serverConfig, object, options, callback) { - // Safe settings - var safe = {}; - // Build the safe parameter if needed - if(object.db_options.journal) safe.j = object.db_options.journal; - if(object.db_options.w) safe.w = object.db_options.w; - if(object.db_options.fsync) safe.fsync = object.db_options.fsync; - if(object.db_options.wtimeoutMS) safe.wtimeout = object.db_options.wtimeoutMS; - - // If we have a read Preference set - if(object.db_options.read_preference) { - var readPreference = new ReadPreference(object.db_options.read_preference); - // If we have the tags set up - if(object.db_options.read_preference_tags) - readPreference = new ReadPreference(object.db_options.read_preference, object.db_options.read_preference_tags); - // Add the read preference - object.db_options.readPreference = readPreference; - } - - // No safe mode if no keys - if(Object.keys(safe).length == 0) safe = false; - - // Add the safe object - object.db_options.safe = safe; - - // Set up the db options - var db = new Db(object.dbName, serverConfig, object.db_options); - // Open the db - db.open(function(err, db){ - if(err) { - return process.nextTick(function() { - try { - callback(err, null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - - if(db.options !== null && !db.options.safe && !db.options.journal - && !db.options.w && !db.options.fsync && typeof db.options.w != 'number' - && (db.options.safe == false && object.db_options.url.indexOf("safe=") == -1)) { - db.options.w = 1; - } - - if(err == null && object.auth){ - // What db to authenticate against - var authentication_db = db; - if(object.db_options && object.db_options.authSource) { - authentication_db = db.db(object.db_options.authSource); - } - - // Build options object - var options = {}; - if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; - if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; - - // Authenticate - authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ - if(success){ - process.nextTick(function() { - try { - callback(null, db); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } else { - if(db) db.close(); - process.nextTick(function() { - try { - callback(err ? err : new Error('Could not authenticate user ' + auth[0]), null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - }); - } else { - process.nextTick(function() { - try { - callback(err, db); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - }); -} - - -exports.MongoClient = MongoClient; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js deleted file mode 100644 index 21e8cec39..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js +++ /dev/null @@ -1,83 +0,0 @@ -var Long = require('bson').Long - , timers = require('timers'); - -// Set processor, setImmediate if 0.10 otherwise nextTick -var processor = require('../utils').processor(); - -/** - Reply message from mongo db -**/ -var MongoReply = exports.MongoReply = function() { - this.documents = []; - this.index = 0; -}; - -MongoReply.prototype.parseHeader = function(binary_reply, bson) { - // Unpack the standard header first - this.messageLength = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Fetch the request id for this reply - this.requestId = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Fetch the id of the request that triggered the response - this.responseTo = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - // Skip op-code field - this.index = this.index + 4 + 4; - // Unpack the reply message - this.responseFlag = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Unpack the cursor id (a 64 bit long integer) - var low_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - var high_bits = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - this.cursorId = new Long(low_bits, high_bits); - // Unpack the starting from - this.startingFrom = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; - // Unpack the number of objects returned - this.numberReturned = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - this.index = this.index + 4; -} - -MongoReply.prototype.parseBody = function(binary_reply, bson, raw, callback) { - raw = raw == null ? false : raw; - - try { - // Let's unpack all the bson documents, deserialize them and store them - for(var object_index = 0; object_index < this.numberReturned; object_index++) { - var _options = {promoteLongs: bson.promoteLongs}; - - // Read the size of the bson object - var bsonObjectSize = binary_reply[this.index] | binary_reply[this.index + 1] << 8 | binary_reply[this.index + 2] << 16 | binary_reply[this.index + 3] << 24; - - // If we are storing the raw responses to pipe straight through - if(raw) { - // Deserialize the object and add to the documents array - this.documents.push(binary_reply.slice(this.index, this.index + bsonObjectSize)); - } else { - // Deserialize the object and add to the documents array - this.documents.push(bson.deserialize(binary_reply.slice(this.index, this.index + bsonObjectSize), _options)); - } - - // Adjust binary index to point to next block of binary bson data - this.index = this.index + bsonObjectSize; - } - - // No error return - callback(null); - } catch(err) { - return callback(err); - } -} - -MongoReply.prototype.is_error = function(){ - if(this.documents.length == 1) { - return this.documents[0].ok == 1 ? false : true; - } - return false; -}; - -MongoReply.prototype.error_message = function() { - return this.documents.length == 1 && this.documents[0].ok == 1 ? '' : this.documents[0].errmsg; -}; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/utils.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/utils.js deleted file mode 100644 index 1e8c6238a..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/lib/mongodb/utils.js +++ /dev/null @@ -1,173 +0,0 @@ -var timers = require('timers'); - -/** - * Sort functions, Normalize and prepare sort parameters - */ -var formatSortValue = exports.formatSortValue = function(sortDirection) { - var value = ("" + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error("Illegal sort clause, must be of the form " - + "[['field1', '(ascending|descending)'], " - + "['field2', '(ascending|descending)']]"); - } -}; - -var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - - if (Array.isArray(sortValue)) { - for(var i = 0; i < sortValue.length; i++) { - if(sortValue[i].constructor == String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if(Object.prototype.toString.call(sortValue) === '[object Object]') { - orderBy = sortValue; - } else if (sortValue.constructor == String) { - orderBy[sortValue] = 1; - } else { - throw new Error("Illegal sort clause, must be of the form " + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); - } - - return orderBy; -}; - -exports.encodeInt = function(value) { - var buffer = new Buffer(4); - buffer[3] = (value >> 24) & 0xff; - buffer[2] = (value >> 16) & 0xff; - buffer[1] = (value >> 8) & 0xff; - buffer[0] = value & 0xff; - return buffer; -} - -exports.encodeIntInPlace = function(value, buffer, index) { - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; -} - -exports.encodeCString = function(string) { - var buf = new Buffer(string, 'utf8'); - return [buf, new Buffer([0])]; -} - -exports.decodeUInt32 = function(array, index) { - return array[index] | array[index + 1] << 8 | array[index + 2] << 16 | array[index + 3] << 24; -} - -// Decode the int -exports.decodeUInt8 = function(array, index) { - return array[index]; -} - -/** - * Context insensitive type checks - */ - -var toString = Object.prototype.toString; - -exports.isObject = function (arg) { - return '[object Object]' == toString.call(arg) -} - -exports.isArray = function (arg) { - return Array.isArray(arg) || - 'object' == typeof arg && '[object Array]' == toString.call(arg) -} - -exports.isDate = function (arg) { - return 'object' == typeof arg && '[object Date]' == toString.call(arg) -} - -exports.isRegExp = function (arg) { - return 'object' == typeof arg && '[object RegExp]' == toString.call(arg) -} - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error; - var e = new Error(msg); - e.name = 'MongoError'; - - // Get all object keys - var keys = typeof error == 'object' - ? Object.keys(error) - : []; - - for(var i = 0; i < keys.length; i++) { - e[keys[i]] = error[keys[i]]; - } - - return e; -} -exports.toError = toError; - -/** - * Convert a single level object to an array - * @ignore - * @api private - */ -exports.objectToArray = function(object) { - var list = []; - - for(var name in object) { - list.push(object[name]) - } - - return list; -} - -/** - * Handle single command document return - * @ignore - * @api private - */ -exports.handleSingleCommandResultReturn = function(override_value_true, override_value_false, callback) { - return function(err, result, connection) { - if(err) return callback(err, null); - if(!result || !result.documents || result.documents.length == 0) - if(callback) return callback(toError("command failed to return results"), null) - if(result.documents[0].ok == 1) { - if(override_value_true) return callback(null, override_value_true) - if(callback) return callback(null, result.documents[0]); - } - - // Return the error from the document - if(callback) return callback(toError(result.documents[0]), override_value_false); - } -} - -/** - * Return correct processor - * @ignore - * @api private - */ -exports.processor = function() { - // Set processor, setImmediate if 0.10 otherwise nextTick - process.maxTickDepth = Infinity; - var processor = timers.setImmediate ? timers.setImmediate : process.nextTick; - // processor = process.nextTick; - return processor; -} - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/.travis.yml b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/.travis.yml deleted file mode 100644 index 94740d045..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - 0.9 # development version of 0.8, may be unstable \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/Makefile deleted file mode 100644 index 77ce4e040..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -NODE = node -NPM = npm -NODEUNIT = node_modules/nodeunit/bin/nodeunit - -all: clean node_gyp - -test: clean node_gyp - npm test - -node_gyp: clean - node-gyp configure build - -clean: - node-gyp clean - -browserify: - node_modules/.bin/onejs build browser_build/package.json browser_build/bson.js - -.PHONY: all diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/README.md b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/README.md deleted file mode 100644 index 1a6fc2baf..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/README.md +++ /dev/null @@ -1,45 +0,0 @@ -Javascript + C++ BSON parser -============================ - -This BSON parser is primarily meant for usage with the `mongodb` node.js driver. However thanks to such wonderful tools at `onejs` we are able to package up a BSON parser that will work in the browser aswell. The current build is located in the `browser_build/bson.js` file. - -A simple example on how to use it - - - - - - - - - It's got two simple methods to use in your application. - - * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** - * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports - - * BSON.deserialize(buffer, options, isArray) - * Options - * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * @param {TypedArray/Array} a TypedArray/Array containing the BSON data - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/binding.gyp b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/binding.gyp deleted file mode 100644 index 42445d325..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/binding.gyp +++ /dev/null @@ -1,17 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'bson', - 'sources': [ 'ext/bson.cc' ], - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'conditions': [ - ['OS=="mac"', { - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' - } - }] - ] - } - ] -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/browser_build/bson.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/browser_build/bson.js deleted file mode 100644 index b13f8eeb1..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,4843 +0,0 @@ -var bson = (function(){ - - var pkgmap = {}, - global = {}, - nativeRequire = typeof require != 'undefined' && require, - lib, ties, main, async; - - function exports(){ return main(); }; - - exports.main = exports; - exports.module = module; - exports.packages = pkgmap; - exports.pkg = pkg; - exports.require = function require(uri){ - return pkgmap.main.index.require(uri); - }; - - - ties = {}; - - aliases = {}; - - - return exports; - -function join() { - return normalize(Array.prototype.join.call(arguments, "/")); -}; - -function normalize(path) { - var ret = [], parts = path.split('/'), cur, prev; - - var i = 0, l = parts.length-1; - for (; i <= l; i++) { - cur = parts[i]; - - if (cur === "." && prev !== undefined) continue; - - if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { - ret.pop(); - prev = ret.slice(-1)[0]; - } else { - if (prev === ".") ret.pop(); - ret.push(cur); - prev = cur; - } - } - - return ret.join("/"); -}; - -function dirname(path) { - return path && path.substr(0, path.lastIndexOf("/")) || "."; -}; - -function findModule(workingModule, uri){ - var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), - moduleIndexId = join(moduleId, 'index'), - pkg = workingModule.pkg, - module; - - var i = pkg.modules.length, - id; - - while(i-->0){ - id = pkg.modules[i].id; - - if(id==moduleId || id == moduleIndexId){ - module = pkg.modules[i]; - break; - } - } - - return module; -} - -function newRequire(callingModule){ - function require(uri){ - var module, pkg; - - if(/^\./.test(uri)){ - module = findModule(callingModule, uri); - } else if ( ties && ties.hasOwnProperty( uri ) ) { - return ties[uri]; - } else if ( aliases && aliases.hasOwnProperty( uri ) ) { - return require(aliases[uri]); - } else { - pkg = pkgmap[uri]; - - if(!pkg && nativeRequire){ - try { - pkg = nativeRequire(uri); - } catch (nativeRequireError) {} - - if(pkg) return pkg; - } - - if(!pkg){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module = pkg.index; - } - - if(!module){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module.parent = callingModule; - return module.call(); - }; - - - return require; -} - - -function module(parent, id, wrapper){ - var mod = { pkg: parent, id: id, wrapper: wrapper }, - cached = false; - - mod.exports = {}; - mod.require = newRequire(mod); - - mod.call = function(){ - if(cached) { - return mod.exports; - } - - cached = true; - - global.require = mod.require; - - mod.wrapper(mod, mod.exports, global, global.require); - return mod.exports; - }; - - if(parent.mainModuleId == mod.id){ - parent.index = mod; - parent.parents.length === 0 && ( main = mod.call ); - } - - parent.modules.push(mod); -} - -function pkg(/* [ parentId ...], wrapper */){ - var wrapper = arguments[ arguments.length - 1 ], - parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), - ctx = wrapper(parents); - - - pkgmap[ctx.name] = ctx; - - arguments.length == 1 && ( pkgmap.main = ctx ); - - return function(modules){ - var id; - for(id in modules){ - module(ctx, id, modules[id]); - } - }; -} - - -}(this)); - -bson.pkg(function(parents){ - - return { - 'name' : 'bson', - 'mainModuleId' : 'bson', - 'modules' : [], - 'parents' : parents - }; - -})({ 'binary': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - - -}, - - - -'binary_parser': function(module, exports, global, require, undefined){ - /** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; - -}, - - - -'bson': function(module, exports, global, require, undefined){ - var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] || true; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; - -}, - - - -'code': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; -}, - - - -'db_ref': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; -}, - - - -'double': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; -}, - - - -'float_parser': function(module, exports, global, require, undefined){ - // Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; -}, - - - -'index': function(module, exports, global, require, undefined){ - try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -}, - - - -'long': function(module, exports, global, require, undefined){ - // 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; -}, - - - -'max_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; -}, - - - -'min_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; -}, - - - -'objectid': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId aswell as ObjectID -var ObjectId = ObjectID; - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = '' - , number - , value; - - for (var index = 0, len = this.id.length; index < len; index++) { - value = BinaryParser.toByte(this.id[index]); - number = value <= 15 - ? '0' + value.toString(16) - : value.toString(16); - hexString = hexString + number; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = 0; - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; - -}, - - - -'symbol': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; -}, - - - -'timestamp': function(module, exports, global, require, undefined){ - // 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; -}, - - }); - - -if(typeof module != 'undefined' && module.exports ){ - module.exports = bson; - - if( !module.parent ){ - bson(); - } -} - -if(typeof window != 'undefined' && typeof require == 'undefined'){ - window.require = bson.require; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/browser_build/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/browser_build/package.json deleted file mode 100644 index 3ebb58761..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../lib/bson/bson" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Makefile deleted file mode 100644 index 647bff8f0..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Makefile +++ /dev/null @@ -1,332 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= flock $(builddir)/linker.lock $(CXX.target) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= $(CXX.host) -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,bson.target.mk)))),) - include bson.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/vagrant/lab4/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/vagrant/.node-gyp/0.10.24/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/vagrant/.node-gyp/0.10.24" "-Dmodule_root_dir=/home/vagrant/lab4/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../.node-gyp/0.10.24/common.gypi $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d deleted file mode 100644 index 866c155bc..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/bson.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/bson.node := rm -rf "Release/bson.node" && cp -af "Release/obj.target/bson.node" "Release/bson.node" diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d deleted file mode 100644 index a7317de71..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/bson.node := flock ./Release/linker.lock g++ -shared -pthread -rdynamic -m32 -Wl,-soname=bson.node -o Release/obj.target/bson.node -Wl,--start-group Release/obj.target/bson/ext/bson.o -Wl,--end-group diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d deleted file mode 100644 index 2c2850626..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/.deps/Release/obj.target/bson/ext/bson.o.d +++ /dev/null @@ -1,28 +0,0 @@ -cmd_Release/obj.target/bson/ext/bson.o := g++ '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/vagrant/.node-gyp/0.10.24/src -I/home/vagrant/.node-gyp/0.10.24/deps/uv/include -I/home/vagrant/.node-gyp/0.10.24/deps/v8/include -Wall -Wextra -Wno-unused-parameter -pthread -m32 -O2 -fno-strict-aliasing -fno-tree-vrp -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/bson/ext/bson.o.d.raw -c -o Release/obj.target/bson/ext/bson.o ../ext/bson.cc -Release/obj.target/bson/ext/bson.o: ../ext/bson.cc \ - /home/vagrant/.node-gyp/0.10.24/deps/v8/include/v8.h \ - /home/vagrant/.node-gyp/0.10.24/deps/v8/include/v8stdint.h \ - /home/vagrant/.node-gyp/0.10.24/src/node.h \ - /home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv.h \ - /home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h \ - /home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h \ - /home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-linux.h \ - /home/vagrant/.node-gyp/0.10.24/src/node_object_wrap.h \ - /home/vagrant/.node-gyp/0.10.24/src/node.h \ - /home/vagrant/.node-gyp/0.10.24/src/node_version.h \ - /home/vagrant/.node-gyp/0.10.24/src/node_buffer.h ../ext/bson.h \ - /home/vagrant/.node-gyp/0.10.24/src/node_object_wrap.h -../ext/bson.cc: -/home/vagrant/.node-gyp/0.10.24/deps/v8/include/v8.h: -/home/vagrant/.node-gyp/0.10.24/deps/v8/include/v8stdint.h: -/home/vagrant/.node-gyp/0.10.24/src/node.h: -/home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv.h: -/home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-unix.h: -/home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/ngx-queue.h: -/home/vagrant/.node-gyp/0.10.24/deps/uv/include/uv-private/uv-linux.h: -/home/vagrant/.node-gyp/0.10.24/src/node_object_wrap.h: -/home/vagrant/.node-gyp/0.10.24/src/node.h: -/home/vagrant/.node-gyp/0.10.24/src/node_version.h: -/home/vagrant/.node-gyp/0.10.24/src/node_buffer.h: -../ext/bson.h: -/home/vagrant/.node-gyp/0.10.24/src/node_object_wrap.h: diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/bson.node b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/bson.node deleted file mode 100644 index ec10a654c..000000000 Binary files a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/bson.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/linker.lock b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/linker.lock deleted file mode 100644 index e69de29bb..000000000 diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node deleted file mode 100644 index ec10a654c..000000000 Binary files a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o deleted file mode 100644 index 90cbde352..000000000 Binary files a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/Release/obj.target/bson/ext/bson.o and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/binding.Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/binding.Makefile deleted file mode 100644 index 90bf8247b..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= build/./. -.PHONY: all -all: - $(MAKE) bson diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/bson.target.mk b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/bson.target.mk deleted file mode 100644 index 47d5b758e..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/bson.target.mk +++ /dev/null @@ -1,126 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := bson -DEFS_Debug := \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -pthread \ - -m32 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti - -INCS_Debug := \ - -I/home/vagrant/.node-gyp/0.10.24/src \ - -I/home/vagrant/.node-gyp/0.10.24/deps/uv/include \ - -I/home/vagrant/.node-gyp/0.10.24/deps/v8/include - -DEFS_Release := \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -pthread \ - -m32 \ - -O2 \ - -fno-strict-aliasing \ - -fno-tree-vrp \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti - -INCS_Release := \ - -I/home/vagrant/.node-gyp/0.10.24/src \ - -I/home/vagrant/.node-gyp/0.10.24/deps/uv/include \ - -I/home/vagrant/.node-gyp/0.10.24/deps/v8/include - -OBJS := \ - $(obj).target/$(TARGET)/ext/bson.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m32 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m32 - -LIBS := - -$(obj).target/bson.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/bson.node: LIBS := $(LIBS) -$(obj).target/bson.node: TOOLSET := $(TOOLSET) -$(obj).target/bson.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/bson.node -# Add target alias -.PHONY: bson -bson: $(builddir)/bson.node - -# Copy this to the executable output path. -$(builddir)/bson.node: TOOLSET := $(TOOLSET) -$(builddir)/bson.node: $(obj).target/bson.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/bson.node -# Short alias for building this executable. -.PHONY: bson.node -bson.node: $(obj).target/bson.node $(builddir)/bson.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/bson.node - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/config.gypi b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/config.gypi deleted file mode 100644 index 91ce77280..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build/config.gypi +++ /dev/null @@ -1,115 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 0, - "gcc_version": 46, - "host_arch": "ia32", - "node_install_npm": "true", - "node_prefix": "/usr/local", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "node_use_systemtap": "false", - "python": "/usr/bin/python", - "target_arch": "ia32", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "true", - "nodedir": "/home/vagrant/.node-gyp/0.10.24", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "sign_git_tag": "", - "always_auth": "", - "user_agent": "node/v0.10.24 linux ia32", - "bin_links": "true", - "key": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "user": "", - "force": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "cache_max": "null", - "userconfig": "/home/vagrant/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "tmp": "/home/vagrant/tmp", - "depth": "null", - "save_dev": "", - "usage": "", - "https_proxy": "", - "onload_script": "", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/bash", - "prefix": "/usr/local", - "registry": "https://registry.npmjs.org/", - "browser": "", - "cache_lock_wait": "10000", - "save_optional": "", - "searchopts": "", - "versions": "", - "cache": "/home/vagrant/.npm", - "ignore_scripts": "", - "searchsort": "name", - "version": "", - "local_address": "", - "viewer": "man", - "color": "true", - "fetch_retry_mintimeout": "10000", - "umask": "18", - "fetch_retry_maxtimeout": "60000", - "message": "%s", - "cert": "", - "global": "", - "link": "", - "save": "", - "unicode": "true", - "long": "", - "production": "", - "unsafe_perm": "true", - "node_version": "v0.10.24", - "tag": "latest", - "git_tag_version": "true", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "npat": "", - "proprietary_attribs": "true", - "strict_ssl": "true", - "username": "", - "dev": "", - "globalconfig": "/usr/local/etc/npmrc", - "init_module": "/home/vagrant/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/local/etc/npmignore", - "cache_lock_retries": "10", - "group": "1000", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "email": "", - "json": "" - } -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build_browser.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build_browser.js deleted file mode 100644 index bb8023844..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/build_browser.js +++ /dev/null @@ -1,7 +0,0 @@ -require('one'); - -one('./package.json') - .tie('bson', BSON) - // .exclude('buffer') - .tie('buffer', {}) - .save('./browser_build/bson.js') \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/Makefile deleted file mode 100644 index 435999ee9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/Makefile +++ /dev/null @@ -1,28 +0,0 @@ -NODE = node -name = all -JOBS = 1 - -all: - rm -rf build .lock-wscript bson.node - node-waf configure build - cp -R ./build/Release/bson.node . || true - -all_debug: - rm -rf build .lock-wscript bson.node - node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clang: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf configure build - cp -R ./build/Release/bson.node . || true - -clang_debug: - rm -rf build .lock-wscript bson.node - CXX=clang node-waf --debug configure build - cp -R ./build/Release/bson.node . || true - -clean: - rm -rf build .lock-wscript bson.node - -.PHONY: all \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/bson.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/bson.cc deleted file mode 100644 index 35c1709ce..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/bson.cc +++ /dev/null @@ -1,1045 +0,0 @@ -//=========================================================================== - -#include -#include -#include -#include -#include - -#ifdef __clang__ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wunused-parameter" -#endif - -#include - -// this and the above block must be around the v8.h header otherwise -// v8 is not happy -#ifdef __clang__ -#pragma clang diagnostic pop -#endif - -#include -#include -#include - -#include -#include -#include -#include - -#ifdef __sun - #include -#endif - -#include "bson.h" - -using namespace v8; -using namespace node; - -//=========================================================================== - -void DataStream::WriteObjectId(const Handle& object, const Handle& key) -{ - uint16_t buffer[12]; - object->Get(key)->ToString()->Write(buffer, 0, 12); - for(uint32_t i = 0; i < 12; ++i) - { - *p++ = (char) buffer[i]; - } -} - -void ThrowAllocatedStringException(size_t allocationSize, const char* format, ...) -{ - va_list args; - va_start(args, format); - char* string = (char*) malloc(allocationSize); - vsprintf(string, format, args); - va_end(args); - - throw string; -} - -void DataStream::CheckKey(const Local& keyName) -{ - size_t keyLength = keyName->Utf8Length(); - if(keyLength == 0) return; - - // Allocate space for the key, do not need to zero terminate as WriteUtf8 does it - char* keyStringBuffer = (char*) alloca(keyLength + 1); - // Write the key to the allocated buffer - keyName->WriteUtf8(keyStringBuffer); - // Check for the zero terminator - char* terminator = strchr(keyStringBuffer, 0x00); - - // If the location is not at the end of the string we've got an illegal 0x00 byte somewhere - if(terminator != &keyStringBuffer[keyLength]) { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain null bytes", keyStringBuffer); - } - - if(keyStringBuffer[0] == '$') - { - ThrowAllocatedStringException(64+keyLength, "key %s must not start with '$'", keyStringBuffer); - } - - if(strchr(keyStringBuffer, '.') != NULL) - { - ThrowAllocatedStringException(64+keyLength, "key %s must not contain '.'", keyStringBuffer); - } -} - -template void BSONSerializer::SerializeDocument(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - Local object = bson->GetSerializeObject(value); - - // Get the object property names - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - Local propertyNames = object->GetPropertyNames(); - #else - Local propertyNames = object->GetOwnPropertyNames(); - #endif - - // Length of the property - int propertyLength = propertyNames->Length(); - for(int i = 0; i < propertyLength; ++i) - { - const Local& propertyName = propertyNames->Get(i)->ToString(); - if(checkKeys) this->CheckKey(propertyName); - - const Local& propertyValue = object->Get(propertyName); - - if(serializeFunctions || !propertyValue->IsFunction()) - { - void* typeLocation = this->BeginWriteType(); - this->WriteString(propertyName); - SerializeValue(typeLocation, propertyValue); - } - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -template void BSONSerializer::SerializeArray(const Handle& value) -{ - void* documentSize = this->BeginWriteSize(); - - Local array = Local::Cast(value->ToObject()); - uint32_t arrayLength = array->Length(); - - for(uint32_t i = 0; i < arrayLength; ++i) - { - void* typeLocation = this->BeginWriteType(); - this->WriteUInt32String(i); - SerializeValue(typeLocation, array->Get(i)); - } - - this->WriteByte(0); - this->CommitSize(documentSize); -} - -// This is templated so that we can use this function to both count the number of bytes, and to serialize those bytes. -// The template approach eliminates almost all of the inspection of values unless they're required (eg. string lengths) -// and ensures that there is always consistency between bytes counted and bytes written by design. -template void BSONSerializer::SerializeValue(void* typeLocation, const Handle& value) -{ - if(value->IsNumber()) - { - double doubleValue = value->NumberValue(); - int intValue = (int) doubleValue; - if(intValue == doubleValue) - { - this->CommitType(typeLocation, BSON_TYPE_INT); - this->WriteInt32(intValue); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(doubleValue); - } - } - else if(value->IsString()) - { - this->CommitType(typeLocation, BSON_TYPE_STRING); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsBoolean()) - { - this->CommitType(typeLocation, BSON_TYPE_BOOLEAN); - this->WriteBool(value); - } - else if(value->IsArray()) - { - this->CommitType(typeLocation, BSON_TYPE_ARRAY); - SerializeArray(value); - } - else if(value->IsDate()) - { - this->CommitType(typeLocation, BSON_TYPE_DATE); - this->WriteInt64(value); - } - else if(value->IsRegExp()) - { - this->CommitType(typeLocation, BSON_TYPE_REGEXP); - const Handle& regExp = Handle::Cast(value); - - this->WriteString(regExp->GetSource()); - - int flags = regExp->GetFlags(); - if(flags & RegExp::kGlobal) this->WriteByte('s'); - if(flags & RegExp::kIgnoreCase) this->WriteByte('i'); - if(flags & RegExp::kMultiline) this->WriteByte('m'); - this->WriteByte(0); - } - else if(value->IsFunction()) - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(value->ToString()); - } - else if(value->IsObject()) - { - const Local& object = value->ToObject(); - if(object->Has(bson->_bsontypeString)) - { - const Local& constructorString = object->GetConstructorName(); - if(bson->longString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_LONG); - this->WriteInt32(object, bson->_longLowString); - this->WriteInt32(object, bson->_longHighString); - } - else if(bson->timestampString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_TIMESTAMP); - this->WriteInt32(object, bson->_longLowString); - this->WriteInt32(object, bson->_longHighString); - } - else if(bson->objectIDString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OID); - this->WriteObjectId(object, bson->_objectIDidString); - } - else if(bson->binaryString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - uint32_t length = object->Get(bson->_binaryPositionString)->Uint32Value(); - Local bufferObj = object->Get(bson->_binaryBufferString)->ToObject(); - - this->WriteInt32(length); - this->WriteByte(object, bson->_binarySubTypeString); // write subtype - // If type 0x02 write the array length aswell - if(object->Get(bson->_binarySubTypeString)->Int32Value() == 0x02) { - this->WriteInt32(length); - } - // Write the actual data - this->WriteData(Buffer::Data(bufferObj), length); - } - else if(bson->doubleString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_NUMBER); - this->WriteDouble(object, bson->_doubleValueString); - } - else if(bson->symbolString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_SYMBOL); - this->WriteLengthPrefixedString(object->Get(bson->_symbolValueString)->ToString()); - } - else if(bson->codeString->StrictEquals(constructorString)) - { - const Local& function = object->Get(bson->_codeCodeString)->ToString(); - const Local& scope = object->Get(bson->_codeScopeString)->ToObject(); - - // For Node < 0.6.X use the GetPropertyNames - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 6 - uint32_t propertyNameLength = scope->GetPropertyNames()->Length(); - #else - uint32_t propertyNameLength = scope->GetOwnPropertyNames()->Length(); - #endif - - if(propertyNameLength > 0) - { - this->CommitType(typeLocation, BSON_TYPE_CODE_W_SCOPE); - void* codeWidthScopeSize = this->BeginWriteSize(); - this->WriteLengthPrefixedString(function->ToString()); - SerializeDocument(scope); - this->CommitSize(codeWidthScopeSize); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_CODE); - this->WriteLengthPrefixedString(function->ToString()); - } - } - else if(bson->dbrefString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - - void* dbRefSize = this->BeginWriteSize(); - - void* refType = this->BeginWriteType(); - this->WriteData("$ref", 5); - SerializeValue(refType, object->Get(bson->_dbRefNamespaceString)); - - void* idType = this->BeginWriteType(); - this->WriteData("$id", 4); - SerializeValue(idType, object->Get(bson->_dbRefOidString)); - - const Local& refDbValue = object->Get(bson->_dbRefDbString); - if(!refDbValue->IsUndefined()) - { - void* dbType = this->BeginWriteType(); - this->WriteData("$db", 4); - SerializeValue(dbType, refDbValue); - } - - this->WriteByte(0); - this->CommitSize(dbRefSize); - } - else if(bson->minKeyString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MIN_KEY); - } - else if(bson->maxKeyString->StrictEquals(constructorString)) - { - this->CommitType(typeLocation, BSON_TYPE_MAX_KEY); - } - } - else if(Buffer::HasInstance(value)) - { - this->CommitType(typeLocation, BSON_TYPE_BINARY); - - #if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Buffer *buffer = ObjectWrap::Unwrap(value->ToObject()); - uint32_t length = object->length(); - #else - uint32_t length = Buffer::Length(value->ToObject()); - #endif - - this->WriteInt32(length); - this->WriteByte(0); - this->WriteData(Buffer::Data(value->ToObject()), length); - } - else - { - this->CommitType(typeLocation, BSON_TYPE_OBJECT); - SerializeDocument(value); - } - } - else if(value->IsNull() || value->IsUndefined()) - { - this->CommitType(typeLocation, BSON_TYPE_NULL); - } -} - -// Data points to start of element list, length is length of entire document including '\0' but excluding initial size -BSONDeserializer::BSONDeserializer(BSON* aBson, char* data, size_t length) -: bson(aBson), - pStart(data), - p(data), - pEnd(data + length - 1) -{ - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -BSONDeserializer::BSONDeserializer(BSONDeserializer& parentSerializer, size_t length) -: bson(parentSerializer.bson), - pStart(parentSerializer.p), - p(parentSerializer.p), - pEnd(parentSerializer.p + length - 1) -{ - parentSerializer.p += length; - if(pEnd > parentSerializer.pEnd) ThrowAllocatedStringException(64, "Child document exceeds parent's bounds"); - if(*pEnd != '\0') ThrowAllocatedStringException(64, "Missing end of document marker '\\0'"); -} - -Local BSONDeserializer::ReadCString() -{ - char* start = p; - while(*p++) { } - return String::New(start, (int32_t) (p-start-1) ); -} - -int32_t BSONDeserializer::ReadRegexOptions() -{ - int32_t options = 0; - for(;;) - { - switch(*p++) - { - case '\0': return options; - case 's': options |= RegExp::kGlobal; break; - case 'i': options |= RegExp::kIgnoreCase; break; - case 'm': options |= RegExp::kMultiline; break; - } - } -} - -uint32_t BSONDeserializer::ReadIntegerString() -{ - uint32_t value = 0; - while(*p) - { - if(*p < '0' || *p > '9') ThrowAllocatedStringException(64, "Invalid key for array"); - value = value * 10 + *p++ - '0'; - } - ++p; - return value; -} - -Local BSONDeserializer::ReadString() -{ - uint32_t length = ReadUInt32(); - char* start = p; - p += length; - return String::New(start, length-1); -} - -Local BSONDeserializer::ReadObjectId() -{ - uint16_t objectId[12]; - for(size_t i = 0; i < 12; ++i) - { - objectId[i] = *reinterpret_cast(p++); - } - return String::New(objectId, 12); -} - -Handle BSONDeserializer::DeserializeDocument(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeDocumentInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeDocumentInternal(bool promoteLongs) -{ - Local returnObject = Object::New(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - const Local& name = ReadCString(); - const Handle& value = DeserializeValue(type, promoteLongs); - returnObject->ForceSet(name, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Document: Serialize consumed unexpected number of bytes"); - - // From JavaScript: - // if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - if(returnObject->Has(bson->_dbRefIdRefString)) - { - Local argv[] = { returnObject->Get(bson->_dbRefRefString), returnObject->Get(bson->_dbRefIdRefString), returnObject->Get(bson->_dbRefDbRefString) }; - return bson->dbrefConstructor->NewInstance(3, argv); - } - else - { - return returnObject; - } -} - -Handle BSONDeserializer::DeserializeArray(bool promoteLongs) -{ - uint32_t length = ReadUInt32(); - if(length < 5) ThrowAllocatedStringException(64, "Bad BSON: Array Document is less than 5 bytes"); - - BSONDeserializer documentDeserializer(*this, length-4); - return documentDeserializer.DeserializeArrayInternal(promoteLongs); -} - -Handle BSONDeserializer::DeserializeArrayInternal(bool promoteLongs) -{ - Local returnArray = Array::New(); - - while(HasMoreData()) - { - BsonType type = (BsonType) ReadByte(); - uint32_t index = ReadIntegerString(); - const Handle& value = DeserializeValue(type, promoteLongs); - returnArray->Set(index, value); - } - if(p != pEnd) ThrowAllocatedStringException(64, "Bad BSON Array: Serialize consumed unexpected number of bytes"); - - return returnArray; -} - -Handle BSONDeserializer::DeserializeValue(BsonType type, bool promoteLongs) -{ - switch(type) - { - case BSON_TYPE_STRING: - return ReadString(); - - case BSON_TYPE_INT: - return Integer::New(ReadInt32()); - - case BSON_TYPE_NUMBER: - return Number::New(ReadDouble()); - - case BSON_TYPE_NULL: - return Null(); - - case BSON_TYPE_UNDEFINED: - return Undefined(); - - case BSON_TYPE_TIMESTAMP: - { - int32_t lowBits = ReadInt32(); - int32_t highBits = ReadInt32(); - Local argv[] = { Int32::New(lowBits), Int32::New(highBits) }; - return bson->timestampConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_BOOLEAN: - return (ReadByte() != 0) ? True() : False(); - - case BSON_TYPE_REGEXP: - { - const Local& regex = ReadCString(); - int32_t options = ReadRegexOptions(); - return RegExp::New(regex, (RegExp::Flags) options); - } - - case BSON_TYPE_CODE: - { - const Local& code = ReadString(); - const Local& scope = Object::New(); - Local argv[] = { code, scope }; - return bson->codeConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_CODE_W_SCOPE: - { - ReadUInt32(); - const Local& code = ReadString(); - const Handle& scope = DeserializeDocument(promoteLongs); - Local argv[] = { code, scope->ToObject() }; - return bson->codeConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_OID: - { - Local argv[] = { ReadObjectId() }; - return bson->objectIDConstructor->NewInstance(1, argv); - } - - case BSON_TYPE_BINARY: - { - uint32_t length = ReadUInt32(); - uint32_t subType = ReadByte(); - if(subType == 0x02) { - length = ReadInt32(); - } - - Buffer* buffer = Buffer::New(p, length); - p += length; - - Handle argv[] = { buffer->handle_, Uint32::New(subType) }; - return bson->binaryConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_LONG: - { - // Read 32 bit integers - int32_t lowBits = (int32_t) ReadInt32(); - int32_t highBits = (int32_t) ReadInt32(); - - // Promote long is enabled - if(promoteLongs) { - // If value is < 2^53 and >-2^53 - if((highBits < 0x200000 || (highBits == 0x200000 && lowBits == 0)) && highBits >= -0x200000) { - // Adjust the pointer and read as 64 bit value - p -= 8; - // Read the 64 bit value - int64_t finalValue = (int64_t) ReadInt64(); - return Number::New(finalValue); - } - } - - // Decode the Long value - Local argv[] = { Int32::New(lowBits), Int32::New(highBits) }; - return bson->longConstructor->NewInstance(2, argv); - } - - case BSON_TYPE_DATE: - return Date::New((double) ReadInt64()); - - case BSON_TYPE_ARRAY: - return DeserializeArray(promoteLongs); - - case BSON_TYPE_OBJECT: - return DeserializeDocument(promoteLongs); - - case BSON_TYPE_SYMBOL: - { - const Local& string = ReadString(); - Local argv[] = { string }; - return bson->symbolConstructor->NewInstance(1, argv); - } - - case BSON_TYPE_MIN_KEY: - return bson->minKeyConstructor->NewInstance(); - - case BSON_TYPE_MAX_KEY: - return bson->maxKeyConstructor->NewInstance(); - - default: - ThrowAllocatedStringException(64, "Unhandled BSON Type: %d", type); - } - - return v8::Null(); -} - - -static Handle VException(const char *msg) -{ - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Persistent BSON::constructor_template; - -BSON::BSON() : ObjectWrap() -{ - // Setup pre-allocated comparision objects - _bsontypeString = Persistent::New(String::New("_bsontype")); - _longLowString = Persistent::New(String::New("low_")); - _longHighString = Persistent::New(String::New("high_")); - _objectIDidString = Persistent::New(String::New("id")); - _binaryPositionString = Persistent::New(String::New("position")); - _binarySubTypeString = Persistent::New(String::New("sub_type")); - _binaryBufferString = Persistent::New(String::New("buffer")); - _doubleValueString = Persistent::New(String::New("value")); - _symbolValueString = Persistent::New(String::New("value")); - _dbRefRefString = Persistent::New(String::New("$ref")); - _dbRefIdRefString = Persistent::New(String::New("$id")); - _dbRefDbRefString = Persistent::New(String::New("$db")); - _dbRefNamespaceString = Persistent::New(String::New("namespace")); - _dbRefDbString = Persistent::New(String::New("db")); - _dbRefOidString = Persistent::New(String::New("oid")); - _codeCodeString = Persistent::New(String::New("code")); - _codeScopeString = Persistent::New(String::New("scope")); - _toBSONString = Persistent::New(String::New("toBSON")); - - longString = Persistent::New(String::New("Long")); - objectIDString = Persistent::New(String::New("ObjectID")); - binaryString = Persistent::New(String::New("Binary")); - codeString = Persistent::New(String::New("Code")); - dbrefString = Persistent::New(String::New("DBRef")); - symbolString = Persistent::New(String::New("Symbol")); - doubleString = Persistent::New(String::New("Double")); - timestampString = Persistent::New(String::New("Timestamp")); - minKeyString = Persistent::New(String::New("MinKey")); - maxKeyString = Persistent::New(String::New("MaxKey")); -} - -void BSON::Initialize(v8::Handle target) -{ - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("BSON")); - - // Instance methods - NODE_SET_PROTOTYPE_METHOD(constructor_template, "calculateObjectSize", CalculateObjectSize); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "serialize", BSONSerialize); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "serializeWithBufferAndIndex", SerializeWithBufferAndIndex); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "deserialize", BSONDeserialize); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "deserializeStream", BSONDeserializeStream); - - target->ForceSet(String::NewSymbol("BSON"), constructor_template->GetFunction()); -} - -// Create a new instance of BSON and passing it the existing context -Handle BSON::New(const Arguments &args) -{ - HandleScope scope; - - // Check that we have an array - if(args.Length() == 1 && args[0]->IsArray()) - { - // Cast the array to a local reference - Local array = Local::Cast(args[0]); - - if(array->Length() > 0) - { - // Create a bson object instance and return it - BSON *bson = new BSON(); - - uint32_t foundClassesMask = 0; - - // Iterate over all entries to save the instantiate funtions - for(uint32_t i = 0; i < array->Length(); i++) { - // Let's get a reference to the function - Local func = Local::Cast(array->Get(i)); - Local functionName = func->GetName()->ToString(); - - // Save the functions making them persistant handles (they don't get collected) - if(functionName->StrictEquals(bson->longString)) { - bson->longConstructor = Persistent::New(func); - foundClassesMask |= 1; - } else if(functionName->StrictEquals(bson->objectIDString)) { - bson->objectIDConstructor = Persistent::New(func); - foundClassesMask |= 2; - } else if(functionName->StrictEquals(bson->binaryString)) { - bson->binaryConstructor = Persistent::New(func); - foundClassesMask |= 4; - } else if(functionName->StrictEquals(bson->codeString)) { - bson->codeConstructor = Persistent::New(func); - foundClassesMask |= 8; - } else if(functionName->StrictEquals(bson->dbrefString)) { - bson->dbrefConstructor = Persistent::New(func); - foundClassesMask |= 0x10; - } else if(functionName->StrictEquals(bson->symbolString)) { - bson->symbolConstructor = Persistent::New(func); - foundClassesMask |= 0x20; - } else if(functionName->StrictEquals(bson->doubleString)) { - bson->doubleConstructor = Persistent::New(func); - foundClassesMask |= 0x40; - } else if(functionName->StrictEquals(bson->timestampString)) { - bson->timestampConstructor = Persistent::New(func); - foundClassesMask |= 0x80; - } else if(functionName->StrictEquals(bson->minKeyString)) { - bson->minKeyConstructor = Persistent::New(func); - foundClassesMask |= 0x100; - } else if(functionName->StrictEquals(bson->maxKeyString)) { - bson->maxKeyConstructor = Persistent::New(func); - foundClassesMask |= 0x200; - } - } - - // Check if we have the right number of constructors otherwise throw an error - if(foundClassesMask != 0x3ff) { - delete bson; - return VException("Missing function constructor for either [Long/ObjectID/Binary/Code/DbRef/Symbol/Double/Timestamp/MinKey/MaxKey]"); - } else { - bson->Wrap(args.This()); - return args.This(); - } - } - else - { - return VException("No types passed in"); - } - } - else - { - return VException("Argument passed in must be an array of types"); - } -} - -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ -//------------------------------------------------------------------------------------------------ - -Handle BSON::BSONDeserialize(const Arguments &args) -{ - HandleScope scope; - - // Fail if the first argument is not a string or a buffer - if(args.Length() > 1 && !args[0]->IsString() && !Buffer::HasInstance(args[0])) - return VException("First Argument must be a Buffer or String."); - - // Promote longs - bool promoteLongs = true; - - // If we have an options object - if(args.Length() == 2 && args[1]->IsObject()) { - Local options = args[1]->ToObject(); - - if(options->Has(String::New("promoteLongs"))) { - promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Define pointer to data - Local obj = args[0]->ToObject(); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // If we passed in a buffer, let's unpack it, otherwise let's unpack the string - if(Buffer::HasInstance(obj)) - { -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Buffer *buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Validate that we have at least 5 bytes - if(length < 5) return VException("corrupt bson message < 5 bytes long"); - - try - { - BSONDeserializer deserializer(bson, data, length); - // deserializer.promoteLongs = promoteLongs; - return deserializer.DeserializeDocument(promoteLongs); - } - catch(char* exception) - { - Handle error = VException(exception); - free(exception); - return error; - } - - } - else - { - // The length of the data for this encoding - ssize_t len = DecodeBytes(args[0], BINARY); - - // Validate that we have at least 5 bytes - if(len < 5) return VException("corrupt bson message < 5 bytes long"); - - // Let's define the buffer size - char* data = (char *)malloc(len); - DecodeWrite(data, len, args[0], BINARY); - - try - { - BSONDeserializer deserializer(bson, data, len); - // deserializer.promoteLongs = promoteLongs; - Handle result = deserializer.DeserializeDocument(promoteLongs); - free(data); - return result; - - } - catch(char* exception) - { - Handle error = VException(exception); - free(exception); - free(data); - return error; - } - } -} - -Local BSON::GetSerializeObject(const Handle& argValue) -{ - Local object = argValue->ToObject(); - if(object->Has(_toBSONString)) - { - const Local& toBSON = object->Get(_toBSONString); - if(!toBSON->IsFunction()) ThrowAllocatedStringException(64, "toBSON is not a function"); - - Local result = Local::Cast(toBSON)->Call(object, 0, NULL); - if(!result->IsObject()) ThrowAllocatedStringException(64, "toBSON function did not return an object"); - return result->ToObject(); - } - else - { - return object; - } -} - -Handle BSON::BSONSerialize(const Arguments &args) -{ - HandleScope scope; - - if(args.Length() == 1 && !args[0]->IsObject()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 3 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !args[2]->IsBoolean() && !args[3]->IsBoolean()) return VException("One, two or tree arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - if(args.Length() > 4) return VException("One, two, tree or four arguments required - [object] or [object, boolean] or [object, boolean, boolean] or [object, boolean, boolean, boolean]"); - - // Check if we have an array as the object - if(args[0]->IsArray()) return VException("Only javascript objects supported"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Calculate the total size of the document in binary form to ensure we only allocate memory once - // With serialize function - bool serializeFunctions = (args.Length() >= 4) && args[3]->BooleanValue(); - - char *serialized_object = NULL; - size_t object_size; - try - { - Local object = bson->GetSerializeObject(args[0]); - - BSONSerializer counter(bson, false, serializeFunctions); - counter.SerializeDocument(object); - object_size = counter.GetSerializeSize(); - - // Allocate the memory needed for the serialization - serialized_object = (char *)malloc(object_size); - - // Check if we have a boolean value - bool checkKeys = args.Length() >= 3 && args[1]->IsBoolean() && args[1]->BooleanValue(); - BSONSerializer data(bson, checkKeys, serializeFunctions, serialized_object); - data.SerializeDocument(object); - } - catch(char *err_msg) - { - free(serialized_object); - Handle error = VException(err_msg); - free(err_msg); - return error; - } - - // If we have 3 arguments - if(args.Length() == 3 || args.Length() == 4) - { - Buffer *buffer = Buffer::New(serialized_object, object_size); - free(serialized_object); - return scope.Close(buffer->handle_); - } - else - { - Local bin_value = Encode(serialized_object, object_size, BINARY)->ToString(); - free(serialized_object); - return bin_value; - } -} - -Handle BSON::CalculateObjectSize(const Arguments &args) -{ - HandleScope scope; - // Ensure we have a valid object - if(args.Length() == 1 && !args[0]->IsObject()) return VException("One argument required - [object]"); - if(args.Length() == 2 && !args[0]->IsObject() && !args[1]->IsBoolean()) return VException("Two arguments required - [object, boolean]"); - if(args.Length() > 3) return VException("One or two arguments required - [object] or [object, boolean]"); - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - bool serializeFunctions = (args.Length() >= 2) && args[1]->BooleanValue(); - BSONSerializer countSerializer(bson, false, serializeFunctions); - countSerializer.SerializeDocument(args[0]); - - // Return the object size - return scope.Close(Uint32::New((uint32_t) countSerializer.GetSerializeSize())); -} - -Handle BSON::SerializeWithBufferAndIndex(const Arguments &args) -{ - HandleScope scope; - - //BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, ->, buffer, index) { - // Ensure we have the correct values - if(args.Length() > 5) return VException("Four or five parameters required [object, boolean, Buffer, int] or [object, boolean, Buffer, int, boolean]"); - if(args.Length() == 4 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32()) return VException("Four parameters required [object, boolean, Buffer, int]"); - if(args.Length() == 5 && !args[0]->IsObject() && !args[1]->IsBoolean() && !Buffer::HasInstance(args[2]) && !args[3]->IsUint32() && !args[4]->IsBoolean()) return VException("Four parameters required [object, boolean, Buffer, int, boolean]"); - - uint32_t index; - size_t object_size; - - try - { - BSON *bson = ObjectWrap::Unwrap(args.This()); - - Local obj = args[2]->ToObject(); - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); - - index = args[3]->Uint32Value(); - bool checkKeys = args.Length() >= 4 && args[1]->IsBoolean() && args[1]->BooleanValue(); - bool serializeFunctions = (args.Length() == 5) && args[4]->BooleanValue(); - - BSONSerializer dataSerializer(bson, checkKeys, serializeFunctions, data+index); - dataSerializer.SerializeDocument(bson->GetSerializeObject(args[0])); - object_size = dataSerializer.GetSerializeSize(); - - if(object_size + index > length) return VException("Serious error - overflowed buffer!!"); - } - catch(char *exception) - { - Handle error = VException(exception); - free(exception); - return error; - } - - return scope.Close(Uint32::New((uint32_t) (index + object_size - 1))); -} - -Handle BSON::BSONDeserializeStream(const Arguments &args) -{ - HandleScope scope; - - // At least 3 arguments required - if(args.Length() < 5) return VException("Arguments required (Buffer(data), Number(index in data), Number(number of documents to deserialize), Array(results), Number(index in the array), Object(optional))"); - - // If the number of argumets equals 3 - if(args.Length() >= 5) - { - if(!Buffer::HasInstance(args[0])) return VException("First argument must be Buffer instance"); - if(!args[1]->IsUint32()) return VException("Second argument must be a positive index number"); - if(!args[2]->IsUint32()) return VException("Third argument must be a positive number of documents to deserialize"); - if(!args[3]->IsArray()) return VException("Fourth argument must be an array the size of documents to deserialize"); - if(!args[4]->IsUint32()) return VException("Sixth argument must be a positive index number"); - } - - // If we have 4 arguments - if(args.Length() == 6 && !args[5]->IsObject()) return VException("Fifth argument must be an object with options"); - - // Define pointer to data - Local obj = args[0]->ToObject(); - uint32_t numberOfDocuments = args[2]->Uint32Value(); - uint32_t index = args[1]->Uint32Value(); - uint32_t resultIndex = args[4]->Uint32Value(); - bool promoteLongs = true; - - // Check for the value promoteLongs in the options object - if(args.Length() == 6) { - Local options = args[5]->ToObject(); - - // Check if we have the promoteLong variable - if(options->Has(String::New("promoteLongs"))) { - promoteLongs = options->Get(String::New("promoteLongs"))->ToBoolean()->Value(); - } - } - - // Unpack the BSON parser instance - BSON *bson = ObjectWrap::Unwrap(args.This()); - - // Unpack the buffer variable -#if NODE_MAJOR_VERSION == 0 && NODE_MINOR_VERSION < 3 - Buffer *buffer = ObjectWrap::Unwrap(obj); - char* data = buffer->data(); - size_t length = buffer->length(); -#else - char* data = Buffer::Data(obj); - size_t length = Buffer::Length(obj); -#endif - - // Fetch the documents - Local documents = args[3]->ToObject(); - - BSONDeserializer deserializer(bson, data+index, length-index); - for(uint32_t i = 0; i < numberOfDocuments; i++) - { - try - { - documents->Set(i + resultIndex, deserializer.DeserializeDocument(promoteLongs)); - } - catch (char* exception) - { - Handle error = VException(exception); - free(exception); - return error; - } - } - - // Return new index of parsing - return scope.Close(Uint32::New((uint32_t) (index + deserializer.GetSerializeSize()))); -} - -// Exporting function -extern "C" void init(Handle target) -{ - HandleScope scope; - BSON::Initialize(target); -} - -NODE_MODULE(bson, BSON::Initialize); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/bson.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/bson.h deleted file mode 100644 index 3638f8269..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/bson.h +++ /dev/null @@ -1,277 +0,0 @@ -//=========================================================================== - -#ifndef BSON_H_ -#define BSON_H_ - -//=========================================================================== - -#ifdef __arm__ -#define USE_MISALIGNED_MEMORY_ACCESS 0 -#else -#define USE_MISALIGNED_MEMORY_ACCESS 1 -#endif - -#include -#include -#include - -using namespace v8; -using namespace node; - -//=========================================================================== - -enum BsonType -{ - BSON_TYPE_NUMBER = 1, - BSON_TYPE_STRING = 2, - BSON_TYPE_OBJECT = 3, - BSON_TYPE_ARRAY = 4, - BSON_TYPE_BINARY = 5, - BSON_TYPE_UNDEFINED = 6, - BSON_TYPE_OID = 7, - BSON_TYPE_BOOLEAN = 8, - BSON_TYPE_DATE = 9, - BSON_TYPE_NULL = 10, - BSON_TYPE_REGEXP = 11, - BSON_TYPE_CODE = 13, - BSON_TYPE_SYMBOL = 14, - BSON_TYPE_CODE_W_SCOPE = 15, - BSON_TYPE_INT = 16, - BSON_TYPE_TIMESTAMP = 17, - BSON_TYPE_LONG = 18, - BSON_TYPE_MAX_KEY = 0x7f, - BSON_TYPE_MIN_KEY = 0xff -}; - -//=========================================================================== - -template class BSONSerializer; - -class BSON : public ObjectWrap { -public: - BSON(); - ~BSON() {} - - static void Initialize(Handle target); - static Handle BSONDeserializeStream(const Arguments &args); - - // JS based objects - static Handle BSONSerialize(const Arguments &args); - static Handle BSONDeserialize(const Arguments &args); - - // Calculate size of function - static Handle CalculateObjectSize(const Arguments &args); - static Handle SerializeWithBufferAndIndex(const Arguments &args); - - // Constructor used for creating new BSON objects from C++ - static Persistent constructor_template; - -private: - static Handle New(const Arguments &args); - static Handle deserialize(BSON *bson, char *data, uint32_t dataLength, uint32_t startIndex, bool is_array_item); - - // BSON type instantiate functions - Persistent longConstructor; - Persistent objectIDConstructor; - Persistent binaryConstructor; - Persistent codeConstructor; - Persistent dbrefConstructor; - Persistent symbolConstructor; - Persistent doubleConstructor; - Persistent timestampConstructor; - Persistent minKeyConstructor; - Persistent maxKeyConstructor; - - // Equality Objects - Persistent longString; - Persistent objectIDString; - Persistent binaryString; - Persistent codeString; - Persistent dbrefString; - Persistent symbolString; - Persistent doubleString; - Persistent timestampString; - Persistent minKeyString; - Persistent maxKeyString; - - // Equality speed up comparison objects - Persistent _bsontypeString; - Persistent _longLowString; - Persistent _longHighString; - Persistent _objectIDidString; - Persistent _binaryPositionString; - Persistent _binarySubTypeString; - Persistent _binaryBufferString; - Persistent _doubleValueString; - Persistent _symbolValueString; - - Persistent _dbRefRefString; - Persistent _dbRefIdRefString; - Persistent _dbRefDbRefString; - Persistent _dbRefNamespaceString; - Persistent _dbRefDbString; - Persistent _dbRefOidString; - - Persistent _codeCodeString; - Persistent _codeScopeString; - Persistent _toBSONString; - - Local GetSerializeObject(const Handle& object); - - template friend class BSONSerializer; - friend class BSONDeserializer; -}; - -//=========================================================================== - -class CountStream -{ -public: - CountStream() : count(0) { } - - void WriteByte(int value) { ++count; } - void WriteByte(const Handle&, const Handle&) { ++count; } - void WriteBool(const Handle& value) { ++count; } - void WriteInt32(int32_t value) { count += 4; } - void WriteInt32(const Handle& value) { count += 4; } - void WriteInt32(const Handle& object, const Handle& key) { count += 4; } - void WriteInt64(int64_t value) { count += 8; } - void WriteInt64(const Handle& value) { count += 8; } - void WriteDouble(double value) { count += 8; } - void WriteDouble(const Handle& value) { count += 8; } - void WriteDouble(const Handle&, const Handle&) { count += 8; } - void WriteUInt32String(uint32_t name) { char buffer[32]; count += sprintf(buffer, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { count += value->Utf8Length()+5; } - void WriteObjectId(const Handle& object, const Handle& key) { count += 12; } - void WriteString(const Local& value) { count += value->Utf8Length() + 1; } // This returns the number of bytes exclusive of the NULL terminator - void WriteData(const char* data, size_t length) { count += length; } - - void* BeginWriteType() { ++count; return NULL; } - void CommitType(void*, BsonType) { } - void* BeginWriteSize() { count += 4; return NULL; } - void CommitSize(void*) { } - - size_t GetSerializeSize() const { return count; } - - // Do nothing. CheckKey is implemented for DataStream - void CheckKey(const Local&) { } - -private: - size_t count; -}; - -class DataStream -{ -public: - DataStream(char* aDestinationBuffer) : destinationBuffer(aDestinationBuffer), p(aDestinationBuffer) { } - - void WriteByte(int value) { *p++ = value; } - void WriteByte(const Handle& object, const Handle& key) { *p++ = object->Get(key)->Int32Value(); } -#if USE_MISALIGNED_MEMORY_ACCESS - void WriteInt32(int32_t value) { *reinterpret_cast(p) = value; p += 4; } - void WriteInt64(int64_t value) { *reinterpret_cast(p) = value; p += 8; } - void WriteDouble(double value) { *reinterpret_cast(p) = value; p += 8; } -#else - void WriteInt32(int32_t value) { memcpy(p, &value, 4); p += 4; } - void WriteInt64(int64_t value) { memcpy(p, &value, 8); p += 8; } - void WriteDouble(double value) { memcpy(p, &value, 8); p += 8; } -#endif - void WriteBool(const Handle& value) { WriteByte(value->BooleanValue() ? 1 : 0); } - void WriteInt32(const Handle& value) { WriteInt32(value->Int32Value()); } - void WriteInt32(const Handle& object, const Handle& key) { WriteInt32(object->Get(key)); } - void WriteInt64(const Handle& value) { WriteInt64(value->IntegerValue()); } - void WriteDouble(const Handle& value) { WriteDouble(value->NumberValue()); } - void WriteDouble(const Handle& object, const Handle& key) { WriteDouble(object->Get(key)); } - void WriteUInt32String(uint32_t name) { p += sprintf(p, "%u", name) + 1; } - void WriteLengthPrefixedString(const Local& value) { WriteInt32(value->Utf8Length()+1); WriteString(value); } - void WriteObjectId(const Handle& object, const Handle& key); - void WriteString(const Local& value) { p += value->WriteUtf8(p); } // This returns the number of bytes inclusive of the NULL terminator. - void WriteData(const char* data, size_t length) { memcpy(p, data, length); p += length; } - - void* BeginWriteType() { void* returnValue = p; p++; return returnValue; } - void CommitType(void* beginPoint, BsonType value) { *reinterpret_cast(beginPoint) = value; } - void* BeginWriteSize() { void* returnValue = p; p += 4; return returnValue; } - -#if USE_MISALIGNED_MEMORY_ACCESS - void CommitSize(void* beginPoint) { *reinterpret_cast(beginPoint) = (int32_t) (p - (char*) beginPoint); } -#else - void CommitSize(void* beginPoint) { int32_t value = (int32_t) (p - (char*) beginPoint); memcpy(beginPoint, &value, 4); } -#endif - - size_t GetSerializeSize() const { return p - destinationBuffer; } - - void CheckKey(const Local& keyName); - -protected: - char *const destinationBuffer; // base, never changes - char* p; // cursor into buffer -}; - -template class BSONSerializer : public T -{ -private: - typedef T Inherited; - -public: - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions) : Inherited(), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - BSONSerializer(BSON* aBson, bool aCheckKeys, bool aSerializeFunctions, char* parentParam) : Inherited(parentParam), checkKeys(aCheckKeys), serializeFunctions(aSerializeFunctions), bson(aBson) { } - - void SerializeDocument(const Handle& value); - void SerializeArray(const Handle& value); - void SerializeValue(void* typeLocation, const Handle& value); - -private: - bool checkKeys; - bool serializeFunctions; - BSON* bson; -}; - -//=========================================================================== - -class BSONDeserializer -{ -public: - BSONDeserializer(BSON* aBson, char* data, size_t length); - BSONDeserializer(BSONDeserializer& parentSerializer, size_t length); - - Handle DeserializeDocument(bool promoteLongs); - - bool HasMoreData() const { return p < pEnd; } - Local ReadCString(); - uint32_t ReadIntegerString(); - int32_t ReadRegexOptions(); - Local ReadString(); - Local ReadObjectId(); - - unsigned char ReadByte() { return *reinterpret_cast(p++); } -#if USE_MISALIGNED_MEMORY_ACCESS - int32_t ReadInt32() { int32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue = *reinterpret_cast(p); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue = *reinterpret_cast(p); p += 8; return returnValue; } - double ReadDouble() { double returnValue = *reinterpret_cast(p); p += 8; return returnValue; } -#else - int32_t ReadInt32() { int32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - uint32_t ReadUInt32() { uint32_t returnValue; memcpy(&returnValue, p, 4); p += 4; return returnValue; } - int64_t ReadInt64() { int64_t returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } - double ReadDouble() { double returnValue; memcpy(&returnValue, p, 8); p += 8; return returnValue; } -#endif - - size_t GetSerializeSize() const { return p - pStart; } - -private: - Handle DeserializeArray(bool promoteLongs); - Handle DeserializeValue(BsonType type, bool promoteLongs); - Handle DeserializeDocumentInternal(bool promoteLongs); - Handle DeserializeArrayInternal(bool promoteLongs); - - BSON* bson; - char* const pStart; - char* p; - char* const pEnd; -}; - -//=========================================================================== - -#endif // BSON_H_ - -//=========================================================================== diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/index.js deleted file mode 100644 index 85e243cc2..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/index.js +++ /dev/null @@ -1,30 +0,0 @@ -var bson = null; - -// Load the precompiled win32 binary -if(process.platform == "win32" && process.arch == "x64") { - bson = require('./win32/x64/bson'); -} else if(process.platform == "win32" && process.arch == "ia32") { - bson = require('./win32/ia32/bson'); -} else { - bson = require('../build/Release/bson'); -} - -exports.BSON = bson.BSON; -exports.Long = require('../lib/bson/long').Long; -exports.ObjectID = require('../lib/bson/objectid').ObjectID; -exports.DBRef = require('../lib/bson/db_ref').DBRef; -exports.Code = require('../lib/bson/code').Code; -exports.Timestamp = require('../lib/bson/timestamp').Timestamp; -exports.Binary = require('../lib/bson/binary').Binary; -exports.Double = require('../lib/bson/double').Double; -exports.MaxKey = require('../lib/bson/max_key').MaxKey; -exports.MinKey = require('../lib/bson/min_key').MinKey; -exports.Symbol = require('../lib/bson/symbol').Symbol; - -// Just add constants tot he Native BSON parser -exports.BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -exports.BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -exports.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -exports.BSON.BSON_BINARY_SUBTYPE_UUID = 3; -exports.BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -exports.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node deleted file mode 100644 index 7f54835e7..000000000 Binary files a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/win32/ia32/bson.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node deleted file mode 100644 index f01f8be35..000000000 Binary files a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/win32/x64/bson.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/wscript b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/wscript deleted file mode 100644 index 40f5317f1..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/ext/wscript +++ /dev/null @@ -1,39 +0,0 @@ -import Options -from os import unlink, symlink, popen -from os.path import exists - -srcdir = "." -blddir = "build" -VERSION = "0.1.0" - -def set_options(opt): - opt.tool_options("compiler_cxx") - opt.add_option( '--debug' - , action='store_true' - , default=False - , help='Build debug variant [Default: False]' - , dest='debug' - ) - -def configure(conf): - conf.check_tool("compiler_cxx") - conf.check_tool("node_addon") - conf.env.append_value('CXXFLAGS', ['-O3', '-funroll-loops']) - - # conf.env.append_value('CXXFLAGS', ['-DDEBUG', '-g', '-O0', '-Wall', '-Wextra']) - # conf.check(lib='node', libpath=['/usr/lib', '/usr/local/lib'], uselib_store='NODE') - -def build(bld): - obj = bld.new_task_gen("cxx", "shlib", "node_addon") - obj.target = "bson" - obj.source = ["bson.cc"] - # obj.uselib = "NODE" - -def shutdown(): - # HACK to get compress.node out of build directory. - # better way to do this? - if Options.commands['clean']: - if exists('bson.node'): unlink('bson.node') - else: - if exists('build/default/bson.node') and not exists('bson.node'): - symlink('build/default/bson.node', 'bson.node') diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/binary.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index 82d4d04c1..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,339 +0,0 @@ -/** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js deleted file mode 100644 index d2fc811f4..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/binary_parser.js +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/bson.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 3004d8486..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,1539 +0,0 @@ -var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/code.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/code.js deleted file mode 100644 index 69b56a3ff..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,25 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index 56b651029..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/double.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/double.js deleted file mode 100644 index ae5146378..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 6fca3924f..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/index.js deleted file mode 100644 index 950fcad34..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/index.js +++ /dev/null @@ -1,74 +0,0 @@ -try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/long.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/long.js deleted file mode 100644 index f8f37a6b8..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,854 +0,0 @@ -// 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index 0825408d0..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 230c2e64a..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 183bbc3c9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId aswell as ObjectID -var ObjectId = ObjectID; - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = '' - , number - , value; - - for (var index = 0, len = this.id.length; index < len; index++) { - value = BinaryParser.toByte(this.id[index]); - number = value <= 15 - ? '0' + value.toString(16) - : value.toString(16); - hexString = hexString + number; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = 0; - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index 8e2838d17..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index c650d1536..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,853 +0,0 @@ -// 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/package.json deleted file mode 100644 index bd3a8b26c..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "version": "0.2.2", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/mongodb/js-bson.git" - }, - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "devDependencies": { - "nodeunit": "0.7.3", - "gleak": "0.2.3", - "one": "2.X.X" - }, - "config": { - "native": false - }, - "main": "./lib/bson/index", - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test/node && TEST_NATIVE=TRUE nodeunit ./test/node" - }, - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "readme": "Javascript + C++ BSON parser\n============================\n\nThis BSON parser is primarily meant for usage with the `mongodb` node.js driver. However thanks to such wonderful tools at `onejs` we are able to package up a BSON parser that will work in the browser aswell. The current build is located in the `browser_build/bson.js` file.\n\nA simple example on how to use it\n\n \n \n \n \n \n \n\n It's got two simple methods to use in your application.\n\n * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions)\n * @param {Object} object the Javascript object to serialize.\n * @param {Boolean} checkKeys the serializer will check if keys are valid.\n * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**.\n * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**\n * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports\n \n * BSON.deserialize(buffer, options, isArray)\n * Options\n * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized.\n * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse.\n * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function.\n * @param {TypedArray/Array} a TypedArray/Array containing the BSON data\n * @param {Object} [options] additional options used for the deserialization.\n * @param {Boolean} [isArray] ignore used for recursive parsing.\n * @return {Object} returns the deserialized Javascript Object.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/mongodb/js-bson", - "_id": "bson@0.2.2", - "dist": { - "shasum": "f7b4239566d10de61b7debd2b53c7e3ad67036ef" - }, - "_from": "bson@0.2.2", - "_resolved": "https://registry.npmjs.org/bson/-/bson-0.2.2.tgz" -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/gleak.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/gleak.js deleted file mode 100644 index c707cfcb5..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/gleak.js +++ /dev/null @@ -1,21 +0,0 @@ - -var gleak = require('gleak')(); -gleak.ignore('AssertionError'); -gleak.ignore('testFullSpec_param_found'); -gleak.ignore('events'); -gleak.ignore('Uint8Array'); -gleak.ignore('Uint8ClampedArray'); -gleak.ignore('TAP_Global_Harness'); -gleak.ignore('setImmediate'); -gleak.ignore('clearImmediate'); - -gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); -gleak.ignore('DTRACE_NET_STREAM_END'); -gleak.ignore('DTRACE_NET_SOCKET_READ'); -gleak.ignore('DTRACE_NET_SOCKET_WRITE'); -gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); -gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); -gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); -gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); - -module.exports = gleak; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE deleted file mode 100644 index 7c435baae..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/MIT.LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008-2011 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js deleted file mode 100644 index 73834010f..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine-html.js +++ /dev/null @@ -1,190 +0,0 @@ -jasmine.TrivialReporter = function(doc) { - this.document = doc || document; - this.suiteDivs = {}; - this.logRunningSpecs = false; -}; - -jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { - var el = document.createElement(type); - - for (var i = 2; i < arguments.length; i++) { - var child = arguments[i]; - - if (typeof child === 'string') { - el.appendChild(document.createTextNode(child)); - } else { - if (child) { el.appendChild(child); } - } - } - - for (var attr in attrs) { - if (attr == "className") { - el[attr] = attrs[attr]; - } else { - el.setAttribute(attr, attrs[attr]); - } - } - - return el; -}; - -jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { - var showPassed, showSkipped; - - this.outerDiv = this.createDom('div', { className: 'jasmine_reporter' }, - this.createDom('div', { className: 'banner' }, - this.createDom('div', { className: 'logo' }, - this.createDom('span', { className: 'title' }, "Jasmine"), - this.createDom('span', { className: 'version' }, runner.env.versionString())), - this.createDom('div', { className: 'options' }, - "Show ", - showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), - showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), - this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") - ) - ), - - this.runnerDiv = this.createDom('div', { className: 'runner running' }, - this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), - this.runnerMessageSpan = this.createDom('span', {}, "Running..."), - this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) - ); - - this.document.body.appendChild(this.outerDiv); - - var suites = runner.suites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - var suiteDiv = this.createDom('div', { className: 'suite' }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), - this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); - this.suiteDivs[suite.id] = suiteDiv; - var parentDiv = this.outerDiv; - if (suite.parentSuite) { - parentDiv = this.suiteDivs[suite.parentSuite.id]; - } - parentDiv.appendChild(suiteDiv); - } - - this.startedAt = new Date(); - - var self = this; - showPassed.onclick = function(evt) { - if (showPassed.checked) { - self.outerDiv.className += ' show-passed'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); - } - }; - - showSkipped.onclick = function(evt) { - if (showSkipped.checked) { - self.outerDiv.className += ' show-skipped'; - } else { - self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); - } - }; -}; - -jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { - var results = runner.results(); - var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; - this.runnerDiv.setAttribute("class", className); - //do it twice for IE - this.runnerDiv.setAttribute("className", className); - var specs = runner.specs(); - var specCount = 0; - for (var i = 0; i < specs.length; i++) { - if (this.specFilter(specs[i])) { - specCount++; - } - } - var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); - message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; - this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); - - this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); -}; - -jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { - var results = suite.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.totalCount === 0) { // todo: change this to check results.skipped - status = 'skipped'; - } - this.suiteDivs[suite.id].className += " " + status; -}; - -jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { - if (this.logRunningSpecs) { - this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); - } -}; - -jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { - var results = spec.results(); - var status = results.passed() ? 'passed' : 'failed'; - if (results.skipped) { - status = 'skipped'; - } - var specDiv = this.createDom('div', { className: 'spec ' + status }, - this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), - this.createDom('a', { - className: 'description', - href: '?spec=' + encodeURIComponent(spec.getFullName()), - title: spec.getFullName() - }, spec.description)); - - - var resultItems = results.getItems(); - var messagesDiv = this.createDom('div', { className: 'messages' }); - for (var i = 0; i < resultItems.length; i++) { - var result = resultItems[i]; - - if (result.type == 'log') { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); - } else if (result.type == 'expect' && result.passed && !result.passed()) { - messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); - - if (result.trace.stack) { - messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); - } - } - } - - if (messagesDiv.childNodes.length > 0) { - specDiv.appendChild(messagesDiv); - } - - this.suiteDivs[spec.suite.id].appendChild(specDiv); -}; - -jasmine.TrivialReporter.prototype.log = function() { - var console = jasmine.getGlobal().console; - if (console && console.log) { - if (console.log.apply) { - console.log.apply(console, arguments); - } else { - console.log(arguments); // ie fix: console.log.apply doesn't exist on ie - } - } -}; - -jasmine.TrivialReporter.prototype.getLocation = function() { - return this.document.location; -}; - -jasmine.TrivialReporter.prototype.specFilter = function(spec) { - var paramMap = {}; - var params = this.getLocation().search.substring(1).split('&'); - for (var i = 0; i < params.length; i++) { - var p = params[i].split('='); - paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); - } - - if (!paramMap.spec) { - return true; - } - return spec.getFullName().indexOf(paramMap.spec) === 0; -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css deleted file mode 100644 index 6583fe7c6..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.css +++ /dev/null @@ -1,166 +0,0 @@ -body { - font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; -} - - -.jasmine_reporter a:visited, .jasmine_reporter a { - color: #303; -} - -.jasmine_reporter a:hover, .jasmine_reporter a:active { - color: blue; -} - -.run_spec { - float:right; - padding-right: 5px; - font-size: .8em; - text-decoration: none; -} - -.jasmine_reporter { - margin: 0 5px; -} - -.banner { - color: #303; - background-color: #fef; - padding: 5px; -} - -.logo { - float: left; - font-size: 1.1em; - padding-left: 5px; -} - -.logo .version { - font-size: .6em; - padding-left: 1em; -} - -.runner.running { - background-color: yellow; -} - - -.options { - text-align: right; - font-size: .8em; -} - - - - -.suite { - border: 1px outset gray; - margin: 5px 0; - padding-left: 1em; -} - -.suite .suite { - margin: 5px; -} - -.suite.passed { - background-color: #dfd; -} - -.suite.failed { - background-color: #fdd; -} - -.spec { - margin: 5px; - padding-left: 1em; - clear: both; -} - -.spec.failed, .spec.passed, .spec.skipped { - padding-bottom: 5px; - border: 1px solid gray; -} - -.spec.failed { - background-color: #fbb; - border-color: red; -} - -.spec.passed { - background-color: #bfb; - border-color: green; -} - -.spec.skipped { - background-color: #bbb; -} - -.messages { - border-left: 1px dashed gray; - padding-left: 1em; - padding-right: 1em; -} - -.passed { - background-color: #cfc; - display: none; -} - -.failed { - background-color: #fbb; -} - -.skipped { - color: #777; - background-color: #eee; - display: none; -} - - -/*.resultMessage {*/ - /*white-space: pre;*/ -/*}*/ - -.resultMessage span.result { - display: block; - line-height: 2em; - color: black; -} - -.resultMessage .mismatch { - color: black; -} - -.stackTrace { - white-space: pre; - font-size: .8em; - margin-left: 10px; - max-height: 5em; - overflow: auto; - border: 1px inset red; - padding: 1em; - background: #eef; -} - -.finished-at { - padding-left: 1em; - font-size: .6em; -} - -.show-passed .passed, -.show-skipped .skipped { - display: block; -} - - -#jasmine_content { - position:fixed; - right: 100%; -} - -.runner { - border: 1px solid gray; - display: block; - margin: 5px 0; - padding: 2px 0 2px 10px; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js deleted file mode 100644 index c3d2dc7d2..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine.js +++ /dev/null @@ -1,2476 +0,0 @@ -var isCommonJS = typeof window == "undefined"; - -/** - * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. - * - * @namespace - */ -var jasmine = {}; -if (isCommonJS) exports.jasmine = jasmine; -/** - * @private - */ -jasmine.unimplementedMethod_ = function() { - throw new Error("unimplemented method"); -}; - -/** - * Use jasmine.undefined instead of undefined, since undefined is just - * a plain old variable and may be redefined by somebody else. - * - * @private - */ -jasmine.undefined = jasmine.___undefined___; - -/** - * Show diagnostic messages in the console if set to true - * - */ -jasmine.VERBOSE = false; - -/** - * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. - * - */ -jasmine.DEFAULT_UPDATE_INTERVAL = 250; - -/** - * Default timeout interval in milliseconds for waitsFor() blocks. - */ -jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; - -jasmine.getGlobal = function() { - function getGlobal() { - return this; - } - - return getGlobal(); -}; - -/** - * Allows for bound functions to be compared. Internal use only. - * - * @ignore - * @private - * @param base {Object} bound 'this' for the function - * @param name {Function} function to find - */ -jasmine.bindOriginal_ = function(base, name) { - var original = base[name]; - if (original.apply) { - return function() { - return original.apply(base, arguments); - }; - } else { - // IE support - return jasmine.getGlobal()[name]; - } -}; - -jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); -jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); -jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); -jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); - -jasmine.MessageResult = function(values) { - this.type = 'log'; - this.values = values; - this.trace = new Error(); // todo: test better -}; - -jasmine.MessageResult.prototype.toString = function() { - var text = ""; - for (var i = 0; i < this.values.length; i++) { - if (i > 0) text += " "; - if (jasmine.isString_(this.values[i])) { - text += this.values[i]; - } else { - text += jasmine.pp(this.values[i]); - } - } - return text; -}; - -jasmine.ExpectationResult = function(params) { - this.type = 'expect'; - this.matcherName = params.matcherName; - this.passed_ = params.passed; - this.expected = params.expected; - this.actual = params.actual; - this.message = this.passed_ ? 'Passed.' : params.message; - - var trace = (params.trace || new Error(this.message)); - this.trace = this.passed_ ? '' : trace; -}; - -jasmine.ExpectationResult.prototype.toString = function () { - return this.message; -}; - -jasmine.ExpectationResult.prototype.passed = function () { - return this.passed_; -}; - -/** - * Getter for the Jasmine environment. Ensures one gets created - */ -jasmine.getEnv = function() { - var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); - return env; -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isArray_ = function(value) { - return jasmine.isA_("Array", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isString_ = function(value) { - return jasmine.isA_("String", value); -}; - -/** - * @ignore - * @private - * @param value - * @returns {Boolean} - */ -jasmine.isNumber_ = function(value) { - return jasmine.isA_("Number", value); -}; - -/** - * @ignore - * @private - * @param {String} typeName - * @param value - * @returns {Boolean} - */ -jasmine.isA_ = function(typeName, value) { - return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; -}; - -/** - * Pretty printer for expecations. Takes any object and turns it into a human-readable string. - * - * @param value {Object} an object to be outputted - * @returns {String} - */ -jasmine.pp = function(value) { - var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); - stringPrettyPrinter.format(value); - return stringPrettyPrinter.string; -}; - -/** - * Returns true if the object is a DOM Node. - * - * @param {Object} obj object to check - * @returns {Boolean} - */ -jasmine.isDomNode = function(obj) { - return obj.nodeType > 0; -}; - -/** - * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. - * - * @example - * // don't care about which function is passed in, as long as it's a function - * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); - * - * @param {Class} clazz - * @returns matchable object of the type clazz - */ -jasmine.any = function(clazz) { - return new jasmine.Matchers.Any(clazz); -}; - -/** - * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. - * - * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine - * expectation syntax. Spies can be checked if they were called or not and what the calling params were. - * - * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). - * - * Spies are torn down at the end of every spec. - * - * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. - * - * @example - * // a stub - * var myStub = jasmine.createSpy('myStub'); // can be used anywhere - * - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // actual foo.not will not be called, execution stops - * spyOn(foo, 'not'); - - // foo.not spied upon, execution will continue to implementation - * spyOn(foo, 'not').andCallThrough(); - * - * // fake example - * var foo = { - * not: function(bool) { return !bool; } - * } - * - * // foo.not(val) will return val - * spyOn(foo, 'not').andCallFake(function(value) {return value;}); - * - * // mock example - * foo.not(7 == 7); - * expect(foo.not).toHaveBeenCalled(); - * expect(foo.not).toHaveBeenCalledWith(true); - * - * @constructor - * @see spyOn, jasmine.createSpy, jasmine.createSpyObj - * @param {String} name - */ -jasmine.Spy = function(name) { - /** - * The name of the spy, if provided. - */ - this.identity = name || 'unknown'; - /** - * Is this Object a spy? - */ - this.isSpy = true; - /** - * The actual function this spy stubs. - */ - this.plan = function() { - }; - /** - * Tracking of the most recent call to the spy. - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy.mostRecentCall.args = [1, 2]; - */ - this.mostRecentCall = {}; - - /** - * Holds arguments for each call to the spy, indexed by call count - * @example - * var mySpy = jasmine.createSpy('foo'); - * mySpy(1, 2); - * mySpy(7, 8); - * mySpy.mostRecentCall.args = [7, 8]; - * mySpy.argsForCall[0] = [1, 2]; - * mySpy.argsForCall[1] = [7, 8]; - */ - this.argsForCall = []; - this.calls = []; -}; - -/** - * Tells a spy to call through to the actual implemenatation. - * - * @example - * var foo = { - * bar: function() { // do some stuff } - * } - * - * // defining a spy on an existing property: foo.bar - * spyOn(foo, 'bar').andCallThrough(); - */ -jasmine.Spy.prototype.andCallThrough = function() { - this.plan = this.originalValue; - return this; -}; - -/** - * For setting the return value of a spy. - * - * @example - * // defining a spy from scratch: foo() returns 'baz' - * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); - * - * // defining a spy on an existing property: foo.bar() returns 'baz' - * spyOn(foo, 'bar').andReturn('baz'); - * - * @param {Object} value - */ -jasmine.Spy.prototype.andReturn = function(value) { - this.plan = function() { - return value; - }; - return this; -}; - -/** - * For throwing an exception when a spy is called. - * - * @example - * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' - * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); - * - * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' - * spyOn(foo, 'bar').andThrow('baz'); - * - * @param {String} exceptionMsg - */ -jasmine.Spy.prototype.andThrow = function(exceptionMsg) { - this.plan = function() { - throw exceptionMsg; - }; - return this; -}; - -/** - * Calls an alternate implementation when a spy is called. - * - * @example - * var baz = function() { - * // do some stuff, return something - * } - * // defining a spy from scratch: foo() calls the function baz - * var foo = jasmine.createSpy('spy on foo').andCall(baz); - * - * // defining a spy on an existing property: foo.bar() calls an anonymnous function - * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); - * - * @param {Function} fakeFunc - */ -jasmine.Spy.prototype.andCallFake = function(fakeFunc) { - this.plan = fakeFunc; - return this; -}; - -/** - * Resets all of a spy's the tracking variables so that it can be used again. - * - * @example - * spyOn(foo, 'bar'); - * - * foo.bar(); - * - * expect(foo.bar.callCount).toEqual(1); - * - * foo.bar.reset(); - * - * expect(foo.bar.callCount).toEqual(0); - */ -jasmine.Spy.prototype.reset = function() { - this.wasCalled = false; - this.callCount = 0; - this.argsForCall = []; - this.calls = []; - this.mostRecentCall = {}; -}; - -jasmine.createSpy = function(name) { - - var spyObj = function() { - spyObj.wasCalled = true; - spyObj.callCount++; - var args = jasmine.util.argsToArray(arguments); - spyObj.mostRecentCall.object = this; - spyObj.mostRecentCall.args = args; - spyObj.argsForCall.push(args); - spyObj.calls.push({object: this, args: args}); - return spyObj.plan.apply(this, arguments); - }; - - var spy = new jasmine.Spy(name); - - for (var prop in spy) { - spyObj[prop] = spy[prop]; - } - - spyObj.reset(); - - return spyObj; -}; - -/** - * Determines whether an object is a spy. - * - * @param {jasmine.Spy|Object} putativeSpy - * @returns {Boolean} - */ -jasmine.isSpy = function(putativeSpy) { - return putativeSpy && putativeSpy.isSpy; -}; - -/** - * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something - * large in one call. - * - * @param {String} baseName name of spy class - * @param {Array} methodNames array of names of methods to make spies - */ -jasmine.createSpyObj = function(baseName, methodNames) { - if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { - throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); - } - var obj = {}; - for (var i = 0; i < methodNames.length; i++) { - obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); - } - return obj; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the current spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.log = function() { - var spec = jasmine.getEnv().currentSpec; - spec.log.apply(spec, arguments); -}; - -/** - * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. - * - * @example - * // spy example - * var foo = { - * not: function(bool) { return !bool; } - * } - * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops - * - * @see jasmine.createSpy - * @param obj - * @param methodName - * @returns a Jasmine spy that can be chained with all spy methods - */ -var spyOn = function(obj, methodName) { - return jasmine.getEnv().currentSpec.spyOn(obj, methodName); -}; -if (isCommonJS) exports.spyOn = spyOn; - -/** - * Creates a Jasmine spec that will be added to the current suite. - * - * // TODO: pending tests - * - * @example - * it('should be true', function() { - * expect(true).toEqual(true); - * }); - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var it = function(desc, func) { - return jasmine.getEnv().it(desc, func); -}; -if (isCommonJS) exports.it = it; - -/** - * Creates a disabled Jasmine spec. - * - * A convenience method that allows existing specs to be disabled temporarily during development. - * - * @param {String} desc description of this specification - * @param {Function} func defines the preconditions and expectations of the spec - */ -var xit = function(desc, func) { - return jasmine.getEnv().xit(desc, func); -}; -if (isCommonJS) exports.xit = xit; - -/** - * Starts a chain for a Jasmine expectation. - * - * It is passed an Object that is the actual value and should chain to one of the many - * jasmine.Matchers functions. - * - * @param {Object} actual Actual value to test against and expected value - */ -var expect = function(actual) { - return jasmine.getEnv().currentSpec.expect(actual); -}; -if (isCommonJS) exports.expect = expect; - -/** - * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. - * - * @param {Function} func Function that defines part of a jasmine spec. - */ -var runs = function(func) { - jasmine.getEnv().currentSpec.runs(func); -}; -if (isCommonJS) exports.runs = runs; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -var waits = function(timeout) { - jasmine.getEnv().currentSpec.waits(timeout); -}; -if (isCommonJS) exports.waits = waits; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); -}; -if (isCommonJS) exports.waitsFor = waitsFor; - -/** - * A function that is called before each spec in a suite. - * - * Used for spec setup, including validating assumptions. - * - * @param {Function} beforeEachFunction - */ -var beforeEach = function(beforeEachFunction) { - jasmine.getEnv().beforeEach(beforeEachFunction); -}; -if (isCommonJS) exports.beforeEach = beforeEach; - -/** - * A function that is called after each spec in a suite. - * - * Used for restoring any state that is hijacked during spec execution. - * - * @param {Function} afterEachFunction - */ -var afterEach = function(afterEachFunction) { - jasmine.getEnv().afterEach(afterEachFunction); -}; -if (isCommonJS) exports.afterEach = afterEach; - -/** - * Defines a suite of specifications. - * - * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared - * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization - * of setup in some tests. - * - * @example - * // TODO: a simple suite - * - * // TODO: a simple suite with a nested describe block - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var describe = function(description, specDefinitions) { - return jasmine.getEnv().describe(description, specDefinitions); -}; -if (isCommonJS) exports.describe = describe; - -/** - * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. - * - * @param {String} description A string, usually the class under test. - * @param {Function} specDefinitions function that defines several specs. - */ -var xdescribe = function(description, specDefinitions) { - return jasmine.getEnv().xdescribe(description, specDefinitions); -}; -if (isCommonJS) exports.xdescribe = xdescribe; - - -// Provide the XMLHttpRequest class for IE 5.x-6.x: -jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { - function tryIt(f) { - try { - return f(); - } catch(e) { - } - return null; - } - - var xhr = tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.6.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP.3.0"); - }) || - tryIt(function() { - return new ActiveXObject("Msxml2.XMLHTTP"); - }) || - tryIt(function() { - return new ActiveXObject("Microsoft.XMLHTTP"); - }); - - if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); - - return xhr; -} : XMLHttpRequest; -/** - * @namespace - */ -jasmine.util = {}; - -/** - * Declare that a child class inherit it's prototype from the parent class. - * - * @private - * @param {Function} childClass - * @param {Function} parentClass - */ -jasmine.util.inherit = function(childClass, parentClass) { - /** - * @private - */ - var subclass = function() { - }; - subclass.prototype = parentClass.prototype; - childClass.prototype = new subclass(); -}; - -jasmine.util.formatException = function(e) { - var lineNumber; - if (e.line) { - lineNumber = e.line; - } - else if (e.lineNumber) { - lineNumber = e.lineNumber; - } - - var file; - - if (e.sourceURL) { - file = e.sourceURL; - } - else if (e.fileName) { - file = e.fileName; - } - - var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); - - if (file && lineNumber) { - message += ' in ' + file + ' (line ' + lineNumber + ')'; - } - - return message; -}; - -jasmine.util.htmlEscape = function(str) { - if (!str) return str; - return str.replace(/&/g, '&') - .replace(//g, '>'); -}; - -jasmine.util.argsToArray = function(args) { - var arrayOfArgs = []; - for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); - return arrayOfArgs; -}; - -jasmine.util.extend = function(destination, source) { - for (var property in source) destination[property] = source[property]; - return destination; -}; - -/** - * Environment for Jasmine - * - * @constructor - */ -jasmine.Env = function() { - this.currentSpec = null; - this.currentSuite = null; - this.currentRunner_ = new jasmine.Runner(this); - - this.reporter = new jasmine.MultiReporter(); - - this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; - this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; - this.lastUpdate = 0; - this.specFilter = function() { - return true; - }; - - this.nextSpecId_ = 0; - this.nextSuiteId_ = 0; - this.equalityTesters_ = []; - - // wrap matchers - this.matchersClass = function() { - jasmine.Matchers.apply(this, arguments); - }; - jasmine.util.inherit(this.matchersClass, jasmine.Matchers); - - jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); -}; - - -jasmine.Env.prototype.setTimeout = jasmine.setTimeout; -jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; -jasmine.Env.prototype.setInterval = jasmine.setInterval; -jasmine.Env.prototype.clearInterval = jasmine.clearInterval; - -/** - * @returns an object containing jasmine version build info, if set. - */ -jasmine.Env.prototype.version = function () { - if (jasmine.version_) { - return jasmine.version_; - } else { - throw new Error('Version not set'); - } -}; - -/** - * @returns string containing jasmine version build info, if set. - */ -jasmine.Env.prototype.versionString = function() { - if (!jasmine.version_) { - return "version unknown"; - } - - var version = this.version(); - var versionString = version.major + "." + version.minor + "." + version.build; - if (version.release_candidate) { - versionString += ".rc" + version.release_candidate; - } - versionString += " revision " + version.revision; - return versionString; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSpecId = function () { - return this.nextSpecId_++; -}; - -/** - * @returns a sequential integer starting at 0 - */ -jasmine.Env.prototype.nextSuiteId = function () { - return this.nextSuiteId_++; -}; - -/** - * Register a reporter to receive status updates from Jasmine. - * @param {jasmine.Reporter} reporter An object which will receive status updates. - */ -jasmine.Env.prototype.addReporter = function(reporter) { - this.reporter.addReporter(reporter); -}; - -jasmine.Env.prototype.execute = function() { - this.currentRunner_.execute(); -}; - -jasmine.Env.prototype.describe = function(description, specDefinitions) { - var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); - - var parentSuite = this.currentSuite; - if (parentSuite) { - parentSuite.add(suite); - } else { - this.currentRunner_.add(suite); - } - - this.currentSuite = suite; - - var declarationError = null; - try { - specDefinitions.call(suite); - } catch(e) { - declarationError = e; - } - - if (declarationError) { - this.it("encountered a declaration exception", function() { - throw declarationError; - }); - } - - this.currentSuite = parentSuite; - - return suite; -}; - -jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { - if (this.currentSuite) { - this.currentSuite.beforeEach(beforeEachFunction); - } else { - this.currentRunner_.beforeEach(beforeEachFunction); - } -}; - -jasmine.Env.prototype.currentRunner = function () { - return this.currentRunner_; -}; - -jasmine.Env.prototype.afterEach = function(afterEachFunction) { - if (this.currentSuite) { - this.currentSuite.afterEach(afterEachFunction); - } else { - this.currentRunner_.afterEach(afterEachFunction); - } - -}; - -jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { - return { - execute: function() { - } - }; -}; - -jasmine.Env.prototype.it = function(description, func) { - var spec = new jasmine.Spec(this, this.currentSuite, description); - this.currentSuite.add(spec); - this.currentSpec = spec; - - if (func) { - spec.runs(func); - } - - return spec; -}; - -jasmine.Env.prototype.xit = function(desc, func) { - return { - id: this.nextSpecId(), - runs: function() { - } - }; -}; - -jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { - if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { - return true; - } - - a.__Jasmine_been_here_before__ = b; - b.__Jasmine_been_here_before__ = a; - - var hasKey = function(obj, keyName) { - return obj !== null && obj[keyName] !== jasmine.undefined; - }; - - for (var property in b) { - if (!hasKey(a, property) && hasKey(b, property)) { - mismatchKeys.push("expected has key '" + property + "', but missing from actual."); - } - } - for (property in a) { - if (!hasKey(b, property) && hasKey(a, property)) { - mismatchKeys.push("expected missing key '" + property + "', but present in actual."); - } - } - for (property in b) { - if (property == '__Jasmine_been_here_before__') continue; - if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { - mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); - } - } - - if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { - mismatchValues.push("arrays were not the same length"); - } - - delete a.__Jasmine_been_here_before__; - delete b.__Jasmine_been_here_before__; - return (mismatchKeys.length === 0 && mismatchValues.length === 0); -}; - -jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { - mismatchKeys = mismatchKeys || []; - mismatchValues = mismatchValues || []; - - for (var i = 0; i < this.equalityTesters_.length; i++) { - var equalityTester = this.equalityTesters_[i]; - var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); - if (result !== jasmine.undefined) return result; - } - - if (a === b) return true; - - if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { - return (a == jasmine.undefined && b == jasmine.undefined); - } - - if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { - return a === b; - } - - if (a instanceof Date && b instanceof Date) { - return a.getTime() == b.getTime(); - } - - if (a instanceof jasmine.Matchers.Any) { - return a.matches(b); - } - - if (b instanceof jasmine.Matchers.Any) { - return b.matches(a); - } - - if (jasmine.isString_(a) && jasmine.isString_(b)) { - return (a == b); - } - - if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { - return (a == b); - } - - if (typeof a === "object" && typeof b === "object") { - return this.compareObjects_(a, b, mismatchKeys, mismatchValues); - } - - //Straight check - return (a === b); -}; - -jasmine.Env.prototype.contains_ = function(haystack, needle) { - if (jasmine.isArray_(haystack)) { - for (var i = 0; i < haystack.length; i++) { - if (this.equals_(haystack[i], needle)) return true; - } - return false; - } - return haystack.indexOf(needle) >= 0; -}; - -jasmine.Env.prototype.addEqualityTester = function(equalityTester) { - this.equalityTesters_.push(equalityTester); -}; -/** No-op base class for Jasmine reporters. - * - * @constructor - */ -jasmine.Reporter = function() { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportRunnerResults = function(runner) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecStarting = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.reportSpecResults = function(spec) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.Reporter.prototype.log = function(str) { -}; - -/** - * Blocks are functions with executable code that make up a spec. - * - * @constructor - * @param {jasmine.Env} env - * @param {Function} func - * @param {jasmine.Spec} spec - */ -jasmine.Block = function(env, func, spec) { - this.env = env; - this.func = func; - this.spec = spec; -}; - -jasmine.Block.prototype.execute = function(onComplete) { - try { - this.func.apply(this.spec); - } catch (e) { - this.spec.fail(e); - } - onComplete(); -}; -/** JavaScript API reporter. - * - * @constructor - */ -jasmine.JsApiReporter = function() { - this.started = false; - this.finished = false; - this.suites_ = []; - this.results_ = {}; -}; - -jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { - this.started = true; - var suites = runner.topLevelSuites(); - for (var i = 0; i < suites.length; i++) { - var suite = suites[i]; - this.suites_.push(this.summarize_(suite)); - } -}; - -jasmine.JsApiReporter.prototype.suites = function() { - return this.suites_; -}; - -jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { - var isSuite = suiteOrSpec instanceof jasmine.Suite; - var summary = { - id: suiteOrSpec.id, - name: suiteOrSpec.description, - type: isSuite ? 'suite' : 'spec', - children: [] - }; - - if (isSuite) { - var children = suiteOrSpec.children(); - for (var i = 0; i < children.length; i++) { - summary.children.push(this.summarize_(children[i])); - } - } - return summary; -}; - -jasmine.JsApiReporter.prototype.results = function() { - return this.results_; -}; - -jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { - return this.results_[specId]; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { - this.finished = true; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { - this.results_[spec.id] = { - messages: spec.results().getItems(), - result: spec.results().failedCount > 0 ? "failed" : "passed" - }; -}; - -//noinspection JSUnusedLocalSymbols -jasmine.JsApiReporter.prototype.log = function(str) { -}; - -jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ - var results = {}; - for (var i = 0; i < specIds.length; i++) { - var specId = specIds[i]; - results[specId] = this.summarizeResult_(this.results_[specId]); - } - return results; -}; - -jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ - var summaryMessages = []; - var messagesLength = result.messages.length; - for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { - var resultMessage = result.messages[messageIndex]; - summaryMessages.push({ - text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, - passed: resultMessage.passed ? resultMessage.passed() : true, - type: resultMessage.type, - message: resultMessage.message, - trace: { - stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined - } - }); - } - - return { - result : result.result, - messages : summaryMessages - }; -}; - -/** - * @constructor - * @param {jasmine.Env} env - * @param actual - * @param {jasmine.Spec} spec - */ -jasmine.Matchers = function(env, actual, spec, opt_isNot) { - this.env = env; - this.actual = actual; - this.spec = spec; - this.isNot = opt_isNot || false; - this.reportWasCalled_ = false; -}; - -// todo: @deprecated as of Jasmine 0.11, remove soon [xw] -jasmine.Matchers.pp = function(str) { - throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); -}; - -// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] -jasmine.Matchers.prototype.report = function(result, failing_message, details) { - throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); -}; - -jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { - for (var methodName in prototype) { - if (methodName == 'report') continue; - var orig = prototype[methodName]; - matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); - } -}; - -jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { - return function() { - var matcherArgs = jasmine.util.argsToArray(arguments); - var result = matcherFunction.apply(this, arguments); - - if (this.isNot) { - result = !result; - } - - if (this.reportWasCalled_) return result; - - var message; - if (!result) { - if (this.message) { - message = this.message.apply(this, arguments); - if (jasmine.isArray_(message)) { - message = message[this.isNot ? 1 : 0]; - } - } else { - var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); - message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; - if (matcherArgs.length > 0) { - for (var i = 0; i < matcherArgs.length; i++) { - if (i > 0) message += ","; - message += " " + jasmine.pp(matcherArgs[i]); - } - } - message += "."; - } - } - var expectationResult = new jasmine.ExpectationResult({ - matcherName: matcherName, - passed: result, - expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], - actual: this.actual, - message: message - }); - this.spec.addMatcherResult(expectationResult); - return jasmine.undefined; - }; -}; - - - - -/** - * toBe: compares the actual to the expected using === - * @param expected - */ -jasmine.Matchers.prototype.toBe = function(expected) { - return this.actual === expected; -}; - -/** - * toNotBe: compares the actual to the expected using !== - * @param expected - * @deprecated as of 1.0. Use not.toBe() instead. - */ -jasmine.Matchers.prototype.toNotBe = function(expected) { - return this.actual !== expected; -}; - -/** - * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. - * - * @param expected - */ -jasmine.Matchers.prototype.toEqual = function(expected) { - return this.env.equals_(this.actual, expected); -}; - -/** - * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual - * @param expected - * @deprecated as of 1.0. Use not.toNotEqual() instead. - */ -jasmine.Matchers.prototype.toNotEqual = function(expected) { - return !this.env.equals_(this.actual, expected); -}; - -/** - * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes - * a pattern or a String. - * - * @param expected - */ -jasmine.Matchers.prototype.toMatch = function(expected) { - return new RegExp(expected).test(this.actual); -}; - -/** - * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch - * @param expected - * @deprecated as of 1.0. Use not.toMatch() instead. - */ -jasmine.Matchers.prototype.toNotMatch = function(expected) { - return !(new RegExp(expected).test(this.actual)); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeDefined = function() { - return (this.actual !== jasmine.undefined); -}; - -/** - * Matcher that compares the actual to jasmine.undefined. - */ -jasmine.Matchers.prototype.toBeUndefined = function() { - return (this.actual === jasmine.undefined); -}; - -/** - * Matcher that compares the actual to null. - */ -jasmine.Matchers.prototype.toBeNull = function() { - return (this.actual === null); -}; - -/** - * Matcher that boolean not-nots the actual. - */ -jasmine.Matchers.prototype.toBeTruthy = function() { - return !!this.actual; -}; - - -/** - * Matcher that boolean nots the actual. - */ -jasmine.Matchers.prototype.toBeFalsy = function() { - return !this.actual; -}; - - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called. - */ -jasmine.Matchers.prototype.toHaveBeenCalled = function() { - if (arguments.length > 0) { - throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to have been called.", - "Expected spy " + this.actual.identity + " not to have been called." - ]; - }; - - return this.actual.wasCalled; -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ -jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was not called. - * - * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead - */ -jasmine.Matchers.prototype.wasNotCalled = function() { - if (arguments.length > 0) { - throw new Error('wasNotCalled does not take arguments'); - } - - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy " + this.actual.identity + " to not have been called.", - "Expected spy " + this.actual.identity + " to have been called." - ]; - }; - - return !this.actual.wasCalled; -}; - -/** - * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. - * - * @example - * - */ -jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - this.message = function() { - if (this.actual.callCount === 0) { - // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was." - ]; - } else { - return [ - "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), - "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) - ]; - } - }; - - return this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; - -/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ -jasmine.Matchers.prototype.wasNotCalledWith = function() { - var expectedArgs = jasmine.util.argsToArray(arguments); - if (!jasmine.isSpy(this.actual)) { - throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); - } - - this.message = function() { - return [ - "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", - "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" - ]; - }; - - return !this.env.contains_(this.actual.argsForCall, expectedArgs); -}; - -/** - * Matcher that checks that the expected item is an element in the actual Array. - * - * @param {Object} expected - */ -jasmine.Matchers.prototype.toContain = function(expected) { - return this.env.contains_(this.actual, expected); -}; - -/** - * Matcher that checks that the expected item is NOT an element in the actual Array. - * - * @param {Object} expected - * @deprecated as of 1.0. Use not.toNotContain() instead. - */ -jasmine.Matchers.prototype.toNotContain = function(expected) { - return !this.env.contains_(this.actual, expected); -}; - -jasmine.Matchers.prototype.toBeLessThan = function(expected) { - return this.actual < expected; -}; - -jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { - return this.actual > expected; -}; - -/** - * Matcher that checks that the expected item is equal to the actual item - * up to a given level of decimal precision (default 2). - * - * @param {Number} expected - * @param {Number} precision - */ -jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { - if (!(precision === 0)) { - precision = precision || 2; - } - var multiplier = Math.pow(10, precision); - var actual = Math.round(this.actual * multiplier); - expected = Math.round(expected * multiplier); - return expected == actual; -}; - -/** - * Matcher that checks that the expected exception was thrown by the actual. - * - * @param {String} expected - */ -jasmine.Matchers.prototype.toThrow = function(expected) { - var result = false; - var exception; - if (typeof this.actual != 'function') { - throw new Error('Actual is not a function'); - } - try { - this.actual(); - } catch (e) { - exception = e; - } - if (exception) { - result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); - } - - var not = this.isNot ? "not " : ""; - - this.message = function() { - if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { - return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); - } else { - return "Expected function to throw an exception."; - } - }; - - return result; -}; - -jasmine.Matchers.Any = function(expectedClass) { - this.expectedClass = expectedClass; -}; - -jasmine.Matchers.Any.prototype.matches = function(other) { - if (this.expectedClass == String) { - return typeof other == 'string' || other instanceof String; - } - - if (this.expectedClass == Number) { - return typeof other == 'number' || other instanceof Number; - } - - if (this.expectedClass == Function) { - return typeof other == 'function' || other instanceof Function; - } - - if (this.expectedClass == Object) { - return typeof other == 'object'; - } - - return other instanceof this.expectedClass; -}; - -jasmine.Matchers.Any.prototype.toString = function() { - return ''; -}; - -/** - * @constructor - */ -jasmine.MultiReporter = function() { - this.subReporters_ = []; -}; -jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); - -jasmine.MultiReporter.prototype.addReporter = function(reporter) { - this.subReporters_.push(reporter); -}; - -(function() { - var functionNames = [ - "reportRunnerStarting", - "reportRunnerResults", - "reportSuiteResults", - "reportSpecStarting", - "reportSpecResults", - "log" - ]; - for (var i = 0; i < functionNames.length; i++) { - var functionName = functionNames[i]; - jasmine.MultiReporter.prototype[functionName] = (function(functionName) { - return function() { - for (var j = 0; j < this.subReporters_.length; j++) { - var subReporter = this.subReporters_[j]; - if (subReporter[functionName]) { - subReporter[functionName].apply(subReporter, arguments); - } - } - }; - })(functionName); - } -})(); -/** - * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults - * - * @constructor - */ -jasmine.NestedResults = function() { - /** - * The total count of results - */ - this.totalCount = 0; - /** - * Number of passed results - */ - this.passedCount = 0; - /** - * Number of failed results - */ - this.failedCount = 0; - /** - * Was this suite/spec skipped? - */ - this.skipped = false; - /** - * @ignore - */ - this.items_ = []; -}; - -/** - * Roll up the result counts. - * - * @param result - */ -jasmine.NestedResults.prototype.rollupCounts = function(result) { - this.totalCount += result.totalCount; - this.passedCount += result.passedCount; - this.failedCount += result.failedCount; -}; - -/** - * Adds a log message. - * @param values Array of message parts which will be concatenated later. - */ -jasmine.NestedResults.prototype.log = function(values) { - this.items_.push(new jasmine.MessageResult(values)); -}; - -/** - * Getter for the results: message & results. - */ -jasmine.NestedResults.prototype.getItems = function() { - return this.items_; -}; - -/** - * Adds a result, tracking counts (total, passed, & failed) - * @param {jasmine.ExpectationResult|jasmine.NestedResults} result - */ -jasmine.NestedResults.prototype.addResult = function(result) { - if (result.type != 'log') { - if (result.items_) { - this.rollupCounts(result); - } else { - this.totalCount++; - if (result.passed()) { - this.passedCount++; - } else { - this.failedCount++; - } - } - } - this.items_.push(result); -}; - -/** - * @returns {Boolean} True if everything below passed - */ -jasmine.NestedResults.prototype.passed = function() { - return this.passedCount === this.totalCount; -}; -/** - * Base class for pretty printing for expectation results. - */ -jasmine.PrettyPrinter = function() { - this.ppNestLevel_ = 0; -}; - -/** - * Formats a value in a nice, human-readable string. - * - * @param value - */ -jasmine.PrettyPrinter.prototype.format = function(value) { - if (this.ppNestLevel_ > 40) { - throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); - } - - this.ppNestLevel_++; - try { - if (value === jasmine.undefined) { - this.emitScalar('undefined'); - } else if (value === null) { - this.emitScalar('null'); - } else if (value === jasmine.getGlobal()) { - this.emitScalar(''); - } else if (value instanceof jasmine.Matchers.Any) { - this.emitScalar(value.toString()); - } else if (typeof value === 'string') { - this.emitString(value); - } else if (jasmine.isSpy(value)) { - this.emitScalar("spy on " + value.identity); - } else if (value instanceof RegExp) { - this.emitScalar(value.toString()); - } else if (typeof value === 'function') { - this.emitScalar('Function'); - } else if (typeof value.nodeType === 'number') { - this.emitScalar('HTMLNode'); - } else if (value instanceof Date) { - this.emitScalar('Date(' + value + ')'); - } else if (value.__Jasmine_been_here_before__) { - this.emitScalar(''); - } else if (jasmine.isArray_(value) || typeof value == 'object') { - value.__Jasmine_been_here_before__ = true; - if (jasmine.isArray_(value)) { - this.emitArray(value); - } else { - this.emitObject(value); - } - delete value.__Jasmine_been_here_before__; - } else { - this.emitScalar(value.toString()); - } - } finally { - this.ppNestLevel_--; - } -}; - -jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { - for (var property in obj) { - if (property == '__Jasmine_been_here_before__') continue; - fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && - obj.__lookupGetter__(property) !== null) : false); - } -}; - -jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; -jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; - -jasmine.StringPrettyPrinter = function() { - jasmine.PrettyPrinter.call(this); - - this.string = ''; -}; -jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); - -jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { - this.append(value); -}; - -jasmine.StringPrettyPrinter.prototype.emitString = function(value) { - this.append("'" + value + "'"); -}; - -jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { - this.append('[ '); - for (var i = 0; i < array.length; i++) { - if (i > 0) { - this.append(', '); - } - this.format(array[i]); - } - this.append(' ]'); -}; - -jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { - var self = this; - this.append('{ '); - var first = true; - - this.iterateObject(obj, function(property, isGetter) { - if (first) { - first = false; - } else { - self.append(', '); - } - - self.append(property); - self.append(' : '); - if (isGetter) { - self.append(''); - } else { - self.format(obj[property]); - } - }); - - this.append(' }'); -}; - -jasmine.StringPrettyPrinter.prototype.append = function(value) { - this.string += value; -}; -jasmine.Queue = function(env) { - this.env = env; - this.blocks = []; - this.running = false; - this.index = 0; - this.offset = 0; - this.abort = false; -}; - -jasmine.Queue.prototype.addBefore = function(block) { - this.blocks.unshift(block); -}; - -jasmine.Queue.prototype.add = function(block) { - this.blocks.push(block); -}; - -jasmine.Queue.prototype.insertNext = function(block) { - this.blocks.splice((this.index + this.offset + 1), 0, block); - this.offset++; -}; - -jasmine.Queue.prototype.start = function(onComplete) { - this.running = true; - this.onComplete = onComplete; - this.next_(); -}; - -jasmine.Queue.prototype.isRunning = function() { - return this.running; -}; - -jasmine.Queue.LOOP_DONT_RECURSE = true; - -jasmine.Queue.prototype.next_ = function() { - var self = this; - var goAgain = true; - - while (goAgain) { - goAgain = false; - - if (self.index < self.blocks.length && !this.abort) { - var calledSynchronously = true; - var completedSynchronously = false; - - var onComplete = function () { - if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { - completedSynchronously = true; - return; - } - - if (self.blocks[self.index].abort) { - self.abort = true; - } - - self.offset = 0; - self.index++; - - var now = new Date().getTime(); - if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { - self.env.lastUpdate = now; - self.env.setTimeout(function() { - self.next_(); - }, 0); - } else { - if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { - goAgain = true; - } else { - self.next_(); - } - } - }; - self.blocks[self.index].execute(onComplete); - - calledSynchronously = false; - if (completedSynchronously) { - onComplete(); - } - - } else { - self.running = false; - if (self.onComplete) { - self.onComplete(); - } - } - } -}; - -jasmine.Queue.prototype.results = function() { - var results = new jasmine.NestedResults(); - for (var i = 0; i < this.blocks.length; i++) { - if (this.blocks[i].results) { - results.addResult(this.blocks[i].results()); - } - } - return results; -}; - - -/** - * Runner - * - * @constructor - * @param {jasmine.Env} env - */ -jasmine.Runner = function(env) { - var self = this; - self.env = env; - self.queue = new jasmine.Queue(env); - self.before_ = []; - self.after_ = []; - self.suites_ = []; -}; - -jasmine.Runner.prototype.execute = function() { - var self = this; - if (self.env.reporter.reportRunnerStarting) { - self.env.reporter.reportRunnerStarting(this); - } - self.queue.start(function () { - self.finishCallback(); - }); -}; - -jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.splice(0,0,beforeEachFunction); -}; - -jasmine.Runner.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.splice(0,0,afterEachFunction); -}; - - -jasmine.Runner.prototype.finishCallback = function() { - this.env.reporter.reportRunnerResults(this); -}; - -jasmine.Runner.prototype.addSuite = function(suite) { - this.suites_.push(suite); -}; - -jasmine.Runner.prototype.add = function(block) { - if (block instanceof jasmine.Suite) { - this.addSuite(block); - } - this.queue.add(block); -}; - -jasmine.Runner.prototype.specs = function () { - var suites = this.suites(); - var specs = []; - for (var i = 0; i < suites.length; i++) { - specs = specs.concat(suites[i].specs()); - } - return specs; -}; - -jasmine.Runner.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Runner.prototype.topLevelSuites = function() { - var topLevelSuites = []; - for (var i = 0; i < this.suites_.length; i++) { - if (!this.suites_[i].parentSuite) { - topLevelSuites.push(this.suites_[i]); - } - } - return topLevelSuites; -}; - -jasmine.Runner.prototype.results = function() { - return this.queue.results(); -}; -/** - * Internal representation of a Jasmine specification, or test. - * - * @constructor - * @param {jasmine.Env} env - * @param {jasmine.Suite} suite - * @param {String} description - */ -jasmine.Spec = function(env, suite, description) { - if (!env) { - throw new Error('jasmine.Env() required'); - } - if (!suite) { - throw new Error('jasmine.Suite() required'); - } - var spec = this; - spec.id = env.nextSpecId ? env.nextSpecId() : null; - spec.env = env; - spec.suite = suite; - spec.description = description; - spec.queue = new jasmine.Queue(env); - - spec.afterCallbacks = []; - spec.spies_ = []; - - spec.results_ = new jasmine.NestedResults(); - spec.results_.description = description; - spec.matchersClass = null; -}; - -jasmine.Spec.prototype.getFullName = function() { - return this.suite.getFullName() + ' ' + this.description + '.'; -}; - - -jasmine.Spec.prototype.results = function() { - return this.results_; -}; - -/** - * All parameters are pretty-printed and concatenated together, then written to the spec's output. - * - * Be careful not to leave calls to jasmine.log in production code. - */ -jasmine.Spec.prototype.log = function() { - return this.results_.log(arguments); -}; - -jasmine.Spec.prototype.runs = function (func) { - var block = new jasmine.Block(this.env, func, this); - this.addToQueue(block); - return this; -}; - -jasmine.Spec.prototype.addToQueue = function (block) { - if (this.queue.isRunning()) { - this.queue.insertNext(block); - } else { - this.queue.add(block); - } -}; - -/** - * @param {jasmine.ExpectationResult} result - */ -jasmine.Spec.prototype.addMatcherResult = function(result) { - this.results_.addResult(result); -}; - -jasmine.Spec.prototype.expect = function(actual) { - var positive = new (this.getMatchersClass_())(this.env, actual, this); - positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); - return positive; -}; - -/** - * Waits a fixed time period before moving to the next block. - * - * @deprecated Use waitsFor() instead - * @param {Number} timeout milliseconds to wait - */ -jasmine.Spec.prototype.waits = function(timeout) { - var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); - this.addToQueue(waitsFunc); - return this; -}; - -/** - * Waits for the latchFunction to return true before proceeding to the next block. - * - * @param {Function} latchFunction - * @param {String} optional_timeoutMessage - * @param {Number} optional_timeout - */ -jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { - var latchFunction_ = null; - var optional_timeoutMessage_ = null; - var optional_timeout_ = null; - - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; - switch (typeof arg) { - case 'function': - latchFunction_ = arg; - break; - case 'string': - optional_timeoutMessage_ = arg; - break; - case 'number': - optional_timeout_ = arg; - break; - } - } - - var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); - this.addToQueue(waitsForFunc); - return this; -}; - -jasmine.Spec.prototype.fail = function (e) { - var expectationResult = new jasmine.ExpectationResult({ - passed: false, - message: e ? jasmine.util.formatException(e) : 'Exception', - trace: { stack: e.stack } - }); - this.results_.addResult(expectationResult); -}; - -jasmine.Spec.prototype.getMatchersClass_ = function() { - return this.matchersClass || this.env.matchersClass; -}; - -jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { - var parent = this.getMatchersClass_(); - var newMatchersClass = function() { - parent.apply(this, arguments); - }; - jasmine.util.inherit(newMatchersClass, parent); - jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); - this.matchersClass = newMatchersClass; -}; - -jasmine.Spec.prototype.finishCallback = function() { - this.env.reporter.reportSpecResults(this); -}; - -jasmine.Spec.prototype.finish = function(onComplete) { - this.removeAllSpies(); - this.finishCallback(); - if (onComplete) { - onComplete(); - } -}; - -jasmine.Spec.prototype.after = function(doAfter) { - if (this.queue.isRunning()) { - this.queue.add(new jasmine.Block(this.env, doAfter, this)); - } else { - this.afterCallbacks.unshift(doAfter); - } -}; - -jasmine.Spec.prototype.execute = function(onComplete) { - var spec = this; - if (!spec.env.specFilter(spec)) { - spec.results_.skipped = true; - spec.finish(onComplete); - return; - } - - this.env.reporter.reportSpecStarting(this); - - spec.env.currentSpec = spec; - - spec.addBeforesAndAftersToQueue(); - - spec.queue.start(function () { - spec.finish(onComplete); - }); -}; - -jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { - var runner = this.env.currentRunner(); - var i; - - for (var suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); - } - } - for (i = 0; i < runner.before_.length; i++) { - this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); - } - for (i = 0; i < this.afterCallbacks.length; i++) { - this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); - } - for (suite = this.suite; suite; suite = suite.parentSuite) { - for (i = 0; i < suite.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); - } - } - for (i = 0; i < runner.after_.length; i++) { - this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); - } -}; - -jasmine.Spec.prototype.explodes = function() { - throw 'explodes function should not have been called'; -}; - -jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { - if (obj == jasmine.undefined) { - throw "spyOn could not find an object to spy upon for " + methodName + "()"; - } - - if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { - throw methodName + '() method does not exist'; - } - - if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { - throw new Error(methodName + ' has already been spied upon'); - } - - var spyObj = jasmine.createSpy(methodName); - - this.spies_.push(spyObj); - spyObj.baseObj = obj; - spyObj.methodName = methodName; - spyObj.originalValue = obj[methodName]; - - obj[methodName] = spyObj; - - return spyObj; -}; - -jasmine.Spec.prototype.removeAllSpies = function() { - for (var i = 0; i < this.spies_.length; i++) { - var spy = this.spies_[i]; - spy.baseObj[spy.methodName] = spy.originalValue; - } - this.spies_ = []; -}; - -/** - * Internal representation of a Jasmine suite. - * - * @constructor - * @param {jasmine.Env} env - * @param {String} description - * @param {Function} specDefinitions - * @param {jasmine.Suite} parentSuite - */ -jasmine.Suite = function(env, description, specDefinitions, parentSuite) { - var self = this; - self.id = env.nextSuiteId ? env.nextSuiteId() : null; - self.description = description; - self.queue = new jasmine.Queue(env); - self.parentSuite = parentSuite; - self.env = env; - self.before_ = []; - self.after_ = []; - self.children_ = []; - self.suites_ = []; - self.specs_ = []; -}; - -jasmine.Suite.prototype.getFullName = function() { - var fullName = this.description; - for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { - fullName = parentSuite.description + ' ' + fullName; - } - return fullName; -}; - -jasmine.Suite.prototype.finish = function(onComplete) { - this.env.reporter.reportSuiteResults(this); - this.finished = true; - if (typeof(onComplete) == 'function') { - onComplete(); - } -}; - -jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { - beforeEachFunction.typeName = 'beforeEach'; - this.before_.unshift(beforeEachFunction); -}; - -jasmine.Suite.prototype.afterEach = function(afterEachFunction) { - afterEachFunction.typeName = 'afterEach'; - this.after_.unshift(afterEachFunction); -}; - -jasmine.Suite.prototype.results = function() { - return this.queue.results(); -}; - -jasmine.Suite.prototype.add = function(suiteOrSpec) { - this.children_.push(suiteOrSpec); - if (suiteOrSpec instanceof jasmine.Suite) { - this.suites_.push(suiteOrSpec); - this.env.currentRunner().addSuite(suiteOrSpec); - } else { - this.specs_.push(suiteOrSpec); - } - this.queue.add(suiteOrSpec); -}; - -jasmine.Suite.prototype.specs = function() { - return this.specs_; -}; - -jasmine.Suite.prototype.suites = function() { - return this.suites_; -}; - -jasmine.Suite.prototype.children = function() { - return this.children_; -}; - -jasmine.Suite.prototype.execute = function(onComplete) { - var self = this; - this.queue.start(function () { - self.finish(onComplete); - }); -}; -jasmine.WaitsBlock = function(env, timeout, spec) { - this.timeout = timeout; - jasmine.Block.call(this, env, null, spec); -}; - -jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); - -jasmine.WaitsBlock.prototype.execute = function (onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); - } - this.env.setTimeout(function () { - onComplete(); - }, this.timeout); -}; -/** - * A block which waits for some condition to become true, with timeout. - * - * @constructor - * @extends jasmine.Block - * @param {jasmine.Env} env The Jasmine environment. - * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. - * @param {Function} latchFunction A function which returns true when the desired condition has been met. - * @param {String} message The message to display if the desired condition hasn't been met within the given time period. - * @param {jasmine.Spec} spec The Jasmine spec. - */ -jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { - this.timeout = timeout || env.defaultTimeoutInterval; - this.latchFunction = latchFunction; - this.message = message; - this.totalTimeSpentWaitingForLatch = 0; - jasmine.Block.call(this, env, null, spec); -}; -jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); - -jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; - -jasmine.WaitsForBlock.prototype.execute = function(onComplete) { - if (jasmine.VERBOSE) { - this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); - } - var latchFunctionResult; - try { - latchFunctionResult = this.latchFunction.apply(this.spec); - } catch (e) { - this.spec.fail(e); - onComplete(); - return; - } - - if (latchFunctionResult) { - onComplete(); - } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { - var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); - this.spec.fail({ - name: 'timeout', - message: message - }); - - this.abort = true; - onComplete(); - } else { - this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; - var self = this; - this.env.setTimeout(function() { - self.execute(onComplete); - }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); - } -}; -// Mock setTimeout, clearTimeout -// Contributed by Pivotal Computer Systems, www.pivotalsf.com - -jasmine.FakeTimer = function() { - this.reset(); - - var self = this; - self.setTimeout = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); - return self.timeoutsMade; - }; - - self.setInterval = function(funcToCall, millis) { - self.timeoutsMade++; - self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); - return self.timeoutsMade; - }; - - self.clearTimeout = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - - self.clearInterval = function(timeoutKey) { - self.scheduledFunctions[timeoutKey] = jasmine.undefined; - }; - -}; - -jasmine.FakeTimer.prototype.reset = function() { - this.timeoutsMade = 0; - this.scheduledFunctions = {}; - this.nowMillis = 0; -}; - -jasmine.FakeTimer.prototype.tick = function(millis) { - var oldMillis = this.nowMillis; - var newMillis = oldMillis + millis; - this.runFunctionsWithinRange(oldMillis, newMillis); - this.nowMillis = newMillis; -}; - -jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { - var scheduledFunc; - var funcsToRun = []; - for (var timeoutKey in this.scheduledFunctions) { - scheduledFunc = this.scheduledFunctions[timeoutKey]; - if (scheduledFunc != jasmine.undefined && - scheduledFunc.runAtMillis >= oldMillis && - scheduledFunc.runAtMillis <= nowMillis) { - funcsToRun.push(scheduledFunc); - this.scheduledFunctions[timeoutKey] = jasmine.undefined; - } - } - - if (funcsToRun.length > 0) { - funcsToRun.sort(function(a, b) { - return a.runAtMillis - b.runAtMillis; - }); - for (var i = 0; i < funcsToRun.length; ++i) { - try { - var funcToRun = funcsToRun[i]; - this.nowMillis = funcToRun.runAtMillis; - funcToRun.funcToCall(); - if (funcToRun.recurring) { - this.scheduleFunction(funcToRun.timeoutKey, - funcToRun.funcToCall, - funcToRun.millis, - true); - } - } catch(e) { - } - } - this.runFunctionsWithinRange(oldMillis, nowMillis); - } -}; - -jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { - this.scheduledFunctions[timeoutKey] = { - runAtMillis: this.nowMillis + millis, - funcToCall: funcToCall, - recurring: recurring, - timeoutKey: timeoutKey, - millis: millis - }; -}; - -/** - * @namespace - */ -jasmine.Clock = { - defaultFakeTimer: new jasmine.FakeTimer(), - - reset: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.reset(); - }, - - tick: function(millis) { - jasmine.Clock.assertInstalled(); - jasmine.Clock.defaultFakeTimer.tick(millis); - }, - - runFunctionsWithinRange: function(oldMillis, nowMillis) { - jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); - }, - - scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { - jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); - }, - - useMock: function() { - if (!jasmine.Clock.isInstalled()) { - var spec = jasmine.getEnv().currentSpec; - spec.after(jasmine.Clock.uninstallMock); - - jasmine.Clock.installMock(); - } - }, - - installMock: function() { - jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; - }, - - uninstallMock: function() { - jasmine.Clock.assertInstalled(); - jasmine.Clock.installed = jasmine.Clock.real; - }, - - real: { - setTimeout: jasmine.getGlobal().setTimeout, - clearTimeout: jasmine.getGlobal().clearTimeout, - setInterval: jasmine.getGlobal().setInterval, - clearInterval: jasmine.getGlobal().clearInterval - }, - - assertInstalled: function() { - if (!jasmine.Clock.isInstalled()) { - throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); - } - }, - - isInstalled: function() { - return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; - }, - - installed: null -}; -jasmine.Clock.installed = jasmine.Clock.real; - -//else for IE support -jasmine.getGlobal().setTimeout = function(funcToCall, millis) { - if (jasmine.Clock.installed.setTimeout.apply) { - return jasmine.Clock.installed.setTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.setTimeout(funcToCall, millis); - } -}; - -jasmine.getGlobal().setInterval = function(funcToCall, millis) { - if (jasmine.Clock.installed.setInterval.apply) { - return jasmine.Clock.installed.setInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.setInterval(funcToCall, millis); - } -}; - -jasmine.getGlobal().clearTimeout = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearTimeout.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearTimeout(timeoutKey); - } -}; - -jasmine.getGlobal().clearInterval = function(timeoutKey) { - if (jasmine.Clock.installed.clearTimeout.apply) { - return jasmine.Clock.installed.clearInterval.apply(this, arguments); - } else { - return jasmine.Clock.installed.clearInterval(timeoutKey); - } -}; - -jasmine.version_= { - "major": 1, - "minor": 1, - "build": 0, - "revision": 1315677058 -}; diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png deleted file mode 100644 index 218f3b437..000000000 Binary files a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/bson/tools/jasmine-1.1.0/jasmine_favicon.png and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/LICENSE b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/README.md b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/README.md deleted file mode 100644 index 7428b0d0e..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/README.md +++ /dev/null @@ -1,4 +0,0 @@ -kerberos -======== - -Kerberos library for node.js \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/binding.gyp b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/binding.gyp deleted file mode 100644 index 027a70f20..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/binding.gyp +++ /dev/null @@ -1,41 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'kerberos', - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'conditions': [ - ['OS=="mac"', { - 'sources': [ 'lib/kerberos.cc', 'lib/worker.cc', 'lib/kerberosgss.c', 'lib/base64.c', 'lib/kerberos_context.cc' ], - 'defines': [ - '__MACOSX_CORE__' - ], - 'xcode_settings': { - 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' - }, - "link_settings": { - "libraries": [ - "-lkrb5" - ] - } - }], - ['OS=="win"', { - 'sources': [ - 'lib/win32/kerberos.cc', - 'lib/win32/base64.c', - 'lib/win32/worker.cc', - 'lib/win32/kerberos_sspi.c', - 'lib/win32/wrappers/security_buffer.cc', - 'lib/win32/wrappers/security_buffer_descriptor.cc', - 'lib/win32/wrappers/security_context.cc', - 'lib/win32/wrappers/security_credentials.cc' - ], - "link_settings": { - "libraries": [ - ] - } - }] - ] - } - ] -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Makefile deleted file mode 100644 index 901981cc7..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Makefile +++ /dev/null @@ -1,332 +0,0 @@ -# We borrow heavily from the kernel build setup, though we are simpler since -# we don't have Kconfig tweaking settings on us. - -# The implicit make rules have it looking for RCS files, among other things. -# We instead explicitly write all the rules we care about. -# It's even quicker (saves ~200ms) to pass -r on the command line. -MAKEFLAGS=-r - -# The source directory tree. -srcdir := .. -abs_srcdir := $(abspath $(srcdir)) - -# The name of the builddir. -builddir_name ?= . - -# The V=1 flag on command line makes us verbosely print command lines. -ifdef V - quiet= -else - quiet=quiet_ -endif - -# Specify BUILDTYPE=Release on the command line for a release build. -BUILDTYPE ?= Release - -# Directory all our build output goes into. -# Note that this must be two directories beneath src/ for unit tests to pass, -# as they reach into the src/ directory for data with relative paths. -builddir ?= $(builddir_name)/$(BUILDTYPE) -abs_builddir := $(abspath $(builddir)) -depsdir := $(builddir)/.deps - -# Object output directory. -obj := $(builddir)/obj -abs_obj := $(abspath $(obj)) - -# We build up a list of every single one of the targets so we can slurp in the -# generated dependency rule Makefiles in one pass. -all_deps := - - - -CC.target ?= $(CC) -CFLAGS.target ?= $(CFLAGS) -CXX.target ?= $(CXX) -CXXFLAGS.target ?= $(CXXFLAGS) -LINK.target ?= $(LINK) -LDFLAGS.target ?= $(LDFLAGS) -AR.target ?= $(AR) - -# C++ apps need to be linked with g++. -# -# Note: flock is used to seralize linking. Linking is a memory-intensive -# process so running parallel links can often lead to thrashing. To disable -# the serialization, override LINK via an envrionment variable as follows: -# -# export LINK=g++ -# -# This will allow make to invoke N linker processes as specified in -jN. -LINK ?= flock $(builddir)/linker.lock $(CXX.target) - -# TODO(evan): move all cross-compilation logic to gyp-time so we don't need -# to replicate this environment fallback in make as well. -CC.host ?= gcc -CFLAGS.host ?= -CXX.host ?= g++ -CXXFLAGS.host ?= -LINK.host ?= $(CXX.host) -LDFLAGS.host ?= -AR.host ?= ar - -# Define a dir function that can handle spaces. -# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions -# "leading spaces cannot appear in the text of the first argument as written. -# These characters can be put into the argument value by variable substitution." -empty := -space := $(empty) $(empty) - -# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces -replace_spaces = $(subst $(space),?,$1) -unreplace_spaces = $(subst ?,$(space),$1) -dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) - -# Flags to make gcc output dependency info. Note that you need to be -# careful here to use the flags that ccache and distcc can understand. -# We write to a dep file on the side first and then rename at the end -# so we can't end up with a broken dep file. -depfile = $(depsdir)/$(call replace_spaces,$@).d -DEPFLAGS = -MMD -MF $(depfile).raw - -# We have to fixup the deps output in a few ways. -# (1) the file output should mention the proper .o file. -# ccache or distcc lose the path to the target, so we convert a rule of -# the form: -# foobar.o: DEP1 DEP2 -# into -# path/to/foobar.o: DEP1 DEP2 -# (2) we want missing files not to cause us to fail to build. -# We want to rewrite -# foobar.o: DEP1 DEP2 \ -# DEP3 -# to -# DEP1: -# DEP2: -# DEP3: -# so if the files are missing, they're just considered phony rules. -# We have to do some pretty insane escaping to get those backslashes -# and dollar signs past make, the shell, and sed at the same time. -# Doesn't work with spaces, but that's fine: .d files have spaces in -# their names replaced with other characters. -define fixup_dep -# The depfile may not exist if the input file didn't have any #includes. -touch $(depfile).raw -# Fixup path as in (1). -sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,kerberos.target.mk)))),) - include kerberos.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/vagrant/lab4/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/vagrant/.node-gyp/0.10.24/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/vagrant/.node-gyp/0.10.24" "-Dmodule_root_dir=/home/vagrant/lab4/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../.node-gyp/0.10.24/common.gypi $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d deleted file mode 100644 index 0bc320607..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/kerberos.node := rm -rf "Release/kerberos.node" && cp -af "Release/obj.target/kerberos.node" "Release/kerberos.node" diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d deleted file mode 100644 index ba6dec80c..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/kerberos.node := flock ./Release/linker.lock g++ -shared -pthread -rdynamic -m32 -Wl,-soname=kerberos.node -o Release/obj.target/kerberos.node -Wl,--start-group -Wl,--end-group diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node deleted file mode 100644 index 5d872403f..000000000 Binary files a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/kerberos.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/linker.lock deleted file mode 100644 index e69de29bb..000000000 diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos.node b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos.node deleted file mode 100644 index 5d872403f..000000000 Binary files a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/Release/obj.target/kerberos.node and /dev/null differ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile deleted file mode 100644 index d0d9c64a7..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= build/./. -.PHONY: all -all: - $(MAKE) kerberos diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/config.gypi b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/config.gypi deleted file mode 100644 index 91ce77280..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/config.gypi +++ /dev/null @@ -1,115 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 0, - "gcc_version": 46, - "host_arch": "ia32", - "node_install_npm": "true", - "node_prefix": "/usr/local", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_unsafe_optimizations": 0, - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "node_use_systemtap": "false", - "python": "/usr/bin/python", - "target_arch": "ia32", - "v8_enable_gdbjit": 0, - "v8_no_strict_aliasing": 1, - "v8_use_snapshot": "true", - "nodedir": "/home/vagrant/.node-gyp/0.10.24", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "sign_git_tag": "", - "always_auth": "", - "user_agent": "node/v0.10.24 linux ia32", - "bin_links": "true", - "key": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "user": "", - "force": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "cache_max": "null", - "userconfig": "/home/vagrant/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "tmp": "/home/vagrant/tmp", - "depth": "null", - "save_dev": "", - "usage": "", - "https_proxy": "", - "onload_script": "", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/bash", - "prefix": "/usr/local", - "registry": "https://registry.npmjs.org/", - "browser": "", - "cache_lock_wait": "10000", - "save_optional": "", - "searchopts": "", - "versions": "", - "cache": "/home/vagrant/.npm", - "ignore_scripts": "", - "searchsort": "name", - "version": "", - "local_address": "", - "viewer": "man", - "color": "true", - "fetch_retry_mintimeout": "10000", - "umask": "18", - "fetch_retry_maxtimeout": "60000", - "message": "%s", - "cert": "", - "global": "", - "link": "", - "save": "", - "unicode": "true", - "long": "", - "production": "", - "unsafe_perm": "true", - "node_version": "v0.10.24", - "tag": "latest", - "git_tag_version": "true", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "npat": "", - "proprietary_attribs": "true", - "strict_ssl": "true", - "username": "", - "dev": "", - "globalconfig": "/usr/local/etc/npmrc", - "init_module": "/home/vagrant/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/local/etc/npmignore", - "cache_lock_retries": "10", - "group": "1000", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "email": "", - "json": "" - } -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk deleted file mode 100644 index d2ce49b92..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/build/kerberos.target.mk +++ /dev/null @@ -1,42 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := kerberos -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m32 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m32 - -LIBS := - -$(obj).target/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/kerberos.node: LIBS := $(LIBS) -$(obj).target/kerberos.node: TOOLSET := $(TOOLSET) -$(obj).target/kerberos.node: FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/kerberos.node -# Add target alias -.PHONY: kerberos -kerberos: $(builddir)/kerberos.node - -# Copy this to the executable output path. -$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) -$(builddir)/kerberos.node: $(obj).target/kerberos.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/kerberos.node -# Short alias for building this executable. -.PHONY: kerberos.node -kerberos.node: $(obj).target/kerberos.node $(builddir)/kerberos.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/kerberos.node - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/index.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/index.js deleted file mode 100644 index b8c853276..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/index.js +++ /dev/null @@ -1,6 +0,0 @@ -// Get the Kerberos library -module.exports = require('./lib/kerberos'); -// Set up the auth processes -module.exports['processes'] = { - MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js deleted file mode 100644 index f1e9231a7..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/auth_processes/mongodb.js +++ /dev/null @@ -1,281 +0,0 @@ -var format = require('util').format; - -var MongoAuthProcess = function(host, port, service_name) { - // Check what system we are on - if(process.platform == 'win32') { - this._processor = new Win32MongoProcessor(host, port, service_name); - } else { - this._processor = new UnixMongoProcessor(host, port, service_name); - } -} - -MongoAuthProcess.prototype.init = function(username, password, callback) { - this._processor.init(username, password, callback); -} - -MongoAuthProcess.prototype.transition = function(payload, callback) { - this._processor.transition(payload, callback); -} - -/******************************************************************* - * - * Win32 SSIP Processor for MongoDB - * - *******************************************************************/ -var Win32MongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.ssip = require("../kerberos").SSIP; - // Set up first transition - this._transition = Win32MongoProcessor.first_transition(this); - // Set up service name - service_name = service_name || "mongodb"; - // Set up target - this.target = format("%s/%s", service_name, host); - // Number of retries - this.retries = 10; -} - -Win32MongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - // Save the values used later - this.username = username; - this.password = password; - // Aquire credentials - this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { - if(err) return callback(err); - // Save credentials - self.security_credentials = security_credentials; - // Callback with success - callback(null); - }); -} - -Win32MongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -Win32MongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.ssip.SecurityContext.initialize( - self.security_credentials, - self.target, - payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.second_transition(self); - self.security_context = security_context; - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.second_transition = function(self) { - return function(payload, callback) { - // Perform a step - self.security_context.initialize(self.target, payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - self._transition = Win32MongoProcessor.first_transition(self); - // Retry - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.third_transition(self); - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.third_transition = function(self) { - return function(payload, callback) { - var messageLength = 0; - // Get the raw bytes - var encryptedBytes = new Buffer(payload, 'base64'); - var encryptedMessage = new Buffer(messageLength); - // Copy first byte - encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); - // Set up trailer - var securityTrailerLength = encryptedBytes.length - messageLength; - var securityTrailer = new Buffer(securityTrailerLength); - // Copy the bytes - encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); - - // Types used - var SecurityBuffer = self.ssip.SecurityBuffer; - var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; - - // Set up security buffers - var buffers = [ - new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) - , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) - ]; - - // Set up the descriptor - var descriptor = new SecurityBufferDescriptor(buffers); - - // Decrypt the data - self.security_context.decryptMessage(descriptor, function(err, security_context) { - if(err) return callback(err); - - var length = 4; - if(self.username != null) { - length += self.username.length; - } - - var bytesReceivedFromServer = new Buffer(length); - bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION - bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION - - if(self.username != null) { - var authorization_id_bytes = new Buffer(self.username, 'utf8'); - authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); - } - - self.security_context.queryContextAttributes(0x00, function(err, sizes) { - if(err) return callback(err); - - var buffers = [ - new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) - , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) - , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) - ] - - var descriptor = new SecurityBufferDescriptor(buffers); - - self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { - if(err) return callback(err); - callback(null, security_context.payload); - }); - }); - }); - } -} - -/******************************************************************* - * - * UNIX MIT Kerberos processor - * - *******************************************************************/ -var UnixMongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.Kerberos = require("../kerberos").Kerberos; - this.kerberos = new this.Kerberos(); - service_name = service_name || "mongodb"; - // Set up first transition - this._transition = UnixMongoProcessor.first_transition(this); - // Set up target - this.target = format("%s@%s", service_name, host); - // Number of retries - this.retries = 10; -} - -UnixMongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - this.username = username; - this.password = password; - // Call client initiate - this.kerberos.authGSSClientInit( - self.target - , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - self.context = context; - // Return the context - callback(null, context); - }); -} - -UnixMongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -UnixMongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, '', function(err, result) { - if(err) return callback(err); - // Set up the next step - self._transition = UnixMongoProcessor.second_transition(self); - // Return the payload - callback(null, self.context.response); - }) - } -} - -UnixMongoProcessor.second_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { - if(err && self.retries == 0) return callback(err); - // Attempt to re-establish a context - if(err) { - // Adjust the number of retries - self.retries = self.retries - 1; - // Call same step again - return self.transition(payload, callback); - } - - // Set up the next step - self._transition = UnixMongoProcessor.third_transition(self); - // Return the payload - callback(null, self.context.response || ''); - }); - } -} - -UnixMongoProcessor.third_transition = function(self) { - return function(payload, callback) { - // GSS Client Unwrap - self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { - if(err) return callback(err, false); - - // Wrap the response - self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { - if(err) return callback(err, false); - // Set up the next step - self._transition = UnixMongoProcessor.fourth_transition(self); - // Return the payload - callback(null, self.context.response); - }); - }); - } -} - -UnixMongoProcessor.fourth_transition = function(self) { - return function(payload, callback) { - // Clean up context - self.kerberos.authGSSClientClean(self.context, function(err, result) { - if(err) return callback(err, false); - // Set the transition to null - self._transition = null; - // Callback with valid authentication - callback(null, true); - }); - } -} - -// Set the process -exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/base64.c b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/base64.c deleted file mode 100644 index 4232106b9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/base64.c +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - unsigned char oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - *rlen = 0; - int c1, c2, c3, c4; - - int vlen = strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/base64.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/base64.h deleted file mode 100644 index f0e1f0616..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc deleted file mode 100644 index 08eda82b2..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.cc +++ /dev/null @@ -1,563 +0,0 @@ -#include "kerberos.h" -#include -#include "worker.h" -#include "kerberos_context.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -Persistent Kerberos::constructor_template; - -// Call structs -typedef struct AuthGSSClientCall { - uint32_t flags; - char *uri; -} AuthGSSClientCall; - -typedef struct AuthGSSClientStepCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientStepCall; - -typedef struct AuthGSSClientUnwrapCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientUnwrapCall; - -typedef struct AuthGSSClientWrapCall { - KerberosContext *context; - char *challenge; - char *user_name; -} AuthGSSClientWrapCall; - -typedef struct AuthGSSClientCleanCall { - KerberosContext *context; -} AuthGSSClientCleanCall; - -// VException object (causes throw in calling code) -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(Kerberos::New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("Kerberos")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientInit", AuthGSSClientInit); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientStep", AuthGSSClientStep); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientUnwrap", AuthGSSClientUnwrap); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientWrap", AuthGSSClientWrap); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "authGSSClientClean", AuthGSSClientClean); - - // Set the symbol - target->ForceSet(String::NewSymbol("Kerberos"), constructor_template->GetFunction()); -} - -Handle Kerberos::New(const Arguments &args) { - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - return args.This(); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientInit(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_client_state *)malloc(sizeof(gss_client_state)); - - // Unpack the parameter data struct - AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; - // Start the kerberos client - response = authenticate_gss_client_init(call->uri, call->flags, state); - - // Release the parameter struct memory - free(call->uri); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Handle _map_authGSSClientInit(Worker *worker) { - HandleScope scope; - - KerberosContext *context = KerberosContext::New(); - context->state = (gss_client_state *)worker->return_value; - // Persistent _context = Persistent::New(context->handle_); - return scope.Close(context->handle_); -} - -// Initialize method -Handle Kerberos::AuthGSSClientInit(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 3) return VException("Requires a service string uri, integer flags and a callback function"); - if(args.Length() == 3 && !args[0]->IsString() && !args[1]->IsInt32() && !args[2]->IsFunction()) - return VException("Requires a service string uri, integer flags and a callback function"); - - Local service = args[0]->ToString(); - // Convert uri string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - service->WriteUtf8(service_str); - - // Allocate a structure - AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); - call->flags =args[1]->ToInt32()->Uint32Value(); - call->uri = service_str; - - // Unpack the callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientInit; - worker->mapper = _map_authGSSClientInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientStep(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; - // Get the state - state = call->context->state; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_step(state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientStep(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientStep(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0])) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString()) return VException("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientStep; - worker->mapper = _map_authGSSClientStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientUnwrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientUnwrap(Worker *worker) { - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_unwrap(call->context->state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Handle _map_authGSSClientUnwrap(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientUnwrap(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 2 && args.Length() != 3) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 2 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return VException("Requires a GSS context, optional challenge string and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // If we have a challenge string - if(args.Length() == 3) { - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callback = args.Length() == 3 ? Local::Cast(args[2]) : Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientUnwrap; - worker->mapper = _map_authGSSClientUnwrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientWrap(Worker *worker) { - gss_client_response *response; - char *user_name = NULL; - - // Unpack the parameter data struct - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; - user_name = call->user_name; - - // Check what kind of challenge we have - if(call->user_name == NULL) { - user_name = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - if(call->user_name != NULL) free(call->user_name); - free(call); - free(response); -} - -static Handle _map_authGSSClientWrap(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientWrap(const Arguments &args) { - HandleScope scope; - - // Ensure valid call - if(args.Length() != 3 && args.Length() != 4) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 3 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(args.Length() == 4 && !KerberosContext::HasInstance(args[0]) && !args[1]->IsString() && !args[2]->IsString() && !args[2]->IsFunction()) return VException("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - - // Challenge string - char *challenge_str = NULL; - char *user_name_str = NULL; - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Unpack the challenge string - Local challenge = args[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - // If we have a user string - if(args.Length() == 4) { - // Unpack user name - Local user_name = args[2]->ToString(); - // Convert uri string to c-string - user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); - // Write v8 string to c-string - user_name->WriteUtf8(user_name_str); - } - - // Allocate a structure - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); - call->context = kerberos_context; - call->challenge = challenge_str; - call->user_name = user_name_str; - - // Unpack the callback - Local callback = args.Length() == 4 ? Local::Cast(args[3]) : Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientWrap; - worker->mapper = _map_authGSSClientWrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_client_clean(call->context->state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Handle _map_authGSSClientClean(Worker *worker) { - HandleScope scope; - // Return the return code - return scope.Close(Int32::New(worker->return_code)); -} - -// Initialize method -Handle Kerberos::AuthGSSClientClean(const Arguments &args) { - HandleScope scope; - - // // Ensure valid call - if(args.Length() != 2) return VException("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(args[0]) && !args[1]->IsFunction()) return VException("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = args[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - // Allocate a structure - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); - call->context = kerberos_context; - - // Unpack the callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authGSSClientClean; - worker->mapper = _map_authGSSClientClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - return scope.Close(Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Kerberos::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void Kerberos::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - delete worker; -} - -// Exporting function -extern "C" void init(Handle target) { - HandleScope scope; - Kerberos::Initialize(target); - KerberosContext::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h deleted file mode 100644 index 061995700..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.h +++ /dev/null @@ -1,47 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include - -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static Handle AuthGSSClientInit(const Arguments &args); - static Handle AuthGSSClientStep(const Arguments &args); - static Handle AuthGSSClientUnwrap(const Arguments &args); - static Handle AuthGSSClientWrap(const Arguments &args); - static Handle AuthGSSClientClean(const Arguments &args); - -private: - static Handle New(const Arguments &args); - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js deleted file mode 100644 index b1a701ba0..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos.js +++ /dev/null @@ -1,91 +0,0 @@ -var kerberos = require('../build/Release/kerberos') - , KerberosNative = kerberos.Kerberos; - -var Kerberos = function() { - this._native_kerberos = new KerberosNative(); -} - -Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { - return this._native_kerberos.authGSSClientInit(uri, flags, callback); -} - -Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientStep(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { - if(typeof user_name == 'function') { - callback = user_name; - user_name = ''; - } - - return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); -} - -Kerberos.prototype.authGSSClientClean = function(context, callback) { - return this._native_kerberos.authGSSClientClean(context, callback); -} - -Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { - return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); -} - -Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { - return this._native_kerberos.prepareOutboundPackage(principal, inputdata); -} - -Kerberos.prototype.decryptMessage = function(challenge) { - return this._native_kerberos.decryptMessage(challenge); -} - -Kerberos.prototype.encryptMessage = function(challenge) { - return this._native_kerberos.encryptMessage(challenge); -} - -Kerberos.prototype.queryContextAttribute = function(attribute) { - if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); - return this._native_kerberos.queryContextAttribute(attribute); -} - -// Some useful result codes -Kerberos.AUTH_GSS_CONTINUE = 0; -Kerberos.AUTH_GSS_COMPLETE = 1; - -// Some useful gss flags -Kerberos.GSS_C_DELEG_FLAG = 1; -Kerberos.GSS_C_MUTUAL_FLAG = 2; -Kerberos.GSS_C_REPLAY_FLAG = 4; -Kerberos.GSS_C_SEQUENCE_FLAG = 8; -Kerberos.GSS_C_CONF_FLAG = 16; -Kerberos.GSS_C_INTEG_FLAG = 32; -Kerberos.GSS_C_ANON_FLAG = 64; -Kerberos.GSS_C_PROT_READY_FLAG = 128; -Kerberos.GSS_C_TRANS_FLAG = 256; - -// Export Kerberos class -exports.Kerberos = Kerberos; - -// If we have SSPI (windows) -if(kerberos.SecurityCredentials) { - // Put all SSPI classes in it's own namespace - exports.SSIP = { - SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext: require('./win32/wrappers/security_context').SecurityContext - , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - } -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc deleted file mode 100644 index 7a5f4eb8d..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.cc +++ /dev/null @@ -1,74 +0,0 @@ -#include "kerberos_context.h" - -Persistent KerberosContext::constructor_template; - -KerberosContext::KerberosContext() : ObjectWrap() { -} - -KerberosContext::~KerberosContext() { -} - -KerberosContext* KerberosContext::New() { - HandleScope scope; - - Local obj = constructor_template->GetFunction()->NewInstance(); - KerberosContext *kerberos_context = ObjectWrap::Unwrap(obj); - - return kerberos_context; -} - -Handle KerberosContext::New(const Arguments &args) { - HandleScope scope; - // Create code object - KerberosContext *kerberos_context = new KerberosContext(); - // Wrap it - kerberos_context->Wrap(args.This()); - // Return the object - return args.This(); -} - -static Persistent response_symbol; - -void KerberosContext::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("KerberosContext")); - - // Property symbols - response_symbol = NODE_PSYMBOL("response"); - - // Getter for the response - constructor_template->InstanceTemplate()->SetAccessor(response_symbol, ResponseGetter); - - // Set up the Symbol for the Class on the Module - target->Set(String::NewSymbol("KerberosContext"), constructor_template->GetFunction()); -} - -// -// Response Setter / Getter -Handle KerberosContext::ResponseGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - gss_client_state *state; - - // Unpack the object - KerberosContext *context = ObjectWrap::Unwrap(info.Holder()); - // Let's grab the response - state = context->state; - // No state no response - if(state == NULL || state->response == NULL) return scope.Close(Null()); - // Return the response - return scope.Close(String::New(state->response)); -} - - - - - - - - - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h deleted file mode 100644 index 8becef6d3..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberos_context.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef KERBEROS_CONTEXT_H -#define KERBEROS_CONTEXT_H - -#include -#include -#include -#include - -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class KerberosContext : public ObjectWrap { - -public: - KerberosContext(); - ~KerberosContext(); - - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Public constructor - static KerberosContext* New(); - - // Handle to the kerberos context - gss_client_state *state; - -private: - static Handle New(const Arguments &args); - - static Handle ResponseGetter(Local property, const AccessorInfo& info); -}; -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c deleted file mode 100644 index f17003db3..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.c +++ /dev/null @@ -1,666 +0,0 @@ -/** - * Copyright (c) 2006-2010 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "kerberosgss.h" - -#include "base64.h" - -#include -#include -#include -#include - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min); - -/*extern PyObject *GssException_class; -extern PyObject *KrbException_class; - -char* server_principal_details(const char* service, const char* hostname) -{ - char match[1024]; - int match_len = 0; - char* result = NULL; - - int code; - krb5_context kcontext; - krb5_keytab kt = NULL; - krb5_kt_cursor cursor = NULL; - krb5_keytab_entry entry; - char* pname = NULL; - - // Generate the principal prefix we want to match - snprintf(match, 1024, "%s/%s@", service, hostname); - match_len = strlen(match); - - code = krb5_init_context(&kcontext); - if (code) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot initialize Kerberos5 context", code)); - return NULL; - } - - if ((code = krb5_kt_default(kcontext, &kt))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get default keytab", code)); - goto end; - } - - if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get sequence cursor from keytab", code)); - goto end; - } - - while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) - { - if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot parse principal name from keytab", code)); - goto end; - } - - if (strncmp(pname, match, match_len) == 0) - { - result = malloc(strlen(pname) + 1); - strcpy(result, pname); - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - break; - } - - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - } - - if (result == NULL) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Principal not found in keytab", -1)); - } - -end: - if (cursor) - krb5_kt_end_seq_get(kcontext, kt, &cursor); - if (kt) - krb5_kt_close(kcontext, kt); - krb5_free_context(kcontext); - - return result; -} -*/ -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_COMPLETE; - - state->server_name = GSS_C_NO_NAME; - state->context = GSS_C_NO_CONTEXT; - state->gss_flags = gss_flags; - state->username = NULL; - state->response = NULL; - - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if(state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - - if(state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - - if(state->username != NULL) { - free(state->username); - state->username = NULL; - } - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_init_sec_context(&min_stat, - GSS_C_NO_CREDENTIAL, - &state->context, - state->server_name, - GSS_C_NO_OID, - (OM_uint32)state->gss_flags, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - NULL, - &output_token, - NULL, - NULL); - - if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; - // Grab the client response to send back to the server - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Try to get the user name if we have completed all GSS operations - if (ret == AUTH_GSS_COMPLETE) { - gss_name_t gssuser = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); - - if(GSS_ERROR(maj_stat)) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - gss_buffer_desc name_token; - name_token.length = 0; - maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); - - if(GSS_ERROR(maj_stat)) { - if(name_token.value) - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - state->username = (char *)malloc(name_token.length + 1); - strncpy(state->username, (char*) name_token.value, name_token.length); - state->username[name_token.length] = 0; - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - } - } - -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_unwrap(&min_stat, - state->context, - &input_token, - &output_token, - NULL, - NULL); - - if(maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - ret = AUTH_GSS_COMPLETE; - } - - // Grab the client response - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - char buf[4096], server_conf_flags; - unsigned long buf_size; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - if(user) { - // get bufsize - server_conf_flags = ((char*) input_token.value)[0]; - ((char*) input_token.value)[0] = 0; - buf_size = ntohl(*((long *) input_token.value)); - free(input_token.value); -#ifdef PRINTFS - printf("User: %s, %c%c%c\n", user, - server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', - server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', - server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); - printf("Maximum GSS token size is %ld\n", buf_size); -#endif - - // agree to terms (hack!) - buf_size = htonl(buf_size); // not relevant without integrity/privacy - memcpy(buf, &buf_size, 4); - buf[0] = GSS_AUTH_P_NONE; - // server decides if principal can log in as user - strncpy(buf + 4, user, sizeof(buf) - 4); - input_token.value = buf; - input_token.length = 4 + strlen(user); - } - - // Do GSSAPI wrap - maj_stat = gss_wrap(&min_stat, - state->context, - 0, - GSS_C_QOP_DEFAULT, - &input_token, - NULL, - &output_token); - - if (maj_stat != GSS_S_COMPLETE) { - response = gss_error(maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else - ret = AUTH_GSS_COMPLETE; - // Grab the client response to send back to the server - if (output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - response->return_code = ret; - } - - // Return the response - return response; -} - -int authenticate_gss_server_init(const char *service, gss_server_state *state) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_COMPLETE; - - state->context = GSS_C_NO_CONTEXT; - state->server_name = GSS_C_NO_NAME; - state->client_name = GSS_C_NO_NAME; - state->server_creds = GSS_C_NO_CREDENTIAL; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->targetname = NULL; - state->response = NULL; - - // Server name may be empty which means we aren't going to create our own creds - size_t service_len = strlen(service); - if (service_len != 0) - { - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Get credentials - maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, GSS_C_ACCEPT, &state->server_creds, NULL, NULL); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - } - -end: - return ret; -} - -int authenticate_gss_server_clean(gss_server_state *state) -{ - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->client_name); - if (state->server_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->server_creds); - if (state->client_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) - { - free(state->username); - state->username = NULL; - } - if (state->targetname != NULL) - { - free(state->targetname); - state->targetname = NULL; - } - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - return ret; -} - -/*int authenticate_gss_server_step(gss_server_state *state, const char *challenge) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) - { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - else - { - PyErr_SetString(KrbException_class, "No challenge parameter in request from client"); - ret = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_accept_sec_context(&min_stat, - &state->context, - state->server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &state->client_name, - NULL, - &output_token, - NULL, - NULL, - &state->client_creds); - - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - - // Grab the server response to send back to the client - if (output_token.length) - { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Get the user name - maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->username = (char *)malloc(output_token.length + 1); - strncpy(state->username, (char*) output_token.value, output_token.length); - state->username[output_token.length] = 0; - - // Get the target name if no server creds were supplied - if (state->server_creds == GSS_C_NO_CREDENTIAL) - { - gss_name_t target_name = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - set_gss_error(maj_stat, min_stat); - ret = AUTH_GSS_ERROR; - goto end; - } - state->targetname = (char *)malloc(output_token.length + 1); - strncpy(state->targetname, (char*) output_token.value, output_token.length); - state->targetname[output_token.length] = 0; - } - - ret = AUTH_GSS_COMPLETE; - -end: - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - return ret; -} -*/ - -static void set_gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char buf_maj[512]; - char buf_min[512]; - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, sizeof(buf_maj)); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if (!GSS_ERROR(maj_stat)) { - - strncpy(buf_min, (char*) status_string.value , sizeof(buf_min)); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); -} - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - char *buf_maj = calloc(512, sizeof(char)); - char *buf_min = calloc(512, sizeof(char)); - char *message = NULL; - gss_client_response *response = calloc(1, sizeof(gss_client_response)); - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - strncpy(buf_maj, (char*) status_string.value, 512); - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if(!GSS_ERROR(maj_stat)) { - strncpy(buf_min, (char*) status_string.value , 512); - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); - - // Join the strings - message = calloc(1026, 1); - // Join the two messages - sprintf(message, "%s, %s", buf_maj, buf_min); - // Free data - free(buf_min); - free(buf_maj); - // Set the message - response->message = message; - // Return the message - return response; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h deleted file mode 100644 index 58ac0b714..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/kerberosgss.h +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Copyright (c) 2006-2009 Apple Inc. All rights reserved. - * - * 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. - **/ -#ifndef KERBEROS_GSS_H -#define KERBEROS_GSS_H - -#include -#include -#include - -#define krb5_get_err_text(context,code) error_message(code) - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -#define GSS_AUTH_P_NONE 1 -#define GSS_AUTH_P_INTEGRITY 2 -#define GSS_AUTH_P_PRIVACY 4 - -typedef struct { - int return_code; - char *message; -} gss_client_response; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - long int gss_flags; - char* username; - char* response; -} gss_client_state; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_name_t client_name; - gss_cred_id_t server_creds; - gss_cred_id_t client_creds; - char* username; - char* targetname; - char* response; -} gss_server_state; - -// char* server_principal_details(const char* service, const char* hostname); - -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); -gss_client_response *authenticate_gss_client_clean(gss_client_state *state); -gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); -gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); - -int authenticate_gss_server_init(const char* service, gss_server_state* state); -int authenticate_gss_server_clean(gss_server_state *state); -// int authenticate_gss_server_step(gss_server_state *state, const char *challenge); - -gss_client_response *gss_error(OM_uint32 err_maj, OM_uint32 err_min); -#endif diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/sspi.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/sspi.js deleted file mode 100644 index d9120fba3..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/sspi.js +++ /dev/null @@ -1,15 +0,0 @@ -// Load the native SSPI classes -var kerberos = require('../build/Release/kerberos') - , Kerberos = kerberos.Kerberos - , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; -var SSPI = function() { -} - -exports.SSPI = SSPI; -exports.SecurityBuffer = SecurityBuffer; -exports.SecurityBufferDescriptor = SecurityBufferDescriptor; -exports.SecurityCredentials = SecurityCredentials; -exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c deleted file mode 100644 index 502a021c8..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.c +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - unsigned char oval; - - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - int c1, c2, c3, c4; - int vlen = (int)strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - *rlen = 0; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h deleted file mode 100644 index f0e1f0616..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc deleted file mode 100644 index 7fd521b8a..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.cc +++ /dev/null @@ -1,53 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "base64.h" -#include "wrappers/security_buffer.h" -#include "wrappers/security_buffer_descriptor.h" -#include "wrappers/security_context.h" -#include "wrappers/security_credentials.h" - -Persistent Kerberos::constructor_template; - -// VException object (causes throw in calling code) -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -} - -Kerberos::Kerberos() : ObjectWrap() { -} - -void Kerberos::Initialize(v8::Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(Kerberos::New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("Kerberos")); - // Set the symbol - target->ForceSet(String::NewSymbol("Kerberos"), constructor_template->GetFunction()); -} - -Handle Kerberos::New(const Arguments &args) { - // Load the security.dll library - load_library(); - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(args.This()); - return args.This(); -} - -// Exporting function -extern "C" void init(Handle target) { - HandleScope scope; - Kerberos::Initialize(target); - SecurityContext::Initialize(target); - SecurityBuffer::Initialize(target); - SecurityBufferDescriptor::Initialize(target); - SecurityCredentials::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h deleted file mode 100644 index 8443e78ab..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include - -extern "C" { - #include "kerberos_sspi.h" - #include "base64.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Handle target); - - // Method available - static Handle AcquireAlternateCredentials(const Arguments &args); - static Handle PrepareOutboundPackage(const Arguments &args); - static Handle DecryptMessage(const Arguments &args); - static Handle EncryptMessage(const Arguments &args); - static Handle QueryContextAttributes(const Arguments &args); - -private: - static Handle New(const Arguments &args); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - // package info - SecPkgInfo m_PkgInfo; - // context - CtxtHandle m_Context; - // Do we have a context - bool m_HaveContext; - // Attributes - DWORD CtxtAttr; - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c deleted file mode 100644 index d75c9ab0a..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.c +++ /dev/null @@ -1,244 +0,0 @@ -#include "kerberos_sspi.h" -#include -#include - -static HINSTANCE _sspi_security_dll = NULL; -static HINSTANCE _sspi_secur32_dll = NULL; - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { - // Create function pointer instance - encryptMessage_fn pfn_encryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function to library method - pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); - // Check if the we managed to map function pointer - if(!pfn_encryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); -} - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); - #else - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_acquireCredentialsHandle) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Status - status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, - pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry - ); - - // Call the function - return status; -} - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { - // Create function pointer instance - deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); - - // Check if the we managed to map function pointer - if(!pfn_deleteSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_deleteSecurityContext)(phContext); -} - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { - // Create function pointer instance - decryptMessage_fn pfn_decryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); - - // Check if the we managed to map function pointer - if(!pfn_decryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); -} - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, PCtxtHandle phContext, - LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, - PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, - unsigned long * pfContextAttr, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); - #else - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_initializeSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Execute intialize context - status = (*pfn_initializeSecurityContext)( - phCredential, phContext, pszTargetName, fContextReq, - Reserved1, TargetDataRep, pInput, Reserved2, - phNewContext, pOutput, pfContextAttr, ptsExpiry - ); - - // Call the function - return status; -} -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer -) { - // Create function pointer instance - queryContextAttributes_fn pfn_queryContextAttributes = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - #ifdef _UNICODE - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); - #else - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_queryContextAttributes) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_queryContextAttributes)( - phContext, ulAttribute, pBuffer - ); -} - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface() { - INIT_SECURITY_INTERFACE InitSecurityInterface; - PSecurityFunctionTable pSecurityInterface = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return NULL; - - #ifdef _UNICODE - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceW")); - #else - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceA")); - #endif - - if(!InitSecurityInterface) { - printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); - return NULL; - } - - // Use InitSecurityInterface to get the function table. - pSecurityInterface = (*InitSecurityInterface)(); - - if(!pSecurityInterface) { - printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); - return NULL; - } - - return pSecurityInterface; -} - -/** - * Load security.dll dynamically - */ -int load_library() { - DWORD err; - // Load the library - _sspi_security_dll = LoadLibrary("security.dll"); - - // Check if the library loaded - if(_sspi_security_dll == NULL) { - err = GetLastError(); - return err; - } - - // Load the library - _sspi_secur32_dll = LoadLibrary("secur32.dll"); - - // Check if the library loaded - if(_sspi_secur32_dll == NULL) { - err = GetLastError(); - return err; - } - - return 0; -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h deleted file mode 100644 index a3008dc53..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/kerberos_sspi.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef SSPI_C_H -#define SSPI_C_H - -#define SECURITY_WIN32 1 - -#include -#include - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); - -typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, // Name of principal - LPSTR pszPackage, // Name of package - unsigned long fCredentialUse, // Flags indicating use - void * pvLogonId, // Pointer to logon ID - void * pAuthData, // Package specific data - SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func - void * pvGetKeyArgument, // Value to pass to GetKey() - PCredHandle phCredential, // (out) Cred Handle - PTimeStamp ptsExpiry // (out) Lifetime (optional) -); - -typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry - ); - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( - PCtxtHandle phContext // Context to delete -); - -typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( - PCtxtHandle phContext, - PSecBufferDesc pMessage, - unsigned long MessageSeqNo, - unsigned long pfQOP -); - -typedef DWORD (WINAPI *decryptMessage_fn)( - PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, // Cred to base context - PCtxtHandle phContext, // Existing context (OPT) - LPSTR pszTargetName, // Name of target - unsigned long fContextReq, // Context Requirements - unsigned long Reserved1, // Reserved, MBZ - unsigned long TargetDataRep, // Data rep of target - PSecBufferDesc pInput, // Input Buffers - unsigned long Reserved2, // Reserved, MBZ - PCtxtHandle phNewContext, // (out) New Context handle - PSecBufferDesc pOutput, // (inout) Output Buffers - unsigned long * pfContextAttr, // (out) Context attrs - PTimeStamp ptsExpiry // (out) Life span (OPT) -); - -typedef DWORD (WINAPI *initializeSecurityContext_fn)( - PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); - -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, // Context to query - unsigned long ulAttribute, // Attribute to query - void * pBuffer // Buffer for attributes -); - -typedef DWORD (WINAPI *queryContextAttributes_fn)( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface(); - -typedef DWORD (WINAPI *initSecurityInterface_fn) (); - -/** - * Load security.dll dynamically - */ -int load_library(); - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc deleted file mode 100644 index e7a472f67..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h deleted file mode 100644 index f73a4a768..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/worker.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - v8::Persistent callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc deleted file mode 100644 index dd38b5928..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_buffer.h" - -using namespace node; - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -Persistent SecurityBuffer::constructor_template; - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : ObjectWrap() { - this->size = size; - this->data = calloc(size, sizeof(char)); - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : ObjectWrap() { - this->size = size; - this->data = data; - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::~SecurityBuffer() { - free(this->data); -} - -Handle SecurityBuffer::New(const Arguments &args) { - HandleScope scope; - SecurityBuffer *security_obj; - - if(args.Length() != 2) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[0]->IsInt32()) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!args[1]->IsInt32() && !Buffer::HasInstance(args[1])) - return VException("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - // Unpack buffer type - uint32_t buffer_type = args[0]->ToUint32()->Value(); - - // If we have an integer - if(args[1]->IsInt32()) { - security_obj = new SecurityBuffer(buffer_type, args[1]->ToUint32()->Value()); - } else { - // Get the length of the Buffer - size_t length = Buffer::Length(args[1]->ToObject()); - // Allocate space for the internal void data pointer - void *data = calloc(length, sizeof(char)); - // Write the data to out of V8 heap space - memcpy(data, Buffer::Data(args[1]->ToObject()), length); - // Create new SecurityBuffer - security_obj = new SecurityBuffer(buffer_type, length, data); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityBuffer::ToBuffer(const Arguments &args) { - HandleScope scope; - - // Unpack the Security Buffer object - SecurityBuffer *security_obj = ObjectWrap::Unwrap(args.This()); - // Create a Buffer - Buffer *buffer = Buffer::New((char *)security_obj->data, (size_t)security_obj->size); - - // Return the buffer - return scope.Close(buffer->handle_); -} - -void SecurityBuffer::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityBuffer")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer); - - // Set up class - target->Set(String::NewSymbol("SecurityBuffer"), constructor_template->GetFunction()); -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h deleted file mode 100644 index d6a567510..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SECURITY_BUFFER_H -#define SECURITY_BUFFER_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBuffer : public ObjectWrap { - public: - SecurityBuffer(uint32_t security_type, size_t size); - SecurityBuffer(uint32_t security_type, size_t size, void *data); - ~SecurityBuffer(); - - // Internal values - void *data; - size_t size; - uint32_t security_type; - SecBuffer sec_buffer; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static Handle ToBuffer(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static Handle New(const Arguments &args); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js deleted file mode 100644 index 4996163c9..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer.js +++ /dev/null @@ -1,12 +0,0 @@ -var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; - -// Add some attributes -SecurityBufferNative.VERSION = 0; -SecurityBufferNative.EMPTY = 0; -SecurityBufferNative.DATA = 1; -SecurityBufferNative.TOKEN = 2; -SecurityBufferNative.PADDING = 9; -SecurityBufferNative.STREAM = 10; - -// Export the modified class -exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc deleted file mode 100644 index 560ef50cf..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc +++ /dev/null @@ -1,177 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include "security_buffer_descriptor.h" -#include "security_buffer.h" - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -Persistent SecurityBufferDescriptor::constructor_template; - -SecurityBufferDescriptor::SecurityBufferDescriptor() : ObjectWrap() { -} - -SecurityBufferDescriptor::SecurityBufferDescriptor(Persistent arrayObject) : ObjectWrap() { - SecurityBuffer *security_obj = NULL; - // Safe reference to array - this->arrayObject = arrayObject; - - // Unpack the array and ensure we have a valid descriptor - this->secBufferDesc.cBuffers = arrayObject->Length(); - this->secBufferDesc.ulVersion = SECBUFFER_VERSION; - - if(arrayObject->Length() == 1) { - // Unwrap the buffer - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - // Assign the buffer - this->secBufferDesc.pBuffers = &security_obj->sec_buffer; - } else { - this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; - this->secBufferDesc.cBuffers = arrayObject->Length(); - - // Assign the buffers - for(uint32_t i = 0; i < arrayObject->Length(); i++) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); - this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; - this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; - this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; - } - } -} - -SecurityBufferDescriptor::~SecurityBufferDescriptor() { -} - -size_t SecurityBufferDescriptor::bufferSize() { - SecurityBuffer *security_obj = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - return security_obj->size; - } else { - int bytesToAllocate = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return total size - return bytesToAllocate; - } -} - -char *SecurityBufferDescriptor::toBuffer() { - SecurityBuffer *security_obj = NULL; - char *data = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - data = (char *)malloc(security_obj->size * sizeof(char)); - memcpy(data, security_obj->data, security_obj->size); - } else { - size_t bytesToAllocate = this->bufferSize(); - char *data = (char *)calloc(bytesToAllocate, sizeof(char)); - int offset = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); - offset +=this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return the data - return data; - } - - return data; -} - -Handle SecurityBufferDescriptor::New(const Arguments &args) { - HandleScope scope; - SecurityBufferDescriptor *security_obj; - Persistent arrayObject; - - if(args.Length() != 1) - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(!args[0]->IsInt32() && !args[0]->IsArray()) - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(args[0]->IsArray()) { - Handle array = Handle::Cast(args[0]); - // Iterate over all items and ensure we the right type - for(uint32_t i = 0; i < array->Length(); i++) { - if(!SecurityBuffer::HasInstance(array->Get(i))) { - return VException("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - } - } - } - - // We have a single integer - if(args[0]->IsInt32()) { - // Create new SecurityBuffer instance - Local argv[] = {Int32::New(0x02), args[0]}; - Handle security_buffer = SecurityBuffer::constructor_template->GetFunction()->NewInstance(2, argv); - // Create a new array - Local array = Array::New(1); - // Set the first value - array->Set(0, security_buffer); - // Create persistent handle - arrayObject = Persistent::New(array); - // Create descriptor - security_obj = new SecurityBufferDescriptor(arrayObject); - } else { - arrayObject = Persistent::New(Handle::Cast(args[0])); - security_obj = new SecurityBufferDescriptor(arrayObject); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityBufferDescriptor::ToBuffer(const Arguments &args) { - HandleScope scope; - - // Unpack the Security Buffer object - SecurityBufferDescriptor *security_obj = ObjectWrap::Unwrap(args.This()); - - // Get the buffer - char *buffer_data = security_obj->toBuffer(); - size_t buffer_size = security_obj->bufferSize(); - - // Create a Buffer - Buffer *buffer = Buffer::New(buffer_data, buffer_size); - - // Return the buffer - return scope.Close(buffer->handle_); -} - -void SecurityBufferDescriptor::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityBufferDescriptor")); - - // Set up method for the Kerberos instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "toBuffer", ToBuffer); - - target->Set(String::NewSymbol("SecurityBufferDescriptor"), constructor_template->GetFunction()); -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h deleted file mode 100644 index 858863259..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef SECURITY_BUFFER_DESCRIPTOR_H -#define SECURITY_BUFFER_DESCRIPTOR_H - -#include -#include -#include - -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBufferDescriptor : public ObjectWrap { - public: - Persistent arrayObject; - SecBufferDesc secBufferDesc; - - SecurityBufferDescriptor(); - SecurityBufferDescriptor(Persistent arrayObject); - ~SecurityBufferDescriptor(); - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - char *toBuffer(); - size_t bufferSize(); - - // Functions available from V8 - static void Initialize(Handle target); - static Handle ToBuffer(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - static Handle New(const Arguments &args); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js deleted file mode 100644 index 9421392ea..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; -// Export the modified class -exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc deleted file mode 100644 index 8c3691a7e..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.cc +++ /dev/null @@ -1,1211 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_context.h" -#include "security_buffer_descriptor.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -static Handle VExceptionErrNo(const char *msg, const int errorNumber) { - HandleScope scope; - - Local err = Exception::Error(String::New(msg)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(errorNumber)); - return ThrowException(err); -}; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -static void After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - free(worker->parameters); - delete worker; -} - -Persistent SecurityContext::constructor_template; - -SecurityContext::SecurityContext() : ObjectWrap() { -} - -SecurityContext::~SecurityContext() { - if(this->hasContext) { - _sspi_DeleteSecurityContext(&this->m_Context); - } -} - -Handle SecurityContext::New(const Arguments &args) { - HandleScope scope; - - PSecurityFunctionTable pSecurityInterface = NULL; - DWORD dwNumOfPkgs; - SECURITY_STATUS status; - - // Create code object - SecurityContext *security_obj = new SecurityContext(); - // Get security table interface - pSecurityInterface = _ssip_InitSecurityInterface(); - // Call the security interface - status = (*pSecurityInterface->EnumerateSecurityPackages)( - &dwNumOfPkgs, - &security_obj->m_PkgInfo); - if(status != SEC_E_OK) { - printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); - return VException("Failed in retrieving security packages"); - } - - // Wrap it - security_obj->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityContext::InitializeContextSync(const Arguments &args) { - HandleScope scope; - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - BYTE *out_bound_data_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - // Status of operation - SECURITY_STATUS status; - - // We need 3 parameters - if(args.Length() != 3) - return VException("Initialize must be called with either [credential:SecurityCredential, servicePrincipalName:string, input:string]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return VException("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create Security context instance - Local security_context_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = security_context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(input->Utf8Length() > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = decoded_input_str_length; - ib.pvBuffer = decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &security_credentials->m_Credentials - , NULL - , const_cast(service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , input->Utf8Length() > 0 ? &ibd : NULL - , 0 - , &security_context->m_Context - , &obd - , &security_context->CtxtAttr - , &security_context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - security_context->hasContext = true; - security_context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - // Return security context - return scope.Close(security_context_value); -} - -// -// Async InitializeContext -// -typedef struct SecurityContextStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStaticInitializeCall; - -static void _initializeContext(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - BYTE *out_bound_data_str = NULL; - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &call->context->security_credentials->m_Credentials - , NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length > 0 ? &ibd : NULL - , 0 - , &call->context->m_Context - , &obd - , &call->context->CtxtAttr - , &call->context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - call->context->hasContext = true; - call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - - // Set the context - worker->return_code = status; - worker->return_value = call->context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContext(Worker *worker) { - HandleScope scope; - - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::InitializeContext(const Arguments &args) { - HandleScope scope; - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - - // We need 3 parameters - if(args.Length() != 4) - return VException("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(args[0])) - return VException("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a callback - if(!args[3]->IsFunction()) - return VException("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free original allocation - free(input_str); - } - - // Unpack the Security credentials - security_credentials = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create Security context instance - Local security_context_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Build the call function - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[3]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _initializeContext; - worker->mapper = _map_initializeContext; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value - return scope.Close(Undefined()); -} - -Handle SecurityContext::PayloadGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(info.Holder()); - // Return the low bits - return scope.Close(String::New(context->payload)); -} - -Handle SecurityContext::HasContextGetter(Local property, const AccessorInfo& info) { - HandleScope scope; - // Unpack the context object - SecurityContext *context = ObjectWrap::Unwrap(info.Holder()); - // Return the low bits - return scope.Close(Boolean::New(context->hasContext)); -} - -// -// Async InitializeContextStep -// -typedef struct SecurityContextStepStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStepStaticInitializeCall; - -static void _initializeContextStep(Worker *worker) { - // Outbound data array - BYTE *out_bound_data_str = NULL; - // Status of operation - SECURITY_STATUS status; - // Unpack data - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; - SecurityContext *context = call->context; - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &context->security_credentials->m_Credentials - , context->hasContext == true ? &context->m_Context : NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length ? &ibd : NULL - , 0 - , &context->m_Context - , &obd - , &context->CtxtAttr - , &context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(context->payload != NULL) free(context->payload); - context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Handle _map_initializeContextStep(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::InitalizeStep(const Arguments &args) { - HandleScope scope; - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - - // We need 3 parameters - if(args.Length() != 3) - return VException("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return VException("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[2]->IsFunction()) - return VException("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free input string - free(input_str); - } - - // Unwrap the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Create call structure - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _initializeContextStep; - worker->mapper = _map_initializeContextStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::InitalizeStepSync(const Arguments &args) { - HandleScope scope; - - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - BYTE *out_bound_data_str = NULL; - int decoded_input_str_length = NULL; - // Status of operation - SECURITY_STATUS status; - - // We need 3 parameters - if(args.Length() != 2) - return VException("Initialize must be called with [servicePrincipalName:string, input:string]"); - - // Second parameter must be a string - if(!args[0]->IsString()) - return VException("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!args[1]->IsString()) - return VException("Second parameter for Initialize must be a string"); - - // Let's unpack the values - Local service_principal_name = args[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = args[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - } - - // Unpack the long object - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - SecurityCredentials *security_credentials = security_context->security_credentials; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = security_context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(input->Utf8Length() > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = decoded_input_str_length; - ib.pvBuffer = decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &security_credentials->m_Credentials - , security_context->hasContext == true ? &security_context->m_Context : NULL - , const_cast(service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , input->Utf8Length() > 0 ? &ibd : NULL - , 0 - , &security_context->m_Context - , &obd - , &security_context->CtxtAttr - , &security_context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(security_context->payload != NULL) free(security_context->payload); - security_context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async EncryptMessage -// -typedef struct SecurityContextEncryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; - unsigned long flags; -} SecurityContextEncryptMessageCall; - -static void _encryptMessage(Worker *worker) { - SECURITY_STATUS status; - // Unpack call - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; - // Unpack the security context - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_EncryptMessage( - &context->m_Context - , call->flags - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set result - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_encryptMessage(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::EncryptMessage(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 3) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[1]->IsUint32()) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!args[2]->IsFunction()) - return VException("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Create call structure - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - call->flags = (unsigned long)args[1]->ToInteger()->Value(); - - // Callback - Local callback = Local::Cast(args[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _encryptMessage; - worker->mapper = _map_encryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::EncryptMessageSync(const Arguments &args) { - HandleScope scope; - SECURITY_STATUS status; - - if(args.Length() != 2) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - if(!args[1]->IsUint32()) - return VException("EncryptMessageSync takes an instance of SecurityBufferDescriptor and an integer flag"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Let's execute encryption - status = _sspi_EncryptMessage( - &security_context->m_Context - , (unsigned long)args[1]->ToInteger()->Value() - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(security_context->payload != NULL) free(security_context->payload); - // Save the payload - security_context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async DecryptMessage -// -typedef struct SecurityContextDecryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; -} SecurityContextDecryptMessageCall; - -static void _decryptMessage(Worker *worker) { - unsigned long quality = 0; - SECURITY_STATUS status; - - // Unpack parameters - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_DecryptMessage( - &context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set return values - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_decryptMessage(Worker *worker) { - HandleScope scope; - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return scope.Close(context->handle_); -} - -Handle SecurityContext::DecryptMessage(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 2) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!args[1]->IsFunction()) - return VException("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - // Create call structure - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _decryptMessage; - worker->mapper = _map_decryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::DecryptMessageSync(const Arguments &args) { - HandleScope scope; - unsigned long quality = 0; - SECURITY_STATUS status; - - if(args.Length() != 1) - return VException("DecryptMessageSync takes an instance of SecurityBufferDescriptor"); - if(!SecurityBufferDescriptor::HasInstance(args[0])) - return VException("DecryptMessageSync takes an instance of SecurityBufferDescriptor"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = ObjectWrap::Unwrap(args[0]->ToObject()); - - // Let's execute encryption - status = _sspi_DecryptMessage( - &security_context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(security_context->payload != NULL) free(security_context->payload); - // Save the payload - security_context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - return scope.Close(Null()); -} - -// -// Async QueryContextAttributes -// -typedef struct SecurityContextQueryContextAttributesCall { - SecurityContext *context; - uint32_t attribute; -} SecurityContextQueryContextAttributesCall; - -static void _queryContextAttributes(Worker *worker) { - SECURITY_STATUS status; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - - // Allocate some space - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &call->context->m_Context, - call->attribute, - sizes - ); - - if(status == SEC_E_OK) { - worker->return_code = status; - worker->return_value = sizes; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Handle _map_queryContextAttributes(Worker *worker) { - HandleScope scope; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - // Unpack the attribute - uint32_t attribute = call->attribute; - - // Convert data - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; - // Create object - Local value = Object::New(); - value->Set(String::New("maxToken"), Integer::New(sizes->cbMaxToken)); - value->Set(String::New("maxSignature"), Integer::New(sizes->cbMaxSignature)); - value->Set(String::New("blockSize"), Integer::New(sizes->cbBlockSize)); - value->Set(String::New("securityTrailer"), Integer::New(sizes->cbSecurityTrailer)); - return scope.Close(value); - } - - // Return the value - return scope.Close(Null()); -} - -Handle SecurityContext::QueryContextAttributes(const Arguments &args) { - HandleScope scope; - - if(args.Length() != 2) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier and a callback function"); - if(!args[0]->IsInt32()) - return VException("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!args[1]->IsFunction()) - return VException("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - - // Unpack the int value - uint32_t attribute = args[0]->ToInt32()->Value(); - - // Check that we have a supported attribute - if(attribute != SECPKG_ATTR_SIZES) - return VException("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Create call structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); - call->attribute = attribute; - call->context = security_context; - - // Callback - Local callback = Local::Cast(args[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _queryContextAttributes; - worker->mapper = _map_queryContextAttributes; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return undefined - return scope.Close(Undefined()); -} - -Handle SecurityContext::QueryContextAttributesSync(const Arguments &args) { - HandleScope scope; - SECURITY_STATUS status; - - if(args.Length() != 1) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier"); - if(!args[0]->IsInt32()) - return VException("QueryContextAttributesSync method takes a an integer Attribute specifier"); - - // Unpack the security context - SecurityContext *security_context = ObjectWrap::Unwrap(args.This()); - uint32_t attribute = args[0]->ToInt32()->Value(); - - if(attribute != SECPKG_ATTR_SIZES) - return VException("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Check what attribute we are asking for - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes sizes; - - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &security_context->m_Context, - attribute, - &sizes - ); - - if(status == SEC_E_OK) { - Local value = Object::New(); - value->Set(String::New("maxToken"), Integer::New(sizes.cbMaxToken)); - value->Set(String::New("maxSignature"), Integer::New(sizes.cbMaxSignature)); - value->Set(String::New("blockSize"), Integer::New(sizes.cbBlockSize)); - value->Set(String::New("securityTrailer"), Integer::New(sizes.cbSecurityTrailer)); - return scope.Close(value); - } else { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - } - - return scope.Close(Null()); -} - -void SecurityContext::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityContext")); - - // Class methods - NODE_SET_METHOD(constructor_template, "initializeSync", InitializeContextSync); - NODE_SET_METHOD(constructor_template, "initialize", InitializeContext); - - // Set up method for the instance - NODE_SET_PROTOTYPE_METHOD(constructor_template, "initializeSync", InitalizeStepSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "initialize", InitalizeStep); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "decryptMessageSync", DecryptMessageSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "decryptMessage", DecryptMessage); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "queryContextAttributesSync", QueryContextAttributesSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "queryContextAttributes", QueryContextAttributes); - - NODE_SET_PROTOTYPE_METHOD(constructor_template, "encryptMessageSync", EncryptMessageSync); - NODE_SET_PROTOTYPE_METHOD(constructor_template, "encryptMessage", EncryptMessage); - - // Getters for correct serialization of the object - constructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol("payload"), PayloadGetter); - // Getters for correct serialization of the object - constructor_template->InstanceTemplate()->SetAccessor(String::NewSymbol("hasContext"), HasContextGetter); - - // Set template class name - target->Set(String::NewSymbol("SecurityContext"), constructor_template->GetFunction()); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - } - - return pszName; -} - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h deleted file mode 100644 index b0059e39e..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.h +++ /dev/null @@ -1,85 +0,0 @@ -#ifndef SECURITY_CONTEXT_H -#define SECURITY_CONTEXT_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include "security_credentials.h" -#include "../worker.h" - -extern "C" { - #include "../kerberos_sspi.h" - #include "../base64.h" -} - -using namespace v8; -using namespace node; - -class SecurityContext : public ObjectWrap { - public: - SecurityContext(); - ~SecurityContext(); - - // Security info package - PSecPkgInfo m_PkgInfo; - // Do we have a context - bool hasContext; - // Reference to security credentials - SecurityCredentials *security_credentials; - // Security context - CtxtHandle m_Context; - // Attributes - DWORD CtxtAttr; - // Expiry time for ticket - TimeStamp Expiration; - // Payload - char *payload; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - - static Handle InitializeContext(const Arguments &args); - static Handle InitializeContextSync(const Arguments &args); - - static Handle InitalizeStep(const Arguments &args); - static Handle InitalizeStepSync(const Arguments &args); - - static Handle DecryptMessage(const Arguments &args); - static Handle DecryptMessageSync(const Arguments &args); - - static Handle QueryContextAttributesSync(const Arguments &args); - static Handle QueryContextAttributes(const Arguments &args); - - static Handle EncryptMessageSync(const Arguments &args); - static Handle EncryptMessage(const Arguments &args); - - // Payload getter - static Handle PayloadGetter(Local property, const AccessorInfo& info); - // hasContext getter - static Handle HasContextGetter(Local property, const AccessorInfo& info); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static Handle New(const Arguments &args); - // // Handles the uv calls - // static void Process(uv_work_t* work_req); - // // Called after work is done - // static void After(uv_work_t* work_req); -}; - -#endif diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js deleted file mode 100644 index ef04e9274..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_context.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; -// Export the modified class -exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc deleted file mode 100644 index 025238b7c..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc +++ /dev/null @@ -1,468 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_credentials.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -static Handle VException(const char *msg) { - HandleScope scope; - return ThrowException(Exception::Error(String::New(msg))); -}; - -static Handle VExceptionErrNo(const char *msg, const int errorNumber) { - HandleScope scope; - - Local err = Exception::Error(String::New(msg)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(errorNumber)); - return ThrowException(err); -}; - -Persistent SecurityCredentials::constructor_template; - -SecurityCredentials::SecurityCredentials() : ObjectWrap() { -} - -SecurityCredentials::~SecurityCredentials() { -} - -Handle SecurityCredentials::New(const Arguments &args) { - HandleScope scope; - - // Create security credentials instance - SecurityCredentials *security_credentials = new SecurityCredentials(); - // Wrap it - security_credentials->Wrap(args.This()); - // Return the object - return args.This(); -} - -Handle SecurityCredentials::AquireSync(const Arguments &args) { - HandleScope scope; - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Status of operation - SECURITY_STATUS status; - - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(!args[0]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(!args[1]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(args.Length() == 3 && !args[2]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull())) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string]]"); - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if(args.Length() == 4 && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Create Security instance - Local security_credentials_value = constructor_template->GetFunction()->NewInstance(); - - // Unwrap the credentials - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(security_credentials_value); - - // If we have domain string - if(domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(username_str); - - // If we have a password string - if(password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - package_str, - SECPKG_CRED_OUTBOUND, - NULL, - password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - LPSTR err_message = DisplaySECError(status); - - if(err_message != NULL) { - return VExceptionErrNo(err_message, status); - } else { - return VExceptionErrNo("Unknown error", status); - } - } - - // Make object persistent - Persistent persistent = Persistent::New(security_credentials_value); - // Return the object - return scope.Close(persistent); -} - -// Call structs -typedef struct SecurityCredentialCall { - char *package_str; - char *username_str; - char *password_str; - char *domain_str; - SecurityCredentials *credentials; -} SecurityCredentialCall; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authSSPIAquire(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - - // Unpack data - SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; - - // Unwrap the credentials - SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; - - // If we have domain string - if(call->domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); - - // If we have a password string - if(call->password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - call->package_str, - SECPKG_CRED_OUTBOUND, - NULL, - call->password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } else { - worker->return_code = status; - worker->return_value = security_credentials; - } - - // Free up parameter structure - if(call->package_str != NULL) free(call->package_str); - if(call->domain_str != NULL) free(call->domain_str); - if(call->password_str != NULL) free(call->password_str); - if(call->username_str != NULL) free(call->username_str); - free(call); -} - -static Handle _map_authSSPIAquire(Worker *worker) { - HandleScope scope; - - // Unpack the credentials - SecurityCredentials *security_credentials = (SecurityCredentials *)worker->return_value; - // Make object persistent - Persistent persistent = Persistent::New(security_credentials->handle_); - // Return the object - return scope.Close(persistent); -} - -Handle SecurityCredentials::Aquire(const Arguments &args) { - HandleScope scope; - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Unpack the variables - if(args.Length() != 2 && args.Length() != 3 && args.Length() != 4 && args.Length() != 5) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[0]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!args[1]->IsString()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 3 && (!args[2]->IsString() && !args[2]->IsFunction())) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 4 && (!args[3]->IsString() && !args[3]->IsUndefined() && !args[3]->IsNull()) && !args[3]->IsFunction()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(args.Length() == 5 && !args[4]->IsFunction()) - return VException("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - Local callback; - - // Figure out which parameter is the callback - if(args.Length() == 5) { - callback = Local::Cast(args[4]); - } else if(args.Length() == 4) { - callback = Local::Cast(args[3]); - } else if(args.Length() == 3) { - callback = Local::Cast(args[2]); - } - - // Unpack the package - Local package = args[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = args[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(args.Length() == 3 || args.Length() == 4 || args.Length() == 5) { - Local password = args[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if((args.Length() == 4 || args.Length() == 5) && args[3]->IsString()) { - Local domain = args[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Create reference object - Local security_credentials_value = constructor_template->GetFunction()->NewInstance(); - // Unwrap object - SecurityCredentials *security_credentials = ObjectWrap::Unwrap(security_credentials_value); - - // Allocate call structure - SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); - call->domain_str = domain_str; - call->package_str = package_str; - call->password_str = password_str; - call->username_str = username_str; - call->credentials = security_credentials; - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = Persistent::New(callback); - worker->parameters = call; - worker->execute = _authSSPIAquire; - worker->mapper = _map_authSSPIAquire; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); - - // Return the undefined value - return scope.Close(Undefined()); -} - -void SecurityCredentials::Initialize(Handle target) { - // Grab the scope of the call from Node - HandleScope scope; - // Define a new function template - Local t = FunctionTemplate::New(New); - constructor_template = Persistent::New(t); - constructor_template->InstanceTemplate()->SetInternalFieldCount(1); - constructor_template->SetClassName(String::NewSymbol("SecurityCredentials")); - - // Class methods - NODE_SET_METHOD(constructor_template, "aquireSync", AquireSync); - NODE_SET_METHOD(constructor_template, "aquire", Aquire); - - // Set the class on the target module - target->Set(String::NewSymbol("SecurityCredentials"), constructor_template->GetFunction()); - - // Attempt to load the security.dll library - load_library(); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - - } - - return pszName; -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void SecurityCredentials::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void SecurityCredentials::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - v8::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - v8::Local err = v8::Exception::Error(v8::String::New(worker->error_message)); - Local obj = err->ToObject(); - obj->Set(NODE_PSYMBOL("code"), Int32::New(worker->error_code)); - v8::Local args[2] = { err, v8::Local::New(v8::Null()) }; - // Execute the error - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } else { - // // Map the data - v8::Handle result = worker->mapper(worker); - // Set up the callback with a null first - v8::Handle args[2] = { v8::Local::New(v8::Null()), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - v8::TryCatch try_catch; - // Call the callback - worker->callback->Call(v8::Context::GetCurrent()->Global(), ARRAY_SIZE(args), args); - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - node::FatalException(try_catch); - } - } - - // Clean up the memory - worker->callback.Dispose(); - delete worker; -} - diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h deleted file mode 100644 index 10b3edaa3..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.h +++ /dev/null @@ -1,67 +0,0 @@ -#ifndef SECURITY_CREDENTIALS_H -#define SECURITY_CREDENTIALS_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" -} - -// SEC_WINNT_AUTH_IDENTITY makes it unusually hard -// to compile for both Unicode and ansi, so I use this macro: -#ifdef _UNICODE -#define USTR(str) (str) -#else -#define USTR(str) ((unsigned char*)(str)) -#endif - -using namespace v8; -using namespace node; - -class SecurityCredentials : public ObjectWrap { - public: - SecurityCredentials(); - ~SecurityCredentials(); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - - // Has instance check - static inline bool HasInstance(Handle val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return constructor_template->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Handle target); - static Handle AquireSync(const Arguments &args); - static Handle Aquire(const Arguments &args); - - // Constructor used for creating new Long objects from C++ - static Persistent constructor_template; - - private: - // Create a new instance - static Handle New(const Arguments &args); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js deleted file mode 100644 index 4215c9274..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/win32/wrappers/security_credentials.js +++ /dev/null @@ -1,22 +0,0 @@ -var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; - -// Add simple kebros helper -SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { - if(typeof password == 'function') { - callback = password; - password = null; - } else if(typeof domain == 'function') { - callback = domain; - domain = null; - } - - // We are going to use the async version - if(typeof callback == 'function') { - return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); - } else { - return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); - } -} - -// Export the modified class -exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/worker.cc b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/worker.cc deleted file mode 100644 index e7a472f67..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/worker.h b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/worker.h deleted file mode 100644 index c5f86f521..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/lib/worker.h +++ /dev/null @@ -1,39 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - v8::Persistent callback; - // // Arguments - // v8::Persistent arguments; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Handle (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/package.json deleted file mode 100644 index b29cfc2c8..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/package.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "name": "kerberos", - "version": "0.0.3", - "description": "Kerberos library for Node.js", - "main": "index.js", - "scripts": { - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "nodeunit ./test" - }, - "repository": { - "type": "git", - "url": "https://github.com/christkv/kerberos.git" - }, - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "devDependencies": { - "nodeunit": "latest" - }, - "author": { - "name": "Christian Amor Kvalheim" - }, - "license": "Apache 2.0", - "readmeFilename": "README.md", - "gitHead": "bb01d4fe322e022999aca19da564e7d9db59a8ed", - "readme": "kerberos\n========\n\nKerberos library for node.js", - "bugs": { - "url": "https://github.com/christkv/kerberos/issues" - }, - "homepage": "https://github.com/christkv/kerberos", - "_id": "kerberos@0.0.3", - "dist": { - "shasum": "53d6ed947fa0d8306a67680dffb4bd32a51e3839" - }, - "_from": "kerberos@0.0.3", - "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.3.tgz" -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js deleted file mode 100644 index a06c5fdfe..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/kerberos_tests.js +++ /dev/null @@ -1,34 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos object'] = function(test) { - var Kerberos = require('../lib/kerberos.js').Kerberos; - var kerberos = new Kerberos(); - // console.dir(kerberos) - - // Initiate kerberos client - kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - console.log("===================================== authGSSClientInit") - test.equal(null, err); - test.ok(context != null && typeof context == 'object'); - // console.log("===================================== authGSSClientInit") - console.dir(err) - console.dir(context) - // console.dir(typeof result) - - // Perform the first step - kerberos.authGSSClientStep(context, function(err, result) { - console.log("===================================== authGSSClientStep") - console.dir(err) - console.dir(result) - console.dir(context) - - test.done(); - }); - }); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js deleted file mode 100644 index d2f704638..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/kerberos_win32_test.js +++ /dev/null @@ -1,19 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos win32 object'] = function(test) { - var KerberosNative = require('../build/Release/kerberos').Kerberos; - // console.dir(KerberosNative) - var kerberos = new KerberosNative(); - console.log("=========================================== 0") - console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); - console.log("=========================================== 1") - console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); - console.log("=========================================== 2") - test.done(); -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js deleted file mode 100644 index 3531b6bc2..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js +++ /dev/null @@ -1,41 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer Descriptor'] = function(test) { - var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // Create descriptor with single Buffer - var securityDescriptor = new SecurityBufferDescriptor(100); - try { - // Fail to work due to no valid Security Buffer - securityDescriptor = new SecurityBufferDescriptor(["hello"]); - test.ok(false); - } catch(err){} - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - // Should correctly return a buffer - var result = securityDescriptor.toBuffer(); - test.equal(100, result.length); - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - var result = securityDescriptor.toBuffer(); - test.equal("hello world", result.toString()); - - // Test passing in more than one Buffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - var result = securityDescriptor.toBuffer(); - test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js deleted file mode 100644 index b52b9598b..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_buffer_tests.js +++ /dev/null @@ -1,22 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer'] = function(test) { - var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - // Create empty buffer - var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - var buffer = securityBuffer.toBuffer(); - test.equal(100, buffer.length); - - // Access data passed in - var allocated_buffer = new Buffer(256); - securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); - buffer = securityBuffer.toBuffer(); - test.deepEqual(allocated_buffer, buffer); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js deleted file mode 100644 index 775818007..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/node_modules/kerberos/test/win32/security_credentials_tests.js +++ /dev/null @@ -1,55 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a set of security credentials'] = function(test) { - var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; - - // Aquire some credentials - try { - var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); - } catch(err) { - console.dir(err) - test.ok(false); - } - - - - // console.dir(SecurityCredentials); - - // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // // Create descriptor with single Buffer - // var securityDescriptor = new SecurityBufferDescriptor(100); - // try { - // // Fail to work due to no valid Security Buffer - // securityDescriptor = new SecurityBufferDescriptor(["hello"]); - // test.ok(false); - // } catch(err){} - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // // Should correctly return a buffer - // var result = securityDescriptor.toBuffer(); - // test.equal(100, result.length); - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello world", result.toString()); - - // // Test passing in more than one Buffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/package.json b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/package.json deleted file mode 100644 index e8304ffec..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/package.json +++ /dev/null @@ -1,228 +0,0 @@ -{ - "name": "mongodb", - "description": "A node.js driver for MongoDB", - "keywords": [ - "mongodb", - "mongo", - "driver", - "db" - ], - "version": "1.3.19", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [ - { - "name": "Aaron Heckmann" - }, - { - "name": "Christoph Pojer" - }, - { - "name": "Pau Ramon Revilla" - }, - { - "name": "Nathan White" - }, - { - "name": "Emmerman" - }, - { - "name": "Seth LaForge" - }, - { - "name": "Boris Filipov" - }, - { - "name": "Stefan Schärmeli" - }, - { - "name": "Tedde Lundgren" - }, - { - "name": "renctan" - }, - { - "name": "Sergey Ukustov" - }, - { - "name": "Ciaran Jessup" - }, - { - "name": "kuno" - }, - { - "name": "srimonti" - }, - { - "name": "Erik Abele" - }, - { - "name": "Pratik Daga" - }, - { - "name": "Slobodan Utvic" - }, - { - "name": "Kristina Chodorow" - }, - { - "name": "Yonathan Randolph" - }, - { - "name": "Brian Noguchi" - }, - { - "name": "Sam Epstein" - }, - { - "name": "James Harrison Fisher" - }, - { - "name": "Vladimir Dronnikov" - }, - { - "name": "Ben Hockey" - }, - { - "name": "Henrik Johansson" - }, - { - "name": "Simon Weare" - }, - { - "name": "Alex Gorbatchev" - }, - { - "name": "Shimon Doodkin" - }, - { - "name": "Kyle Mueller" - }, - { - "name": "Eran Hammer-Lahav" - }, - { - "name": "Marcin Ciszak" - }, - { - "name": "François de Metz" - }, - { - "name": "Vinay Pulim" - }, - { - "name": "nstielau" - }, - { - "name": "Adam Wiggins" - }, - { - "name": "entrinzikyl" - }, - { - "name": "Jeremy Selier" - }, - { - "name": "Ian Millington" - }, - { - "name": "Public Keating" - }, - { - "name": "andrewjstone" - }, - { - "name": "Christopher Stott" - }, - { - "name": "Corey Jewett" - }, - { - "name": "brettkiefer" - }, - { - "name": "Rob Holland" - }, - { - "name": "Senmiao Liu" - }, - { - "name": "heroic" - }, - { - "name": "gitfy" - }, - { - "name": "Andrew Stone" - }, - { - "name": "John Le Drew" - }, - { - "name": "Lucasfilm Singapore" - }, - { - "name": "Roman Shtylman" - }, - { - "name": "Matt Self" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/mongodb/node-mongodb-native.git" - }, - "bugs": { - "url": "http://github.com/mongodb/node-mongodb-native/issues" - }, - "dependencies": { - "bson": "0.2.2", - "kerberos": "0.0.3" - }, - "devDependencies": { - "dox": "0.2.0", - "uglify-js": "1.2.5", - "ejs": "0.6.1", - "request": "2.12.0", - "nodeunit": "0.7.4", - "markdown": "0.3.1", - "gleak": "0.2.3", - "step": "0.0.5", - "async": "0.1.22", - "integra": "latest", - "optimist": "latest" - }, - "optionalDependencies": { - "kerberos": "0.0.3" - }, - "config": { - "native": false - }, - "main": "./lib/mongodb/index", - "homepage": "http://mongodb.github.com/node-mongodb-native/", - "directories": { - "lib": "./lib/mongodb" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "test": "make test_functional" - }, - "licenses": [ - { - "type": "Apache License, Version 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0" - } - ], - "readme": "Up to date documentation\n========================\n\n[Documentation](http://mongodb.github.com/node-mongodb-native/)\n\nInstall\n=======\n\nTo install the most recent release from npm, run:\n\n npm install mongodb\n\nThat may give you a warning telling you that bugs['web'] should be bugs['url'], it would be safe to ignore it (this has been fixed in the development version)\n\nTo install the latest from the repository, run::\n\n npm install path/to/node-mongodb-native\n\nCommunity\n=========\nCheck out the google group [node-mongodb-native](http://groups.google.com/group/node-mongodb-native) for questions/answers from users of the driver.\n\nLive Examples\n============\n\n\nIntroduction\n============\n\nThis is a node.js driver for MongoDB. It's a port (or close to a port) of the library for ruby at http://github.com/mongodb/mongo-ruby-driver/.\n\nA simple example of inserting a document.\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n var collection = db.collection('test_insert');\n collection.insert({a:2}, function(err, docs) {\n \n collection.count(function(err, count) {\n console.log(format(\"count = %s\", count));\n });\n\n // Locate all the entries using find\n collection.find().toArray(function(err, results) {\n console.dir(results);\n // Let's close the db\n db.close();\n }); \n });\n })\n```\n\nData types\n==========\n\nTo store and retrieve the non-JSON MongoDb primitives ([ObjectID](http://www.mongodb.org/display/DOCS/Object+IDs), Long, Binary, [Timestamp](http://www.mongodb.org/display/DOCS/Timestamp+data+type), [DBRef](http://www.mongodb.org/display/DOCS/Database+References#DatabaseReferences-DBRef), Code).\n\nIn particular, every document has a unique `_id` which can be almost any type, and by default a 12-byte ObjectID is created. ObjectIDs can be represented as 24-digit hexadecimal strings, but you must convert the string back into an ObjectID before you can use it in the database. For example:\n\n```javascript\n // Get the objectID type\n var ObjectID = require('mongodb').ObjectID;\n\n var idString = '4e4e1638c85e808431000003';\n collection.findOne({_id: new ObjectID(idString)}, console.log) // ok\n collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined\n```\n\nHere are the constructors the non-Javascript BSON primitive types:\n\n```javascript\n // Fetch the library\n var mongo = require('mongodb');\n // Create new instances of BSON types\n new mongo.Long(numberString)\n new mongo.ObjectID(hexString)\n new mongo.Timestamp() // the actual unique number is generated on insert.\n new mongo.DBRef(collectionName, id, dbName)\n new mongo.Binary(buffer) // takes a string or Buffer\n new mongo.Code(code, [context])\n new mongo.Symbol(string)\n new mongo.MinKey()\n new mongo.MaxKey()\n new mongo.Double(number)\t// Force double storage\n```\n\nThe C/C++ bson parser/serializer\n--------------------------------\n\nIf you are running a version of this library has the C/C++ parser compiled, to enable the driver to use the C/C++ bson parser pass it the option native_parser:true like below\n\n```javascript\n // using native_parser:\n MongoClient.connect('mongodb://127.0.0.1:27017/test'\n , {db: {native_parser: true}}, function(err, db) {})\n```\n\nThe C++ parser uses the js objects both for serialization and deserialization.\n\nGitHub information\n==================\n\nThe source code is available at http://github.com/mongodb/node-mongodb-native.\nYou can either clone the repository or download a tarball of the latest release.\n\nOnce you have the source you can test the driver by running\n\n $ make test\n\nin the main directory. You will need to have a mongo instance running on localhost for the integration tests to pass.\n\nExamples\n========\n\nFor examples look in the examples/ directory. You can execute the examples using node.\n\n $ cd examples\n $ node queries.js\n\nGridStore\n=========\n\nThe GridStore class allows for storage of binary files in mongoDB using the mongoDB defined files and chunks collection definition.\n\nFor more information have a look at [Gridstore](https://github.com/mongodb/node-mongodb-native/blob/master/docs/gridfs.md)\n\nReplicasets\n===========\nFor more information about how to connect to a replicaset have a look at the extensive documentation [Documentation](http://mongodb.github.com/node-mongodb-native/)\n\nPrimary Key Factories\n---------------------\n\nDefining your own primary key factory allows you to generate your own series of id's\n(this could f.ex be to use something like ISBN numbers). The generated the id needs to be a 12 byte long \"string\".\n\nSimple example below\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n // Custom factory (need to provide a 12 byte array);\n CustomPKFactory = function() {}\n CustomPKFactory.prototype = new Object();\n CustomPKFactory.createPk = function() {\n return new ObjectID(\"aaaaaaaaaaaa\");\n }\n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n db.dropDatabase(function(err, done) {\n \n db.createCollection('test_custom_key', function(err, collection) {\n \n collection.insert({'a':1}, function(err, docs) {\n \n collection.find({'_id':new ObjectID(\"aaaaaaaaaaaa\")}).toArray(function(err, items) {\n console.dir(items);\n // Let's close the db\n db.close();\n });\n });\n });\n });\n });\n```\n\nDocumentation\n=============\n\nIf this document doesn't answer your questions, see the source of\n[Collection](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/collection.js)\nor [Cursor](https://github.com/mongodb/node-mongodb-native/blob/master/lib/mongodb/cursor.js),\nor the documentation at MongoDB for query and update formats.\n\nFind\n----\n\nThe find method is actually a factory method to create\nCursor objects. A Cursor lazily uses the connection the first time\nyou call `nextObject`, `each`, or `toArray`.\n\nThe basic operation on a cursor is the `nextObject` method\nthat fetches the next matching document from the database. The convenience\nmethods `each` and `toArray` call `nextObject` until the cursor is exhausted.\n\nSignatures:\n\n```javascript\n var cursor = collection.find(query, [fields], options);\n cursor.sort(fields).limit(n).skip(m).\n\n cursor.nextObject(function(err, doc) {});\n cursor.each(function(err, doc) {});\n cursor.toArray(function(err, docs) {});\n\n cursor.rewind() // reset the cursor to its initial state.\n```\n\nUseful chainable methods of cursor. These can optionally be options of `find` instead of method calls:\n\n * `.limit(n).skip(m)` to control paging.\n * `.sort(fields)` Order by the given fields. There are several equivalent syntaxes:\n * `.sort({field1: -1, field2: 1})` descending by field1, then ascending by field2.\n * `.sort([['field1', 'desc'], ['field2', 'asc']])` same as above\n * `.sort([['field1', 'desc'], 'field2'])` same as above\n * `.sort('field1')` ascending by field1\n\nOther options of `find`:\n\n* `fields` the fields to fetch (to avoid transferring the entire document)\n* `tailable` if true, makes the cursor [tailable](http://www.mongodb.org/display/DOCS/Tailable+Cursors).\n* `batchSize` The number of the subset of results to request the database\nto return for every request. This should initially be greater than 1 otherwise\nthe database will automatically close the cursor. The batch size can be set to 1\nwith `batchSize(n, function(err){})` after performing the initial query to the database.\n* `hint` See [Optimization: hint](http://www.mongodb.org/display/DOCS/Optimization#Optimization-Hint).\n* `explain` turns this into an explain query. You can also call\n`explain()` on any cursor to fetch the explanation.\n* `snapshot` prevents documents that are updated while the query is active\nfrom being returned multiple times. See more\n[details about query snapshots](http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database).\n* `timeout` if false, asks MongoDb not to time out this cursor after an\ninactivity period.\n\n\nFor information on how to create queries, see the\n[MongoDB section on querying](http://www.mongodb.org/display/DOCS/Querying).\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n var collection = db\n .collection('test')\n .find({})\n .limit(10)\n .toArray(function(err, docs) {\n console.dir(docs);\n });\n });\n```\n\nInsert\n------\n\nSignature:\n\n```javascript\n collection.insert(docs, options, [callback]);\n```\n\nwhere `docs` can be a single document or an array of documents.\n\nUseful options:\n\n* `safe:true` Should always set if you have a callback.\n\nSee also: [MongoDB docs for insert](http://www.mongodb.org/display/DOCS/Inserting).\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n \n db.collection('test').insert({hello: 'world'}, {w:1}, function(err, objects) {\n if (err) console.warn(err.message);\n if (err && err.message.indexOf('E11000 ') !== -1) {\n // this _id was already inserted in the database\n }\n });\n });\n```\n\nNote that there's no reason to pass a callback to the insert or update commands\nunless you use the `safe:true` option. If you don't specify `safe:true`, then\nyour callback will be called immediately.\n\nUpdate; update and insert (upsert)\n----------------------------------\n\nThe update operation will update the first document that matches your query\n(or all documents that match if you use `multi:true`).\nIf `safe:true`, `upsert` is not set, and no documents match, your callback will return 0 documents updated.\n\nSee the [MongoDB docs](http://www.mongodb.org/display/DOCS/Updating) for\nthe modifier (`$inc`, `$set`, `$push`, etc.) formats.\n\nSignature:\n\n```javascript\n collection.update(criteria, objNew, options, [callback]);\n```\n\nUseful options:\n\n* `safe:true` Should always set if you have a callback.\n* `multi:true` If set, all matching documents are updated, not just the first.\n* `upsert:true` Atomically inserts the document if no documents matched.\n\nExample for `update`:\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n\n db.collection('test').update({hi: 'here'}, {$set: {hi: 'there'}}, {w:1}, function(err) {\n if (err) console.warn(err.message);\n else console.log('successfully updated');\n });\n });\n```\n\nFind and modify\n---------------\n\n`findAndModify` is like `update`, but it also gives the updated document to\nyour callback. But there are a few key differences between findAndModify and\nupdate:\n\n 1. The signatures differ.\n 2. You can only findAndModify a single item, not multiple items.\n\nSignature:\n\n```javascript\n collection.findAndModify(query, sort, update, options, callback)\n```\n\nThe sort parameter is used to specify which object to operate on, if more than\none document matches. It takes the same format as the cursor sort (see\nConnection.find above).\n\nSee the\n[MongoDB docs for findAndModify](http://www.mongodb.org/display/DOCS/findAndModify+Command)\nfor more details.\n\nUseful options:\n\n* `remove:true` set to a true to remove the object before returning\n* `new:true` set to true if you want to return the modified object rather than the original. Ignored for remove.\n* `upsert:true` Atomically inserts the document if no documents matched.\n\nExample for `findAndModify`:\n\n```javascript\n var MongoClient = require('mongodb').MongoClient\n , format = require('util').format; \n\n MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {\n if(err) throw err;\n db.collection('test').findAndModify({hello: 'world'}, [['_id','asc']], {$set: {hi: 'there'}}, {}, function(err, object) {\n if (err) console.warn(err.message);\n else console.dir(object); // undefined if no matching object exists.\n });\n });\n```\n\nSave\n----\n\nThe `save` method is a shorthand for upsert if the document contains an\n`_id`, or an insert if there is no `_id`.\n\nSponsors\n========\nJust as Felix Geisendörfer I'm also working on the driver for my own startup and this driver is a big project that also benefits other companies who are using MongoDB.\n\nIf your company could benefit from a even better-engineered node.js mongodb driver I would appreciate any type of sponsorship you may be able to provide. All the sponsors will get a lifetime display in this readme, priority support and help on problems and votes on the roadmap decisions for the driver. If you are interested contact me on [christkv AT g m a i l.com](mailto:christkv@gmail.com) for details.\n\nAnd I'm very thankful for code contributions. If you are interested in working on features please contact me so we can discuss API design and testing.\n\nRelease Notes\n=============\n\nSee HISTORY\n\nCredits\n=======\n\n1. [10gen](http://github.com/mongodb/mongo-ruby-driver/)\n2. [Google Closure Library](http://code.google.com/closure/library/)\n3. [Jonas Raoni Soares Silva](http://jsfromhell.com/classes/binary-parser)\n\nContributors\n============\n\nAaron Heckmann, Christoph Pojer, Pau Ramon Revilla, Nathan White, Emmerman, Seth LaForge, Boris Filipov, Stefan Schärmeli, Tedde Lundgren, renctan, Sergey Ukustov, Ciaran Jessup, kuno, srimonti, Erik Abele, Pratik Daga, Slobodan Utvic, Kristina Chodorow, Yonathan Randolph, Brian Noguchi, Sam Epstein, James Harrison Fisher, Vladimir Dronnikov, Ben Hockey, Henrik Johansson, Simon Weare, Alex Gorbatchev, Shimon Doodkin, Kyle Mueller, Eran Hammer-Lahav, Marcin Ciszak, François de Metz, Vinay Pulim, nstielau, Adam Wiggins, entrinzikyl, Jeremy Selier, Ian Millington, Public Keating, andrewjstone, Christopher Stott, Corey Jewett, brettkiefer, Rob Holland, Senmiao Liu, heroic, gitfy\n\nLicense\n=======\n\n Copyright 2009 - 2012 Christian Amor Kvalheim.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n", - "readmeFilename": "Readme.md", - "_id": "mongodb@1.3.19", - "dist": { - "shasum": "d0a396154c89e1a7137f3c64defee4dae7fa8abc" - }, - "_from": "mongodb@1.3.19", - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-1.3.19.tgz" -} diff --git a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/t.js b/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/t.js deleted file mode 100644 index 77b48b6de..000000000 --- a/node_modules/mongoose/node_modules/mquery/node_modules/mongodb/t.js +++ /dev/null @@ -1,147 +0,0 @@ -var mongodb = require('./lib/mongodb'); - -var mongoserver = new mongodb.Server('localhost', 27017, {}); -var db_conn = new mongodb.Db('test1', mongoserver, { w : 1 }); - -db_conn.on('open', function () { - console.log("this is an open event"); -}); - -db_conn.on('close', function () { - console.log("this is a close event"); -}); - -db_conn.on('reconnect', function () { - console.log("this is a reconnect event"); -}); - -db_conn.open(function (err) { - if (err) throw err; - - var col = db_conn.collection('test'); - - var count = 0; - // Run a simple 'find' query every second - setInterval(function() { - col.findOne(function(err, item) { - if (err) { - return console.log("mongodb query not ok %d", count) - } - console.log("mongodb query ok %d", count); - count++; - }) - if (count == 40) { - db_conn.close(); - } - }, 1000) - console.log('hi'); -}); - -// var MongoClient = require('./lib/mongodb').MongoClient -// , Server = require('./lib/mongodb').Server -// , ReplSet = require('./lib/mongodb').ReplSet -// , Db = require('./lib/mongodb').Db; -// var format = require('util').format; - -// var host = process.env['MONGO_NODE_DRIVER_HOST'] || 'localhost'; -// var port = process.env['MONGO_NODE_DRIVER_PORT'] || 27017; -// var url = format("mongodb://%s:%s,%s:%s,%s:%s/node-mongo-examples" -// , host, port, host, 27018, host, 27019); -// var url = "mongodb://localhost:27017/node-mongo-examples" -// // console.dir(url) - -// // MongoClient.connect(url, function(err, db) { -// // new Db("node-mongo-examples", new Server("localhost", 27017), {w:1}).open(function(err, db) { -// var replSet = new ReplSet([new Server("localhost", 31000) -// , new Server("localhost", 31001) -// , new Server("localhost", 31002)]) -// new Db("node-mongo-examples", replSet, {safe:true}).open(function(err, db) { -// if(err) throw err; -// console.log("=========================== 0") -// db.close(); -// }); - -// // console.log("------------------------- 0") - -// // db.on('error', function(err, db) { -// // console.log("---------------------- GOT ERROR") -// // console.dir(err) -// // db.close(function() { -// // console.log("----------------- error") -// // process.exit(1); -// // }) -// // }); -// // // throw new Error("3") - -// // console.log('connected'); - -// // db.collection('t').findOne(function(err, result) { -// // console.log("33333") -// // throw new Error("3") -// // }) - -// // thisMethodDoesNotExists('foo', 'bar', 123); - -// process.on("uncaughtException", function(err) { -// console.log("######################") -// }) - -// // var now; -// // var obj, i; -// // var count = 10000000; -// // var key = 'key'; - -// // obj = {}; -// // now = Date.now(); -// // for (i = 0; i < count; i++) { -// // obj[key] = 1; -// // obj[key] = null; -// // } -// // console.log('null assignment(`obj[key] = null`):\n %d ms', Date.now() - now); - -// // obj = {}; -// // now = Date.now(); -// // for (i = 0; i < count; i++) { -// // obj[key] = 1; -// // delete obj[key]; -// // } -// // console.log('deleting property(`delete obj[key]`):\n %d ms', Date.now() - now); - -// // // var mongodb = require('./lib/mongodb'); - -// // // // var url = 'mongodb://user:pass@host1,host2,host3/db'; -// // // var url = 'mongodb://127.0.0.1:31000,192.168.2.173:31001,127.0.0.1:31002/test'; -// // // var options = {db: {safe: true}, server: {auto_reconnect: true}}; - -// // // mongodb.connect(url, options, function (err, db) { -// // // if (err) { -// // // console.log(err); -// // // process.exit(1); -// // // } - -// // // db.collection('test', function (err, c) { -// // // if (err) { -// // // console.log(err); -// // // process.exit(2); -// // // } - -// // // var successCount = 0; -// // // var errCount = 0; -// // // var lastErr = null; -// // // setInterval(function () { -// // // c.find({}).limit(100).toArray(function (err, results) { -// // // if (err) { -// // // lastErr = err; -// // // errCount++; -// // // } else { -// // // successCount++; -// // // } -// // // }); -// // // }, 100); - -// // // setInterval(function () { -// // // console.log("STATUS", successCount, errCount); -// // // }, 1000); - -// // // }); -// // // }); \ No newline at end of file diff --git a/node_modules/mongoose/node_modules/mquery/package.json b/node_modules/mongoose/node_modules/mquery/package.json deleted file mode 100644 index c694fdb25..000000000 --- a/node_modules/mongoose/node_modules/mquery/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "mquery", - "version": "0.4.1", - "description": "Expressive query building for MongoDB", - "main": "index.js", - "scripts": { - "test": "make test" - }, - "repository": { - "type": "git", - "url": "git://github.com/aheckmann/mquery.git" - }, - "keywords": [ - "mongodb", - "query", - "builder" - ], - "dependencies": { - "sliced": "0.0.5", - "debug": "0.7.0", - "mongodb": "1.3.19", - "regexp-clone": "0.0.1" - }, - "devDependencies": { - "mocha": "1.9.x" - }, - "bugs": { - "url": "https://github.com/aheckmann/mquery/issues/new" - }, - "author": { - "name": "Aaron Heckmann", - "email": "aaron.heckmann+github@gmail.com" - }, - "license": "MIT", - "homepage": "https://github.com/aheckmann/mquery/", - "readme": "#mquery\n===========\n\n`mquery` is a fluent mongodb query builder designed to run in multiple environments. As of v0.1, `mquery` runs on `Node.js` only with support for the MongoDB shell and browser environments planned for upcoming releases.\n\n##Features\n\n - fluent query builder api\n - custom base query support\n - MongoDB 2.4 geoJSON support\n - method + option combinations validation\n - node.js driver compatibility\n - environment detection\n - [debug](https://github.com/visionmedia/debug) support\n - separated collection implementations for maximum flexibility\n\n[![Build Status](https://travis-ci.org/aheckmann/mquery.png)](https://travis-ci.org/aheckmann/mquery)\n\n##Use\n\n```js\nrequire('mongodb').connect(uri, function (err, db) {\n if (err) return handleError(err);\n\n // get a collection\n var collection = db.collection('artists');\n\n // pass it to the constructor\n mquery(collection).find({..}, callback);\n\n // or pass it to the collection method\n mquery().find({..}).collection(collection).exec(callback)\n\n // or better yet, create a custom query constructor that has it always set\n var Artist = mquery(collection).toConstructor();\n Artist().find(..).where(..).exec(callback)\n})\n```\n\n`mquery` requires a collection object to work with. In the example above we just pass the collection object created using the official [MongoDB driver](https://github.com/mongodb/node-mongodb-native).\n\n\n##Fluent API\n\n###find()\n\nDeclares this query a _find_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.\n\n```js\nmquery().find()\nmquery().find(match)\nmquery().find(callback)\nmquery().find(match, function (err, docs) {\n assert(Array.isArray(docs));\n})\n```\n\n###findOne()\n\nDeclares this query a _findOne_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.\n\n```js\nmquery().findOne()\nmquery().findOne(match)\nmquery().findOne(callback)\nmquery().findOne(match, function (err, doc) {\n if (doc) {\n // the document may not be found\n console.log(doc);\n }\n})\n```\n\n###count()\n\nDeclares this query a _count_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.\n\n```js\nmquery().count()\nmquery().count(match)\nmquery().count(callback)\nmquery().count(match, function (err, number){\n console.log('we found %d matching documents', number);\n})\n```\n\n###remove()\n\nDeclares this query a _remove_ query. Optionally pass a match clause and / or callback. If a callback is passed the query is executed.\n\n```js\nmquery().remove()\nmquery().remove(match)\nmquery().remove(callback)\nmquery().remove(match, function (err){})\n```\n\n###update()\n\nDeclares this query an _update_ query. Optionally pass an update document, match clause, options or callback. If a callback is passed, the query is executed. To force execution without passing a callback, run `update(true)`.\n\n```js\nmquery().update()\nmquery().update(match, updateDocument)\nmquery().update(match, updateDocument, options)\n\n// the following all execute the command\nmquery().update(callback)\nmquery().update({$set: updateDocument, callback)\nmquery().update(match, updateDocument, callback)\nmquery().update(match, updateDocument, options, function (err, result){})\nmquery().update(true) // executes (unsafe write)\n```\n\n#####the update document\n\nAll paths passed that are not `$atomic` operations will become `$set` ops. For example:\n\n```js\nmquery(collection).where({ _id: id }).update({ title: 'words' }, callback)\n```\n\nbecomes\n\n```js\ncollection.update({ _id: id }, { $set: { title: 'words' }}, callback)\n```\n\nThis behavior can be overridden using the `overwrite` option (see below).\n\n#####options\n\nOptions are passed to the `setOptions()` method.\n\n- overwrite\n\nPassing an empty object `{ }` as the update document will result in a no-op unless the `overwrite` option is passed. Without the `overwrite` option, the update operation will be ignored and the callback executed without sending the command to MongoDB to prevent accidently overwritting documents in the collection.\n\n```js\nvar q = mquery(collection).where({ _id: id }).setOptions({ overwrite: true });\nq.update({ }, callback); // overwrite with an empty doc\n```\n\nThe `overwrite` option isn't just for empty objects, it also provides a means to override the default `$set` conversion and send the update document as is.\n\n```js\n// create a base query\nvar base = mquery({ _id: 108 }).collection(collection).toConstructor();\n\nbase().findOne(function (err, doc) {\n console.log(doc); // { _id: 108, name: 'cajon' })\n\n base().setOptions({ overwrite: true }).update({ changed: true }, function (err) {\n base.findOne(function (err, doc) {\n console.log(doc); // { _id: 108, changed: true }) - the doc was overwritten\n });\n });\n})\n```\n\n- multi\n\nUpdates only modify a single document by default. To update multiple documents, set the `multi` option to `true`.\n\n```js\nmquery()\n .collection(coll)\n .update({ name: /^match/ }, { $addToSet: { arr: 4 }}, { multi: true }, callback)\n\n// another way of doing it\nmquery({ name: /^match/ })\n .collection(coll)\n .setOptions({ multi: true })\n .update({ $addToSet: { arr: 4 }}, callback)\n\n// update multiple documents with an empty doc\nvar q = mquery(collection).where({ name: /^match/ });\nq.setOptions({ multi: true, overwrite: true })\nq.update({ });\nq.update(function (err, result) {\n console.log(arguments);\n});\n```\n\n###findOneAndUpdate()\n\nDeclares this query a _findAndModify_ with update query. Optionally pass a match clause, update document, options, or callback. If a callback is passed, the query is executed.\n\nWhen executed, the first matching document (if found) is modified according to the update document and passed back to the callback.\n\n#####options\n\nOptions are passed to the `setOptions()` method.\n\n- `new`: boolean - true to return the modified document rather than the original. defaults to true\n- `upsert`: boolean - creates the object if it doesn't exist. defaults to false\n- `sort`: if multiple docs are found by the match condition, sets the sort order to choose which doc to update\n\n```js\nquery.findOneAndUpdate()\nquery.findOneAndUpdate(updateDocument)\nquery.findOneAndUpdate(match, updateDocument)\nquery.findOneAndUpdate(match, updateDocument, options)\n\n// the following all execute the command\nquery.findOneAndUpdate(callback)\nquery.findOneAndUpdate(updateDocument, callback)\nquery.findOneAndUpdate(match, updateDocument, callback)\nquery.findOneAndUpdate(match, updateDocument, options, function (err, doc) {\n if (doc) {\n // the document may not be found\n console.log(doc);\n }\n})\n ```\n\n###findOneAndRemove()\n\nDeclares this query a _findAndModify_ with remove query. Optionally pass a match clause, options, or callback. If a callback is passed, the query is executed.\n\nWhen executed, the first matching document (if found) is modified according to the update document, removed from the collection and passed to the callback.\n\n#####options\n\nOptions are passed to the `setOptions()` method.\n\n- `sort`: if multiple docs are found by the condition, sets the sort order to choose which doc to modify and remove\n\n```js\nA.where().findOneAndRemove()\nA.where().findOneAndRemove(match)\nA.where().findOneAndRemove(match, options)\n\n// the following all execute the command\nA.where().findOneAndRemove(callback)\nA.where().findOneAndRemove(match, callback)\nA.where().findOneAndRemove(match, options, function (err, doc) {\n if (doc) {\n // the document may not be found\n console.log(doc);\n }\n})\n ```\n\n###distinct()\n\nDeclares this query a _distinct_ query. Optionally pass the distinct field, a match clause or callback. If a callback is passed the query is executed.\n\n```js\nmquery().distinct()\nmquery().distinct(match)\nmquery().distinct(match, field)\nmquery().distinct(field)\n\n// the following all execute the command\nmquery().distinct(callback)\nmquery().distinct(field, callback)\nmquery().distinct(match, callback)\nmquery().distinct(match, field, function (err, result) {\n console.log(result);\n})\n```\n\n###exec()\n\nExecutes the query.\n\n```js\nmquery().findOne().where('route').intersects(polygon).exec(function (err, docs){})\n```\n\n-------------\n\n###all()\n\nSpecifies an `$all` query condition\n\n```js\nmquery().where('permission').all(['read', 'write'])\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/all/)\n\n###and()\n\nSpecifies arguments for an `$and` condition\n\n```js\nmquery().and([{ color: 'green' }, { status: 'ok' }])\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/and/)\n\n###box()\n\nSpecifies a `$box` condition\n\n```js\nvar lowerLeft = [40.73083, -73.99756]\nvar upperRight= [40.741404, -73.988135]\n\nmquery().where('location').within().box(lowerLeft, upperRight)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/box/)\n\n###circle()\n\nSpecifies a `$center` or `$centerSphere` condition.\n\n```js\nvar area = { center: [50, 50], radius: 10, unique: true }\nquery.where('loc').within().circle(area)\nquery.circle('loc', area);\n\n// for spherical calculations\nvar area = { center: [50, 50], radius: 10, unique: true, spherical: true }\nquery.where('loc').within().circle(area)\nquery.circle('loc', area);\n```\n\n- [MongoDB Documentation - center](http://docs.mongodb.org/manual/reference/operator/center/)\n- [MongoDB Documentation - centerSphere](http://docs.mongodb.org/manual/reference/operator/centerSphere/)\n\n###elemMatch()\n\nSpecifies an `$elemMatch` condition\n\n```js\nquery.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})\n\nquery.elemMatch('comment', function (elem) {\n elem.where('author').equals('autobot');\n elem.where('votes').gte(5);\n})\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/elemMatch/)\n\n###equals()\n\nSpecifies the complementary comparison value for the path specified with `where()`.\n\n```js\nmquery().where('age').equals(49);\n\n// is the same as\n\nmquery().where({ 'age': 49 });\n```\n\n###exists()\n\nSpecifies an `$exists` condition\n\n```js\n// { name: { $exists: true }}\nmquery().where('name').exists()\nmquery().where('name').exists(true)\nmquery().exists('name')\n\n// { name: { $exists: false }}\nmquery().where('name').exists(false);\nmquery().exists('name', false);\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/exists/)\n\n###geometry()\n\nSpecifies a `$geometry` condition\n\n```js\nvar polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]\nquery.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })\n\n// or\nvar polyB = [[ 0, 0 ], [ 1, 1 ]]\nquery.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })\n\n// or\nvar polyC = [ 0, 0 ]\nquery.where('loc').within().geometry({ type: 'Point', coordinates: polyC })\n\n// or\nquery.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })\n\n// or\nquery.where('loc').near().geometry({ type: 'Point', coordinates: [3,5] })\n```\n\n`geometry()` **must** come after `intersects()`, `within()`, or `near()`.\n\nThe `object` argument must contain `type` and `coordinates` properties.\n\n- type `String`\n- coordinates `Array`\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geometry/)\n\n###gt()\n\nSpecifies a `$gt` query condition.\n\n```js\nmquery().where('clicks').gt(999)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gt/)\n\n###gte()\n\nSpecifies a `$gte` query condition.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/gte/)\n\n```js\nmquery().where('clicks').gte(1000)\n```\n\n###in()\n\nSpecifies an `$in` query condition.\n\n```js\nmquery().where('author_id').in([3, 48901, 761])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/in/)\n\n###intersects()\n\nDeclares an `$geoIntersects` query for `geometry()`.\n\n```js\nquery.where('path').intersects().geometry({\n type: 'LineString'\n , coordinates: [[180.0, 11.0], [180, 9.0]]\n})\n\n// geometry arguments are supported\nquery.where('path').intersects({\n type: 'LineString'\n , coordinates: [[180.0, 11.0], [180, 9.0]]\n})\n```\n\n**Must** be used after `where()`.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoIntersects/)\n\n###lt()\n\nSpecifies a `$lt` query condition.\n\n```js\nmquery().where('clicks').lt(50)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lt/)\n\n###lte()\n\nSpecifies a `$lte` query condition.\n\n```js\nmquery().where('clicks').lte(49)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/lte/)\n\n###maxDistance()\n\nSpecifies a `$maxDistance` query condition.\n\n```js\nmquery().where('location').near({ center: [139, 74.3] }).maxDistance(5)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/maxDistance/)\n\n###mod()\n\nSpecifies a `$mod` condition\n\n```js\nmquery().where('count').mod(2, 0)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/mod/)\n\n###ne()\n\nSpecifies a `$ne` query condition.\n\n```js\nmquery().where('status').ne('ok')\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/ne/)\n\n###nin()\n\nSpecifies an `$nin` query condition.\n\n```js\nmquery().where('author_id').nin([3, 48901, 761])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nin/)\n\n###nor()\n\nSpecifies arguments for an `$nor` condition.\n\n```js\nmquery().nor([{ color: 'green' }, { status: 'ok' }])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/nor/)\n\n###near()\n\nSpecifies arguments for a `$near` or `$nearSphere` condition.\n\nThese operators return documents sorted by distance.\n\n####Example\n\n```js\nquery.where('loc').near({ center: [10, 10] });\nquery.where('loc').near({ center: [10, 10], maxDistance: 5 });\nquery.near('loc', { center: [10, 10], maxDistance: 5 });\n\n// GeoJSON\nquery.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }});\nquery.where('loc').near({ center: { type: 'Point', coordinates: [10, 10] }, maxDistance: 5, spherical: true });\nquery.where('loc').near().geometry({ type: 'Point', coordinates: [10, 10] });\n\n// For a $nearSphere condition, pass the `spherical` option.\nquery.near({ center: [10, 10], maxDistance: 5, spherical: true });\n```\n\n[MongoDB Documentation](http://www.mongodb.org/display/DOCS/Geospatial+Indexing)\n\n###or()\n\nSpecifies arguments for an `$or` condition.\n\n```js\nmquery().or([{ color: 'red' }, { status: 'emergency' }])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/or/)\n\n###polygon()\n\nSpecifies a `$polygon` condition\n\n```js\nmquery().where('loc').within().polygon([10,20], [13, 25], [7,15])\nmquery().polygon('loc', [10,20], [13, 25], [7,15])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/polygon/)\n\n###regex()\n\nSpecifies a `$regex` query condition.\n\n```js\nmquery().where('name').regex(/^sixstepsrecords/)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/regex/)\n\n###select()\n\nSpecifies which document fields to include or exclude\n\n```js\n// 1 means include, 0 means exclude\nmquery().select({ name: 1, address: 1, _id: 0 })\n\n// or\n\nmquery().select('name address -_id')\n```\n\n#####String syntax\n\nWhen passing a string, prefixing a path with `-` will flag that path as excluded. When a path does not have the `-` prefix, it is included.\n\n```js\n// include a and b, exclude c\nquery.select('a b -c');\n\n// or you may use object notation, useful when\n// you have keys already prefixed with a \"-\"\nquery.select({a: 1, b: 1, c: 0});\n```\n\n_Cannot be used with `distinct()`._\n\n###selected()\n\nDetermines if the query has selected any fields.\n\n```js\nvar query = mquery();\nquery.selected() // false\nquery.select('-name');\nquery.selected() // true\n```\n\n###selectedInclusively()\n\nDetermines if the query has selected any fields inclusively.\n\n```js\nvar query = mquery().select('name');\nquery.selectedInclusively() // true\n\nvar query = mquery();\nquery.selected() // false\nquery.select('-name');\nquery.selectedInclusively() // false\nquery.selectedExclusively() // true\n```\n\n###selectedExclusively()\n\nDetermines if the query has selected any fields exclusively.\n\n```js\nvar query = mquery().select('-name');\nquery.selectedExclusively() // true\n\nvar query = mquery();\nquery.selected() // false\nquery.select('name');\nquery.selectedExclusively() // false\nquery.selectedInclusively() // true\n```\n\n###size()\n\nSpecifies a `$size` query condition.\n\n```js\nmquery().where('someArray').size(6)\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/size/)\n\n###slice()\n\nSpecifies a `$slice` projection for a `path`\n\n```js\nmquery().where('comments').slice(5)\nmquery().where('comments').slice(-5)\nmquery().where('comments').slice([-10, 5])\n```\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/projection/slice/)\n\n###within()\n\nSets a `$geoWithin` or `$within` argument for geo-spatial queries.\n\n```js\nmquery().within().box()\nmquery().within().circle()\nmquery().within().geometry()\n\nmquery().where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });\nmquery().where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });\nmquery().where('loc').within({ polygon: [[],[],[],[]] });\n\nmquery().where('loc').within([], [], []) // polygon\nmquery().where('loc').within([], []) // box\nmquery().where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry\n```\n\nAs of mquery 2.0, `$geoWithin` is used by default. This impacts you if running MongoDB < 2.4. To alter this behavior, see [mquery.use$geoWithin](#mqueryusegeowithin).\n\n**Must** be used after `where()`.\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/reference/operator/geoWithin/)\n\n###where()\n\nSpecifies a `path` for use with chaining\n\n```js\n// instead of writing:\nmquery().find({age: {$gte: 21, $lte: 65}});\n\n// we can instead write:\nmquery().where('age').gte(21).lte(65);\n\n// passing query conditions is permitted too\nmquery().find().where({ name: 'vonderful' })\n\n// chaining\nmquery()\n.where('age').gte(21).lte(65)\n.where({ 'name': /^vonderful/i })\n.where('friends').slice(10)\n.exec(callback)\n```\n\n###$where()\n\nSpecifies a `$where` condition.\n\nUse `$where` when you need to select documents using a JavaScript expression.\n\n```js\nquery.$where('this.comments.length > 10 || this.name.length > 5').exec(callback)\n\nquery.$where(function () {\n return this.comments.length > 10 || this.name.length > 5;\n})\n```\n\nOnly use `$where` when you have a condition that cannot be met using other MongoDB operators like `$lt`. Be sure to read about all of [its caveats](http://docs.mongodb.org/manual/reference/operator/where/) before using.\n\n-----------\n\n###batchSize()\n\nSpecifies the batchSize option.\n\n```js\nquery.batchSize(100)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.batchSize/)\n\n###comment()\n\nSpecifies the comment option.\n\n```js\nquery.comment('login query');\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/)\n\n###hint()\n\nSets query hints.\n\n```js\nmquery().hint({ indexA: 1, indexB: -1 })\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/hint/)\n\n###limit()\n\nSpecifies the limit option.\n\n```js\nquery.limit(20)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.limit/)\n\n###maxScan()\n\nSpecifies the maxScan option.\n\n```js\nquery.maxScan(100)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/maxScan/)\n\n###skip()\n\nSpecifies the skip option.\n\n```js\nquery.skip(100).limit(20)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.skip/)\n\n###sort()\n\nSets the query sort order.\n\nIf an object is passed, key values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`.\n\nIf a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with `-` which will be treated as descending.\n\n```js\n// these are equivalent\nquery.sort({ field: 'asc', test: -1 });\nquery.sort('field -test');\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/cursor.sort/)\n\n###read()\n\nSets the readPreference option for the query.\n\n```js\nmquery().read('primary')\nmquery().read('p') // same as primary\n\nmquery().read('primaryPreferred')\nmquery().read('pp') // same as primaryPreferred\n\nmquery().read('secondary')\nmquery().read('s') // same as secondary\n\nmquery().read('secondaryPreferred')\nmquery().read('sp') // same as secondaryPreferred\n\nmquery().read('nearest')\nmquery().read('n') // same as nearest\n\n// specifying tags\nmquery().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])\n```\n\n#####Preferences:\n\n- `primary` - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.\n- `secondary` - Read from secondary if available, otherwise error.\n- `primaryPreferred` - Read from primary if available, otherwise a secondary.\n- `secondaryPreferred` - Read from a secondary if available, otherwise read from the primary.\n- `nearest` - All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.\n\nAliases\n\n- `p` primary\n- `pp` primaryPreferred\n- `s` secondary\n- `sp` secondaryPreferred\n- `n` nearest\n\nRead more about how to use read preferrences [here](http://docs.mongodb.org/manual/applications/replication/#read-preference) and [here](http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences).\n\n###slaveOk()\n\nSets the slaveOk option. `true` allows reading from secondaries.\n\n**deprecated** use [read()](#read) preferences instead if on mongodb >= 2.2\n\n```js\nquery.slaveOk() // true\nquery.slaveOk(true)\nquery.slaveOk(false)\n```\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/method/rs.slaveOk/)\n\n###snapshot()\n\nSpecifies this query as a snapshot query.\n\n```js\nmquery().snapshot() // true\nmquery().snapshot(true)\nmquery().snapshot(false)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB documentation](http://docs.mongodb.org/manual/reference/operator/snapshot/)\n\n###tailable()\n\nSets tailable option.\n\n```js\nmquery().tailable() <== true\nmquery().tailable(true)\nmquery().tailable(false)\n```\n\n_Cannot be used with `distinct()`._\n\n[MongoDB Documentation](http://docs.mongodb.org/manual/tutorial/create-tailable-cursor/)\n\n##Helpers\n\n###collection()\n\nSets the querys collection.\n\n```js\nmquery().collection(aCollection)\n```\n\n\n###merge(object)\n\nMerges other mquery or match condition objects into this one. When an muery instance is passed, its match conditions, field selection and options are merged.\n\n```js\nvar drum = mquery({ type: 'drum' }).collection(instruments);\nvar redDrum = mqery({ color: 'red' }).merge(drum);\nredDrum.count(function (err, n) {\n console.log('there are %d red drums', n);\n})\n```\n\nInternally uses `mquery.canMerge` to determine validity.\n\n###setOptions(options)\n\nSets query options.\n\n```js\nmquery().setOptions({ collection: coll, limit: 20 })\n```\n\n#####options\n\n- [tailable](#tailable) *\n- [sort](#sort) *\n- [limit](#limit) *\n- [skip](#skip) *\n- [maxScan](#maxScan) *\n- [batchSize](#batchSize) *\n- [comment](#comment) *\n- [snapshot](#snapshot) *\n- [hint](#hint) *\n- [slaveOk](#slaveOk) *\n- [safe](http://docs.mongodb.org/manual/reference/write-concern/): Boolean - passed through to the collection. Setting to `true` is equivalent to `{ w: 1 }`\n- [collection](#collection): the collection to query against\n\n_* denotes a query helper method is also available_\n\n###mquery.canMerge(conditions)\n\nDetermines if `conditions` can be merged using `mquery().merge()`.\n\n```js\nvar query = mquery({ type: 'drum' });\nvar okToMerge = mquery.canMerge(anObject)\nif (okToMerge) {\n query.merge(anObject);\n}\n```\n\n##mquery.use$geoWithin\n\nMongoDB 2.4 introduced the `$geoWithin` operator which replaces and is 100% backward compatible with `$within`. As of mquery 0.2, we default to using `$geoWithin` for all `within()` calls.\n\nIf you are running MongoDB < 2.4 this will be problematic. To force `mquery` to be backward compatible and always use `$within`, set the `mquery.use$geoWithin` flag to `false`.\n\n```js\nmquery.use$geoWithin = false;\n```\n\n##Custom Base Queries\n\nOften times we want custom base queries that encapsulate predefined criteria. With `mquery` this is easy. First create the query you want to reuse and call its `toConstructor()` method which returns a new subclass of `mquery` that retains all options and criteria of the original.\n\n```js\nvar greatMovies = mquery(movieCollection).where('rating').gte(4.5).toConstructor();\n\n// use it!\ngreatMovies().count(function (err, n) {\n console.log('There are %d great movies', n);\n});\n\ngreatMovies().where({ name: /^Life/ }).select('name').find(function (err, docs) {\n console.log(docs);\n});\n```\n\n##Validation\n\nMethod and options combinations are checked for validity at runtime to prevent creation of invalid query constructs. For example, a `distinct` query does not support specifying options like `hint` or field selection. In this case an error will be thrown so you can catch these mistakes in development.\n\n##Debug support\n\nDebug mode is provided through the use of the [debug](https://github.com/visionmedia/debug) module. To enable:\n\n DEBUG=mquery node yourprogram.js\n\nRead the debug module documentation for more details.\n\n##Future goals\n\n - mongo shell compatibility\n - browser compatibility\n - mongoose compatibility\n\n## Installation\n\n $ npm install mquery\n\n## License\n\n[MIT](https://github.com/aheckmann/mquery/blob/master/LICENSE)\n\n", - "readmeFilename": "README.md", - "_id": "mquery@0.4.1", - "dist": { - "shasum": "1488e7f806df9bce9536756ec9543e7afa060fee" - }, - "_from": "mquery@0.4.1", - "_resolved": "https://registry.npmjs.org/mquery/-/mquery-0.4.1.tgz" -} diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/browser.js b/node_modules/mongoose/node_modules/mquery/test/collection/browser.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js b/node_modules/mongoose/node_modules/mquery/test/collection/mongo.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/node_modules/mongoose/node_modules/mquery/test/collection/node.js b/node_modules/mongoose/node_modules/mquery/test/collection/node.js deleted file mode 100644 index 43f446edb..000000000 --- a/node_modules/mongoose/node_modules/mquery/test/collection/node.js +++ /dev/null @@ -1,29 +0,0 @@ - -var assert = require('assert') -var slice = require('sliced') -var mongo = require('mongodb') -var utils = require('../../').utils; - -var uri = process.env.MQUERY_URI || 'mongodb://localhost/mquery'; -var db; - -exports.getCollection = function (cb) { - mongo.Db.connect(uri, function (err, db_) { - assert.ifError(err); - db = db_; - - var collection = db.collection('stuff'); - collection.opts.safe = true; - - // clean test db before starting - db.dropDatabase(function () { - cb(null, collection); - }); - }) -} - -exports.dropCollection = function (cb) { - db.dropDatabase(function () { - db.close(cb); - }) -} diff --git a/node_modules/mongoose/node_modules/mquery/test/env.js b/node_modules/mongoose/node_modules/mquery/test/env.js deleted file mode 100644 index 9b9b80b4c..000000000 --- a/node_modules/mongoose/node_modules/mquery/test/env.js +++ /dev/null @@ -1,20 +0,0 @@ - -var assert = require('assert') -var env = require('../').env; - -console.log('environment: %s', env.type); - -var col; -switch (env.type) { - case 'node': - col = require('./collection/node'); - break; - case 'mongo': - col = require('./collection/mongo'); - case 'browser': - col = require('./collection/browser'); - default: - throw new Error('missing collection implementation for environment: ' + env.type); -} - -module.exports = exports = col; diff --git a/node_modules/mongoose/node_modules/mquery/test/index.js b/node_modules/mongoose/node_modules/mquery/test/index.js deleted file mode 100644 index 9d068b37e..000000000 --- a/node_modules/mongoose/node_modules/mquery/test/index.js +++ /dev/null @@ -1,2643 +0,0 @@ - -var mquery = require('../') -var mongo = require('mongodb') -var assert = require('assert') -var slice = require('sliced') - -describe('mquery', function(){ - var col; - - before(function(done){ - // get the env specific collection interface - require('./env').getCollection(function (err, collection) { - assert.ifError(err); - col = collection; - done(); - }); - }) - - after(function(done){ - require('./env').dropCollection(done); - }) - - describe('mquery', function(){ - it('is a function', function(){ - assert.equal('function', typeof mquery); - }) - it('creates instances with the `new` keyword', function(){ - assert.ok(mquery() instanceof mquery); - }) - describe('defaults', function(){ - it('are set', function(){ - var m = mquery(); - assert.strictEqual(undefined, m.op); - assert.deepEqual({}, m.options); - }) - }) - describe('criteria', function(){ - it('if collection-like is used as collection', function(){ - var m = mquery(col); - assert.equal(col, m._collection.collection); - }) - it('non-collection-like is used as criteria', function(){ - var m = mquery({ works: true }); - assert.ok(!m._collection); - assert.deepEqual({ works: true }, m._conditions); - }) - }) - describe('options', function(){ - it('are merged when passed', function(){ - var m = mquery(col, { safe: true }); - assert.deepEqual({ safe: true }, m.options); - var m = mquery({ name: 'mquery' }, { safe: true }); - assert.deepEqual({ safe: true }, m.options); - }) - }) - }) - - describe('toConstructor', function(){ - it('creates subclasses of mquery', function(){ - var opts = { safe: { w: 'majority' }, readPreference: 'p' }; - var match = { name: 'test', count: { $gt: 101 }}; - var select = { name: 1, count: 0 } - var update = { $set: { x: true }}; - var path = 'street'; - - var q = mquery().setOptions(opts); - q.where(match); - q.select(select); - q.update(update); - q.where(path); - q.find(); - - var M = q.toConstructor(); - var m = M(); - - assert.ok(m instanceof mquery); - assert.deepEqual(opts, m.options); - assert.deepEqual(match, m._conditions); - assert.deepEqual(select, m._fields); - assert.deepEqual(update, m._update); - assert.equal(path, m._path); - assert.equal('find', m.op); - }) - }) - - describe('setOptions', function(){ - it('calls associated methods', function(){ - var m = mquery(); - assert.equal(m._collection, null); - m.setOptions({ collection: col }); - assert.equal(m._collection.collection, col); - }) - it('directly sets option when no method exists', function(){ - var m = mquery(); - assert.equal(m.options.woot, null); - m.setOptions({ woot: 'yay' }); - assert.equal(m.options.woot, 'yay'); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.setOptions(); - assert.equal(m, n); - var n = m.setOptions({ x: 1 }); - assert.equal(m, n); - }) - }) - - describe('collection', function(){ - it('sets the _collection', function(){ - var m = mquery(); - m.collection(col); - assert.equal(m._collection.collection, col); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.collection(col); - assert.equal(m, n); - }) - }) - - describe('$where', function(){ - it('sets the $where condition', function(){ - var m = mquery(); - function go () {} - m.$where(go); - assert.ok(go === m._conditions.$where); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.$where('x'); - assert.equal(m, n); - }) - }) - - describe('where', function(){ - it('without arguments', function(){ - var m = mquery(); - m.where(); - assert.deepEqual({}, m._conditions); - }) - it('with non-string/object argument', function(){ - var m = mquery(); - - assert.throws(function(){ - m.where([]); - }, /path must be a string or object/); - }) - describe('with one argument', function(){ - it('that is an object', function(){ - var m = mquery(); - m.where({ name: 'flawed' }); - assert.strictEqual(m._conditions.name, 'flawed'); - }) - it('that is a query', function(){ - var m = mquery({ name: 'first' }); - var n = mquery({ name: 'changed' }); - m.where(n); - assert.strictEqual(m._conditions.name, 'changed'); - }) - it('that is a string', function(){ - var m = mquery(); - m.where('name'); - assert.equal('name', m._path); - assert.strictEqual(m._conditions.name, undefined); - }) - }) - it('with two arguments', function(){ - var m = mquery(); - m.where('name', 'The Great Pumpkin'); - assert.equal('name', m._path); - assert.strictEqual(m._conditions.name, 'The Great Pumpkin'); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.where('x', 'y'); - assert.equal(m, n); - var n = m.where() - assert.equal(m, n); - }) - }) - - describe('equals', function(){ - it('must be called after where()', function(){ - var m = mquery(); - assert.throws(function () { - m.equals(); - }, /must be used after where/) - }) - it('sets value of path set with where()', function(){ - var m = mquery(); - m.where('age').equals(1000); - assert.deepEqual({ age: 1000 }, m._conditions); - }) - it('is chainable', function(){ - var m = mquery(); - var n = m.where('x').equals(3); - assert.equal(m, n); - }) - }) - - describe('or', function(){ - it('pushes onto the internal $or condition', function(){ - var m = mquery(); - m.or({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$or) - }) - it('allows passing arrays', function(){ - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.or(arg); - assert.deepEqual(arg, m._conditions.$or) - }) - it('allows calling multiple times', function(){ - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.or(arg); - m.or({ y: 1 }) - m.or([{ w: 'oo' }, { z: 'oo'} ]) - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$or) - }) - it('is chainable', function(){ - var m = mquery(); - m.or({ o: "k"}).where('name', 'table'); - assert.deepEqual({ name: 'table', $or: [{ o: 'k' }] }, m._conditions) - }) - }) - - describe('nor', function(){ - it('pushes onto the internal $nor condition', function(){ - var m = mquery(); - m.nor({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$nor) - }) - it('allows passing arrays', function(){ - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.nor(arg); - assert.deepEqual(arg, m._conditions.$nor) - }) - it('allows calling multiple times', function(){ - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.nor(arg); - m.nor({ y: 1 }) - m.nor([{ w: 'oo' }, { z: 'oo'} ]) - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$nor) - }) - it('is chainable', function(){ - var m = mquery(); - m.nor({ o: "k"}).where('name', 'table'); - assert.deepEqual({ name: 'table', $nor: [{ o: 'k' }] }, m._conditions) - }) - }) - - describe('and', function(){ - it('pushes onto the internal $and condition', function(){ - var m = mquery(); - m.and({ 'Nightmare Before Christmas': true }); - assert.deepEqual([{'Nightmare Before Christmas': true }], m._conditions.$and) - }) - it('allows passing arrays', function(){ - var m = mquery(); - var arg = [{ 'Nightmare Before Christmas': true }, { x: 1 }]; - m.and(arg); - assert.deepEqual(arg, m._conditions.$and) - }) - it('allows calling multiple times', function(){ - var m = mquery(); - var arg = [{ looper: true }, { x: 1 }]; - m.and(arg); - m.and({ y: 1 }) - m.and([{ w: 'oo' }, { z: 'oo'} ]) - assert.deepEqual([{looper:true},{x:1},{y:1},{w:'oo'},{z:'oo'}], m._conditions.$and) - }) - it('is chainable', function(){ - var m = mquery(); - m.and({ o: "k"}).where('name', 'table'); - assert.deepEqual({ name: 'table', $and: [{ o: 'k' }] }, m._conditions) - }) - }) - - function generalCondition (type) { - return function () { - it('accepts 2 args', function(){ - var m = mquery()[type]('count', 3); - var check = {}; - check['$' + type] = 3; - assert.deepEqual(m._conditions.count, check); - }) - it('uses previously set `where` path if 1 arg passed', function(){ - var m = mquery().where('count')[type](3); - var check = {}; - check['$' + type] = 3; - assert.deepEqual(m._conditions.count, check); - }) - it('throws if 1 arg was passed but no previous `where` was used', function(){ - assert.throws(function(){ - mquery()[type](3); - }, /must be used after where/); - }) - it('is chainable', function(){ - var m = mquery().where('count')[type](3).where('x', 8); - var check = {x: 8, count: {}}; - check.count['$' + type] = 3; - assert.deepEqual(m._conditions, check); - }) - it('overwrites previous value', function(){ - var m = mquery().where('count')[type](3)[type](8); - var check = {}; - check['$' + type] = 8; - assert.deepEqual(m._conditions.count, check); - }) - } - } - - 'gt gte lt lte ne in nin regex size maxDistance'.split(' ').forEach(function (type) { - describe(type, generalCondition(type)) - }) - - describe('mod', function () { - describe('with 1 argument', function(){ - it('requires a previous where()', function(){ - assert.throws(function () { - mquery().mod([30, 10]) - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('madmen').mod([10,20]); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) - }) - }) - - describe('with 2 arguments and second is non-Array', function(){ - it('requires a previous where()', function(){ - assert.throws(function () { - mquery().mod('x', 10) - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('madmen').mod(10, 20); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) - }) - }) - - it('with 2 arguments and second is an array', function(){ - var m = mquery().mod('madmen', [10,20]); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) - }) - - it('with 3 arguments', function(){ - var m = mquery().mod('madmen', 10, 20); - assert.deepEqual(m._conditions, { madmen: { $mod: [10,20] }}) - }) - - it('is chainable', function(){ - var m = mquery().mod('madmen', 10, 20).where('x', 8); - var check = { madmen: { $mod: [10,20] }, x: 8}; - assert.deepEqual(m._conditions, check); - }) - }) - - describe('exists', function(){ - it('with 0 args', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().exists() - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('name').exists(); - var check = { name: { $exists: true }}; - assert.deepEqual(m._conditions, check); - }) - }) - - describe('with 1 arg', function(){ - describe('that is boolean', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().exists() - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().exists('name', false); - var check = { name: { $exists: false }}; - assert.deepEqual(m._conditions, check); - }) - }) - describe('that is not boolean', function(){ - it('sets the value to `true`', function(){ - var m = mquery().where('name').exists('yummy'); - var check = { yummy: { $exists: true }}; - assert.deepEqual(m._conditions, check); - }) - }) - }) - - describe('with 2 args', function(){ - it('works', function(){ - var m = mquery().exists('yummy', false); - var check = { yummy: { $exists: false }}; - assert.deepEqual(m._conditions, check); - }) - }) - - it('is chainable', function(){ - var m = mquery().where('name').exists().find({ x: 1 }); - var check = { name: { $exists: true }, x: 1}; - assert.deepEqual(m._conditions, check); - }) - }) - - describe('elemMatch', function(){ - describe('with null/undefined first argument', function(){ - assert.throws(function () { - mquery().elemMatch(); - }, /Invalid argument/); - assert.throws(function () { - mquery().elemMatch(null); - }, /Invalid argument/); - assert.doesNotThrow(function () { - mquery().elemMatch('', {}); - }); - }) - - describe('with 1 argument', function(){ - it('throws if not a function or object', function(){ - assert.throws(function () { - mquery().elemMatch([]); - }, /Invalid argument/); - }) - - describe('that is an object', function(){ - it('throws if no previous `where` was used', function(){ - assert.throws(function () { - mquery().elemMatch({}); - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('comment').elemMatch({ author: 'joe', votes: {$gte: 3 }}); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }) - }) - describe('that is a function', function(){ - it('throws if no previous `where` was used', function(){ - assert.throws(function () { - mquery().elemMatch(function(){}); - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('comment').elemMatch(function (query) { - query.where({ author: 'joe', votes: {$gte: 3 }}) - }); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }) - }) - }) - - describe('with 2 arguments', function(){ - describe('and the 2nd is an object', function(){ - it('works', function(){ - var m = mquery().elemMatch('comment', { author: 'joe', votes: {$gte: 3 }}); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }) - }) - describe('and the 2nd is a function', function(){ - it('works', function(){ - var m = mquery().elemMatch('comment', function (query) { - query.where({ author: 'joe', votes: {$gte: 3 }}) - }); - assert.deepEqual({ comment: { $elemMatch: { author: 'joe', votes: {$gte: 3}}}}, m._conditions); - }) - }) - it('and the 2nd is not a function or object', function(){ - assert.throws(function () { - mquery().elemMatch('comment', []); - }, /Invalid argument/); - }) - }) - }) - - describe('within', function(){ - it('is chainable', function(){ - var m = mquery(); - assert.equal(m.where('a').within(), m); - }) - describe('when called with arguments', function(){ - it('must follow where()', function(){ - assert.throws(function () { - mquery().within([]); - }, /must be used after where/); - }) - - describe('of length 1', function(){ - it('throws if not a recognized shape', function(){ - assert.throws(function () { - mquery().where('loc').within({}); - }, /Invalid argument/) - assert.throws(function () { - mquery().where('loc').within(null); - }, /Invalid argument/) - }) - it('delegates to circle when center exists', function(){ - var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); - assert.deepEqual({ $geoWithin: {$center:[[10,10], 3]}}, m._conditions.loc); - }) - it('delegates to box when exists', function(){ - var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); - assert.deepEqual({ $geoWithin: {$box:[[10,10], [11,14]]}}, m._conditions.loc); - }) - it('delegates to polygon when exists', function(){ - var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $geoWithin: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); - }) - it('delegates to geometry when exists', function(){ - var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $geoWithin: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); - }) - }) - - describe('of length 2', function(){ - it('delegates to box()', function(){ - var m = mquery().where('loc').within([1,2],[2,5]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[2,5]]}}); - }) - }) - - describe('of length > 2', function(){ - it('delegates to polygon()', function(){ - var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); - }) - }) - }) - }) - - describe('geoWithin', function(){ - before(function(){ - mquery.use$geoWithin = false; - }) - after(function(){ - mquery.use$geoWithin = true; - }) - describe('when called with arguments', function(){ - describe('of length 1', function(){ - it('delegates to circle when center exists', function(){ - var m = mquery().where('loc').within({ center: [10,10], radius: 3 }); - assert.deepEqual({ $within: {$center:[[10,10], 3]}}, m._conditions.loc); - }) - it('delegates to box when exists', function(){ - var m = mquery().where('loc').within({ box: [[10,10], [11,14]] }); - assert.deepEqual({ $within: {$box:[[10,10], [11,14]]}}, m._conditions.loc); - }) - it('delegates to polygon when exists', function(){ - var m = mquery().where('loc').within({ polygon: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $within: {$polygon:[[10,10], [11,14],[10,9]]}}, m._conditions.loc); - }) - it('delegates to geometry when exists', function(){ - var m = mquery().where('loc').within({ type: 'Polygon', coordinates: [[10,10], [11,14],[10,9]] }); - assert.deepEqual({ $within: {$geometry: {type:'Polygon', coordinates: [[10,10], [11,14],[10,9]]}}}, m._conditions.loc); - }) - }) - - describe('of length 2', function(){ - it('delegates to box()', function(){ - var m = mquery().where('loc').within([1,2],[2,5]); - assert.deepEqual(m._conditions.loc, { $within: { $box: [[1,2],[2,5]]}}); - }) - }) - - describe('of length > 2', function(){ - it('delegates to polygon()', function(){ - var m = mquery().where('loc').within([1,2],[2,5],[2,4],[1,3]); - assert.deepEqual(m._conditions.loc, { $within: { $polygon: [[1,2],[2,5],[2,4],[1,3]]}}); - }) - }) - }) - }) - - describe('box', function(){ - describe('with 1 argument', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().box('sometihng'); - }, /Invalid argument/); - }) - }) - describe('with > 3 arguments', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().box(1,2,3,4); - }, /Invalid argument/); - }) - }) - - describe('with 2 arguments', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().box([],[]); - }, /must be used after where/); - }) - it('works', function(){ - var m = mquery().where('loc').box([1,2],[3,4]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); - }) - }) - - describe('with 3 arguments', function(){ - it('works', function(){ - var m = mquery().box('loc', [1,2],[3,4]); - assert.deepEqual(m._conditions.loc, { $geoWithin: { $box: [[1,2],[3,4]] }}); - }) - }) - }) - - describe('polygon', function(){ - describe('when first argument is not a string', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().polygon({}); - }, /must be used after where/); - - assert.doesNotThrow(function () { - mquery().where('loc').polygon([1,2], [2,3], [3,6]); - }); - }) - - it('assigns arguments to within polygon condition', function(){ - var m = mquery().where('loc').polygon([1,2], [2,3], [3,6]); - assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); - }) - }) - - describe('when first arg is a string', function(){ - it('assigns remaining arguments to within polygon condition', function(){ - var m = mquery().polygon('loc', [1,2], [2,3], [3,6]); - assert.deepEqual(m._conditions, { loc: {$geoWithin: {$polygon: [[1,2],[2,3],[3,6]]}} }); - }) - }) - }) - - describe('circle', function(){ - describe('with one arg', function(){ - it('must follow where()', function(){ - assert.throws(function () { - mquery().circle('x'); - }, /must be used after where/); - assert.doesNotThrow(function () { - mquery().where('loc').circle({center:[0,0], radius: 3 }); - }); - }) - it('works', function(){ - var m = mquery().where('loc').circle({center:[0,0], radius: 3 }); - assert.deepEqual(m._conditions, { loc: { $geoWithin: {$center: [[0,0],3] }}}); - }) - }) - describe('with 3 args', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().where('loc').circle(1,2,3); - }, /Invalid argument/); - }) - }) - describe('requires radius and center', function(){ - assert.throws(function () { - mquery().circle('loc', { center: 1 }); - }, /center and radius are required/); - assert.throws(function () { - mquery().circle('loc', { radius: 1 }); - }, /center and radius are required/); - assert.doesNotThrow(function () { - mquery().circle('loc', { center: [1,2], radius: 1 }); - }); - }) - }) - - describe('geometry', function(){ - // within + intersects - var point = { type: 'Point', coordinates: [[0,0],[1,1]] }; - - it('must be called after within or intersects', function(done){ - assert.throws(function () { - mquery().where('a').geometry(point); - }, /must come after/); - - assert.doesNotThrow(function () { - mquery().where('a').within().geometry(point); - }); - - assert.doesNotThrow(function () { - mquery().where('a').intersects().geometry(point); - }); - - done(); - }) - - describe('when called with one argument', function(){ - describe('after within()', function(){ - it('and arg quacks like geoJSON', function(done){ - var m = mquery().where('a').within().geometry(point); - assert.deepEqual({ a: { $geoWithin: { $geometry: point }}}, m._conditions); - done(); - }) - }) - - describe('after intersects()', function(){ - it('and arg quacks like geoJSON', function(done){ - var m = mquery().where('a').intersects().geometry(point); - assert.deepEqual({ a: { $geoIntersects: { $geometry: point }}}, m._conditions); - done(); - }) - }) - - it('and arg does not quack like geoJSON', function(done){ - assert.throws(function () { - mquery().where('b').within().geometry({type:1, coordinates:2}); - }, /Invalid argument/); - done(); - }) - }) - - describe('when called with zero arguments', function(){ - it('throws', function(done){ - assert.throws(function () { - mquery().where('a').within().geometry(); - }, /Invalid argument/); - - done(); - }) - }) - - describe('when called with more than one arguments', function(){ - it('throws', function(done){ - assert.throws(function () { - mquery().where('a').within().geometry({type:'a',coordinates:[]}, 2); - }, /Invalid argument/); - done(); - }) - }) - }) - - describe('intersects', function(){ - it('must be used after where()', function(done){ - var m = mquery(); - assert.throws(function () { - m.intersects(); - }, /must be used after where/) - done(); - }) - - it('sets geo comparison to "$intersects"', function(done){ - var n = mquery().where('a').intersects(); - assert.equal('$geoIntersects', n._geoComparison); - done(); - }) - - it('is chainable', function(){ - var m = mquery(); - assert.equal(m.where('a').intersects(), m); - }) - - it('calls geometry if argument quacks like geojson', function(done){ - var m = mquery(); - var o = { type: 'LineString', coordinates: [[0,1],[3,40]] }; - var ran = false; - - m.geometry = function (arg) { - ran = true; - assert.deepEqual(o, arg); - } - - m.where('a').intersects(o); - assert.ok(ran); - - done(); - }) - - it('throws if argument is not geometry-like', function(done){ - var m = mquery().where('a'); - - assert.throws(function () { - m.intersects(null); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects(undefined); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects(false); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects({}); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects([]); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects(function(){}); - }, /Invalid argument/); - - assert.throws(function () { - m.intersects(NaN); - }, /Invalid argument/); - - done(); - }) - }) - - describe('near', function(){ - // near nearSphere - describe('with 0 args', function(){ - it('is compatible with geometry()', function(done){ - var q = mquery().where('x').near().geometry({ type: 'Point', coordinates: [180, 11] }); - assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [180,11]}}}, q._conditions.x); - done(); - }) - }) - - describe('with 1 arg', function(){ - it('throws if not used after where()', function(){ - assert.throws(function () { - mquery().near(1); - }, /must be used after where/) - }) - it('does not throw if used after where()', function(){ - assert.doesNotThrow(function () { - mquery().where('loc').near({center:[1,1]}); - }) - }) - }) - describe('with > 2 args', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().near(1,2,3); - }, /Invalid argument/) - }) - }) - - it('creates $geometry args for GeoJSON', function(){ - var m = mquery().where('loc').near({ center: { type: 'Point', coordinates: [10,10] }}); - assert.deepEqual({ $near: {$geometry: {type:'Point', coordinates: [10,10]}}}, m._conditions.loc); - }) - - it('expects `center`', function(){ - assert.throws(function () { - mquery().near('loc', { maxDistance: 3 }); - }, /center is required/) - assert.doesNotThrow(function () { - mquery().near('loc', { center: [3,4] }); - }) - }) - - it('accepts spherical conditions', function(){ - var m = mquery().where('loc').near({ center: [1,2], spherical: true }); - assert.deepEqual(m._conditions, { loc: { $nearSphere: [1,2]}}); - }) - - it('is non-spherical by default', function(){ - var m = mquery().where('loc').near({ center: [1,2] }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2]}}); - }) - - it('supports maxDistance', function(){ - var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}}); - }) - - it('is chainable', function(){ - var m = mquery().where('loc').near({ center: [1,2], maxDistance:4 }).find({ x: 1 }); - assert.deepEqual(m._conditions, { loc: { $near: [1,2], $maxDistance: 4}, x: 1}); - }) - - describe('supports passing GeoJSON, gh-13', function(){ - it('with center', function(){ - var m = mquery().where('loc').near({ - center: { type: 'Point', coordinates: [1,1] } - , maxDistance: 2 - }); - - var expect = { - loc: { - $near: { - $geometry: { - type: 'Point' - , coordinates : [1,1] - } - } - , $maxDistance : 2 - } - } - - assert.deepEqual(m._conditions, expect); - }) - }) - }) - - // fields - - describe('select', function(){ - describe('with 0 args', function(){ - it('is chainable', function(){ - var m = mquery() - assert.equal(m, m.select()); - }) - }) - - it('accepts an object', function(){ - var o = { x: 1, y: 1 } - var m = mquery().select(o); - assert.deepEqual(m._fields, o); - }) - - it('accepts a string', function(){ - var o = 'x -y'; - var m = mquery().select(o); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - }) - - it('does not accept an array', function(done){ - assert.throws(function () { - var o = ['x', '-y']; - var m = mquery().select(o); - }, /Invalid select/); - done(); - }) - - it('merges previous arguments', function(){ - var o = { x: 1, y: 0, a: 1 } - var m = mquery().select(o); - m.select('z -u w').select({ x: 0 }) - assert.deepEqual(m._fields, { - x: 0 - , y: 0 - , z: 1 - , u: 0 - , w: 1 - , a: 1 - }); - }) - - it('rejects non-string, object, arrays', function(){ - assert.throws(function () { - mquery().select(function(){}); - }, /Invalid select\(\) argument/); - }) - - it('accepts aguments objects', function(){ - var m = mquery(); - function t () { - m.select(arguments); - assert.deepEqual(m._fields, { x: 1, y: 0 }); - } - t('x', '-y'); - }) - - noDistinct('select'); - no('count', 'select'); - }) - - describe('selected', function() { - it('returns true when fields have been selected', function(done) { - var m = mquery().select({ name: 1 }); - assert.ok(m.selected()); - - var m = mquery().select('name'); - assert.ok(m.selected()); - - done(); - }); - - it('returns false when no fields have been selected', function(done) { - var m = mquery(); - assert.strictEqual(false, m.selected()); - done(); - }); - }); - - describe('selectedInclusively', function() { - describe('returns false', function(){ - it('when no fields have been selected', function(done) { - assert.strictEqual(false, mquery().selectedInclusively()); - assert.equal(false, mquery().select({}).selectedInclusively()); - done(); - }); - it('when any fields have been excluded', function(done) { - assert.strictEqual(false, mquery().select('-name').selectedInclusively()); - assert.strictEqual(false, mquery().select({ name: 0 }).selectedInclusively()); - assert.strictEqual(false, mquery().select('name bio -_id').selectedInclusively()); - assert.strictEqual(false, mquery().select({ name: 1, _id: 0 }).selectedInclusively()); - done(); - }); - }); - - describe('returns true', function() { - it('when fields have been included', function(done) { - assert.equal(true, mquery().select('name').selectedInclusively()); - assert.equal(true, mquery().select({ name:1 }).selectedInclusively()); - done(); - }); - }); - }); - - describe('selectedExclusively', function() { - describe('returns false', function(){ - it('when no fields have been selected', function(done) { - assert.equal(false, mquery().selectedExclusively()); - assert.equal(false, mquery().select({}).selectedExclusively()); - done(); - }); - it('when fields have only been included', function(done) { - assert.equal(false, mquery().select('name').selectedExclusively()); - assert.equal(false, mquery().select({ name: 1 }).selectedExclusively()); - done(); - }); - }); - - describe('returns true', function() { - it('when any field has been excluded', function(done) { - assert.equal(true, mquery().select('-name').selectedExclusively()); - assert.equal(true, mquery().select({ name:0 }).selectedExclusively()); - assert.equal(true, mquery().select('-_id').selectedExclusively()); - assert.strictEqual(true, mquery().select('name bio -_id').selectedExclusively()); - assert.strictEqual(true, mquery().select({ name: 1, _id: 0 }).selectedExclusively()); - done(); - }); - }); - }); - - describe('slice', function(){ - describe('with 0 args', function(){ - it('is chainable', function(){ - var m = mquery() - assert.equal(m, m.slice()); - }) - it('is a noop', function(){ - var m = mquery().slice(); - assert.deepEqual(m._fields, undefined); - }) - }) - - describe('with 1 arg', function(){ - it('throws if not called after where()', function(){ - assert.throws(function () { - mquery().slice(1); - }, /must be used after where/); - assert.doesNotThrow(function () { - mquery().where('a').slice(1); - }); - }) - it('that is a number', function(){ - var query = mquery(); - query.where('collection').slice(5); - assert.deepEqual(query._fields, {collection: {$slice: 5}}); - }) - it('that is an array', function(){ - var query = mquery(); - query.where('collection').slice([5,10]); - assert.deepEqual(query._fields, {collection: {$slice: [5,10]}}); - }) - }) - - describe('with 2 args', function(){ - describe('and first is a number', function(){ - it('throws if not called after where', function(){ - assert.throws(function () { - mquery().slice(2,3); - }, /must be used after where/); - }) - it('does not throw if used after where', function(){ - var query = mquery(); - query.where('collection').slice(2,3); - assert.deepEqual(query._fields, {collection: {$slice: [2,3]}}); - }) - }) - it('and first is not a number', function(){ - var query = mquery().slice('collection', [-5, 2]); - assert.deepEqual(query._fields, {collection: {$slice: [-5,2]}}); - }) - }) - - describe('with 3 args', function(){ - it('works', function(){ - var query = mquery(); - query.slice('collection', 14, 10); - assert.deepEqual(query._fields, {collection: {$slice: [14, 10]}}); - }) - }) - - noDistinct('slice'); - no('count', 'slice'); - }) - - // options - - describe('sort', function(){ - describe('with 0 args', function(){ - it('chains', function(){ - var m = mquery(); - assert.equal(m, m.sort()); - }) - it('has no affect', function(){ - var m = mquery(); - assert.equal(m.options.sort, undefined); - }) - }) - - it('works', function(){ - var query = mquery(); - query.sort('a -c b'); - assert.deepEqual(query.options.sort, { a : 1, b: 1, c : -1}); - - query = mquery(); - query.sort({'a': 1, 'c': -1, 'b': 'asc', e: 'descending', f: 'ascending'}); - assert.deepEqual(query.options.sort, {'a': 1, 'c': -1, 'b': 1, 'e': -1, 'f': 1}); - - query = mquery(); - var e= undefined; - try { - query.sort(['a', 1]); - } catch (err) { - e= err; - } - assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); - - e= undefined; - try { - query.sort('a', 1, 'c', -1, 'b', 1); - } catch (err) { - e= err; - } - assert.ok(e, 'uh oh. no error was thrown'); - assert.equal(e.message, 'Invalid sort() argument. Must be a string or object.'); - }) - - no('count', 'sort'); - }) - - function simpleOption (type) { - describe(type, function(){ - it('sets the ' + type + ' option', function(){ - var m = mquery()[type](2); - assert.equal(2, m.options[type]); - }) - it('is chainable', function(){ - var m = mquery(); - assert.equal(m[type](3), m); - }) - - noDistinct(type); - - if ('limit' == type || 'skip' == type) return; - no('count', type); - }) - } - - 'limit skip maxScan batchSize comment'.split(' ').forEach(simpleOption); - - describe('snapshot', function(){ - it('works', function(){ - var query = mquery(); - query.snapshot(); - assert.equal(true, query.options.snapshot); - - var query = mquery() - query.snapshot(true); - assert.equal(true, query.options.snapshot); - - var query = mquery() - query.snapshot(false); - assert.equal(false, query.options.snapshot); - }) - noDistinct('snapshot'); - no('count', 'snapshot'); - }) - - describe('hint', function(){ - it('accepts an object', function(){ - var query2 = mquery(); - query2.hint({'a': 1, 'b': -1}); - assert.deepEqual(query2.options.hint, {'a': 1, 'b': -1}); - }) - - it('rejects everything else', function(){ - assert.throws(function(){ - mquery().hint('c'); - }, /Invalid hint./); - assert.throws(function(){ - mquery().hint(['c']); - }, /Invalid hint./); - assert.throws(function(){ - mquery().hint(1); - }, /Invalid hint./); - }) - - describe('does not have side affects', function(){ - it('on invalid arg', function(){ - var m = mquery(); - try { - m.hint(1); - } catch (err) { - // ignore - } - assert.equal(undefined, m.options.hint); - }) - it('on missing arg', function(){ - var m = mquery().hint(); - assert.equal(undefined, m.options.hint); - }) - }) - - noDistinct('hint'); - no('count', 'hint'); - }) - - describe('slaveOk', function(){ - it('works', function(){ - var query = mquery(); - query.slaveOk(); - assert.equal(true, query.options.slaveOk); - - var query = mquery() - query.slaveOk(true); - assert.equal(true, query.options.slaveOk); - - var query = mquery() - query.slaveOk(false); - assert.equal(false, query.options.slaveOk); - }) - }) - - describe('read', function(){ - it('sets associated readPreference option', function(){ - var m = mquery(); - m.read('p'); - assert.equal('primary', m.options.readPreference.mode); - }) - it('is chainable', function(){ - var m = mquery(); - assert.equal(m, m.read('sp')); - }) - }) - - describe('tailable', function(){ - it('works', function(){ - var query = mquery(); - query.tailable(); - assert.equal(true, query.options.tailable); - - var query = mquery() - query.tailable(true); - assert.equal(true, query.options.tailable); - - var query = mquery() - query.tailable(false); - assert.equal(false, query.options.tailable); - }) - it('is chainable', function(){ - var m = mquery(); - assert.equal(m, m.tailable()); - }) - noDistinct('tailable'); - no('count', 'tailable'); - }) - - // utils - - describe('merge', function(){ - describe('with falsy arg', function(){ - it('returns itself', function(){ - var m = mquery(); - assert.equal(m, m.merge()); - assert.equal(m, m.merge(null)); - assert.equal(m, m.merge(0)); - }) - }) - describe('with an argument', function(){ - describe('that is not a query or plain object', function(){ - it('throws', function(){ - assert.throws(function () { - mquery().merge([]); - }, /Invalid argument/); - assert.throws(function () { - mquery().merge('merge'); - }, /Invalid argument/); - assert.doesNotThrow(function () { - mquery().merge({}); - }, /Invalid argument/); - }) - }) - - describe('that is a query', function(){ - it('merges conditions, field selection, and options', function(){ - var m = mquery({ x: 'hi' }, { select: 'x y', another: true }) - var n = mquery().merge(m); - assert.deepEqual(n._conditions, m._conditions); - assert.deepEqual(n._fields, m._fields); - assert.deepEqual(n.options, m.options); - }) - it('clones update arguments', function(done){ - var original = { $set: { iTerm: true }} - var m = mquery().update(original); - var n = mquery().merge(m); - m.update({ $set: { x: 2 }}) - assert.notDeepEqual(m._update, n._update); - done(); - }) - it('is chainable', function(){ - var m = mquery({ x: 'hi' }); - var n = mquery(); - assert.equal(n, n.merge(m)); - }) - }) - - describe('that is an object', function(){ - it('merges', function(){ - var m = { x: 'hi' }; - var n = mquery().merge(m); - assert.deepEqual(n._conditions, { x: 'hi' }); - }) - it('clones update arguments', function(done){ - var original = { $set: { iTerm: true }} - var m = mquery().update(original); - var n = mquery().merge(original); - m.update({ $set: { x: 2 }}) - assert.notDeepEqual(m._update, n._update); - done(); - }) - it('is chainable', function(){ - var m = { x: 'hi' }; - var n = mquery(); - assert.equal(n, n.merge(m)); - }) - }) - }) - }) - - // queries - - describe('find', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.find() - }) - assert.doesNotThrow(function () { - m.find({ x: 1 }) - }) - }) - }) - - it('is chainable', function(){ - var m = mquery().find({ x: 1 }).find().find({ y: 2 }); - assert.deepEqual(m._conditions, {x:1,y:2}); - }) - - it('merges other queries', function(){ - var m = mquery({ name: 'mquery' }); - m.tailable(); - m.select('_id'); - var a = mquery().find(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }) - - describe('executes', function(){ - before(function (done) { - col.insert({ name: 'mquery' }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ name: 'mquery' }, done); - }) - - it('when criteria is passed with a callback', function(done){ - mquery(col).find({ name: 'mquery' }, function (err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }) - }) - it('when Quer yis passed with a callback', function(done){ - var m = mquery({ name: 'mquery' }); - mquery(col).find(m, function (err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }) - }) - it('when just a callback is passed', function(done){ - mquery({ name: 'mquery' }).collection(col).find(function (err, docs) { - assert.ifError(err); - assert.equal(1, docs.length); - done(); - }); - }) - }) - }) - - describe('findOne', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.findOne() - }) - assert.doesNotThrow(function () { - m.findOne({ x: 1 }) - }) - }) - }) - - it('is chainable', function(){ - var m = mquery(); - var n = m.findOne({ x: 1 }).findOne().findOne({ y: 2 }); - assert.equal(m, n); - assert.deepEqual(m._conditions, {x:1,y:2}); - assert.equal('findOne', m.op); - }) - - it('merges other queries', function(){ - var m = mquery({ name: 'mquery' }); - m.read('nearest'); - m.select('_id'); - var a = mquery().findOne(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }) - - describe('executes', function(){ - before(function (done) { - col.insert({ name: 'mquery findone' }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ name: 'mquery findone' }, done); - }) - - it('when criteria is passed with a callback', function(done){ - mquery(col).findOne({ name: 'mquery findone' }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }) - }) - it('when Query is passed with a callback', function(done){ - var m = mquery(col).where({ name: 'mquery findone' }); - mquery(col).findOne(m, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }) - }) - it('when just a callback is passed', function(done){ - mquery({ name: 'mquery findone' }).collection(col).findOne(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('mquery findone', doc.name); - done(); - }); - }) - }) - }) - - describe('count', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.count() - }) - assert.doesNotThrow(function () { - m.count({ x: 1 }) - }) - }) - }) - - it('is chainable', function(){ - var m = mquery(); - var n = m.count({ x: 1 }).count().count({ y: 2 }); - assert.equal(m, n); - assert.deepEqual(m._conditions, {x:1,y:2}); - assert.equal('count', m.op); - }) - - it('merges other queries', function(){ - var m = mquery({ name: 'mquery' }); - m.read('nearest'); - m.select('_id'); - var a = mquery().count(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - }) - - describe('executes', function(){ - before(function (done) { - col.insert({ name: 'mquery count' }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ name: 'mquery count' }, done); - }) - - it('when criteria is passed with a callback', function(done){ - mquery(col).count({ name: 'mquery count' }, function (err, count) { - assert.ifError(err); - assert.ok(count); - assert.ok(1 === count); - done(); - }) - }) - it('when Query is passed with a callback', function(done){ - var m = mquery({ name: 'mquery count' }); - mquery(col).count(m, function (err, count) { - assert.ifError(err); - assert.ok(count); - assert.ok(1 === count); - done(); - }) - }) - it('when just a callback is passed', function(done){ - mquery({ name: 'mquery count' }).collection(col).count(function (err, count) { - assert.ifError(err); - assert.ok(1 === count); - done(); - }); - }) - }) - - describe('validates its option', function(){ - it('sort', function(done){ - assert.throws(function(){ - var m = mquery().sort('x').count(); - }, /sort cannot be used with count/); - done(); - }) - - it('select', function(done){ - assert.throws(function(){ - var m = mquery().select('x').count(); - }, /field selection and slice cannot be used with count/); - done(); - }) - - it('slice', function(done){ - assert.throws(function(){ - var m = mquery().where('x').slice(-3).count(); - }, /field selection and slice cannot be used with count/); - done(); - }) - - it('limit', function(done){ - assert.doesNotThrow(function(){ - var m = mquery().limit(3).count(); - }) - done(); - }) - - it('skip', function(done){ - assert.doesNotThrow(function(){ - var m = mquery().skip(3).count(); - }) - done(); - }) - - it('batchSize', function(done){ - assert.throws(function(){ - var m = mquery({}, { batchSize: 3 }).count(); - }, /batchSize cannot be used with count/); - done(); - }) - - it('comment', function(done){ - assert.throws(function(){ - var m = mquery().comment('mquery').count(); - }, /comment cannot be used with count/); - done(); - }) - - it('maxScan', function(done){ - assert.throws(function(){ - var m = mquery().maxScan(300).count(); - }, /maxScan cannot be used with count/); - done(); - }) - - it('snapshot', function(done){ - assert.throws(function(){ - var m = mquery().snapshot().count(); - }, /snapshot cannot be used with count/); - done(); - }) - - it('hint', function(done){ - assert.throws(function(){ - var m = mquery().hint({ x: 1 }).count(); - }, /hint cannot be used with count/); - done(); - }) - - it('tailable', function(done){ - assert.throws(function(){ - var m = mquery().tailable().count(); - }, /tailable cannot be used with count/); - done(); - }) - }) - }) - - describe('distinct', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.distinct() - }) - assert.doesNotThrow(function () { - m.distinct('name') - }) - assert.doesNotThrow(function () { - m.distinct({ name: 'mquery distinct' }) - }) - assert.doesNotThrow(function () { - m.distinct({ name: 'mquery distinct' }, 'name') - }) - }) - }) - - it('is chainable', function(){ - var m = mquery({x:1}).distinct('name'); - var n = m.distinct({y:2}); - assert.equal(m, n); - assert.deepEqual(n._conditions, {x:1, y:2}); - assert.equal('name', n._distinct); - assert.equal('distinct', n.op); - }); - - it('overwrites field', function(){ - var m = mquery({ name: 'mquery' }).distinct('name'); - m.distinct('rename'); - assert.equal(m._distinct, 'rename'); - m.distinct({x:1}, 'renamed'); - assert.equal(m._distinct, 'renamed'); - }) - - it('merges other queries', function(){ - var m = mquery().distinct({ name: 'mquery' }, 'age') - m.read('nearest'); - var a = mquery().distinct(m); - assert.deepEqual(a._conditions, m._conditions); - assert.deepEqual(a.options, m.options); - assert.deepEqual(a._fields, m._fields); - assert.deepEqual(a._distinct, m._distinct); - }) - - describe('executes', function(){ - before(function (done) { - col.insert({ name: 'mquery distinct', age: 1 }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ name: 'mquery distinct' }, done); - }) - - it('when distinct arg is passed with a callback', function(done){ - mquery(col).distinct('distinct', function (err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }) - }) - describe('when criteria is passed with a callback', function(){ - it('if distinct arg was declared', function(done){ - mquery(col).distinct('age').distinct({ name: 'mquery distinct' }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }) - }) - it('but not if distinct arg was not declared', function(){ - assert.throws(function(){ - mquery(col).distinct({ name: 'mquery distinct' }, function(){}) - }, /No value for `distinct`/) - }) - }) - describe('when Query is passed with a callback', function(){ - var m = mquery({ name: 'mquery distinct' }); - it('if distinct arg was declared', function(done){ - mquery(col).distinct('age').distinct(m, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }) - }) - it('but not if distinct arg was not declared', function(){ - assert.throws(function(){ - mquery(col).distinct(m, function(){}) - }, /No value for `distinct`/) - }) - }) - describe('when just a callback is passed', function(done){ - it('if distinct arg was declared', function(done){ - var m = mquery({ name: 'mquery distinct' }); - m.collection(col); - m.distinct('age'); - m.distinct(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - done(); - }); - }) - it('but not if no distinct arg was declared', function(){ - var m = mquery(); - m.collection(col); - assert.throws(function () { - m.distinct(function(){}); - }, /No value for `distinct`/); - }) - }) - }) - - describe('validates its option', function(){ - it('sort', function(done){ - assert.throws(function(){ - var m = mquery().sort('x').distinct(); - }, /sort cannot be used with distinct/); - done(); - }) - - it('select', function(done){ - assert.throws(function(){ - var m = mquery().select('x').distinct(); - }, /field selection and slice cannot be used with distinct/); - done(); - }) - - it('slice', function(done){ - assert.throws(function(){ - var m = mquery().where('x').slice(-3).distinct(); - }, /field selection and slice cannot be used with distinct/); - done(); - }) - - it('limit', function(done){ - assert.throws(function(){ - var m = mquery().limit(3).distinct(); - }, /limit cannot be used with distinct/); - done(); - }) - - it('skip', function(done){ - assert.throws(function(){ - var m = mquery().skip(3).distinct(); - }, /skip cannot be used with distinct/); - done(); - }) - - it('batchSize', function(done){ - assert.throws(function(){ - var m = mquery({}, { batchSize: 3 }).distinct(); - }, /batchSize cannot be used with distinct/); - done(); - }) - - it('comment', function(done){ - assert.throws(function(){ - var m = mquery().comment('mquery').distinct(); - }, /comment cannot be used with distinct/); - done(); - }) - - it('maxScan', function(done){ - assert.throws(function(){ - var m = mquery().maxScan(300).distinct(); - }, /maxScan cannot be used with distinct/); - done(); - }) - - it('snapshot', function(done){ - assert.throws(function(){ - var m = mquery().snapshot().distinct(); - }, /snapshot cannot be used with distinct/); - done(); - }) - - it('hint', function(done){ - assert.throws(function(){ - var m = mquery().hint({ x: 1 }).distinct(); - }, /hint cannot be used with distinct/); - done(); - }) - - it('tailable', function(done){ - assert.throws(function(){ - var m = mquery().tailable().distinct(); - }, /tailable cannot be used with distinct/); - done(); - }) - }) - }) - - describe('update', function(){ - describe('with no callback', function(){ - it('does not execute', function(){ - var m = mquery(); - assert.doesNotThrow(function () { - m.update({ name: 'old' }, { name: 'updated' }, { multi: true }) - }) - assert.doesNotThrow(function () { - m.update({ name: 'old' }, { name: 'updated' }) - }) - assert.doesNotThrow(function () { - m.update({ name: 'updated' }) - }) - assert.doesNotThrow(function () { - m.update() - }) - }) - }) - - it('is chainable', function(){ - var m = mquery({x:1}).update({ y: 2 }); - var n = m.where({y:2}); - assert.equal(m, n); - assert.deepEqual(n._conditions, {x:1, y:2}); - assert.deepEqual({ y: 2 }, n._update); - assert.equal('update', n.op); - }); - - it('merges update doc arg', function(){ - var a = [1,2]; - var m = mquery().where({ name: 'mquery' }).update({ x: 'stuff', a: a }); - m.update({ z: 'stuff' }); - assert.deepEqual(m._update, { z: 'stuff', x: 'stuff', a: a }); - assert.deepEqual(m._conditions, { name: 'mquery' }); - assert.ok(!m.options.overwrite); - m.update({}, { z: 'renamed' }, { overwrite: true }); - assert.ok(m.options.overwrite === true); - assert.deepEqual(m._conditions, { name: 'mquery' }); - assert.deepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); - a.push(3); - assert.notDeepEqual(m._update, { z: 'renamed', x: 'stuff', a: a }); - }) - - it('merges other options', function(){ - var m = mquery(); - m.setOptions({ overwrite: true }); - m.update({ age: 77 }, { name: 'pagemill' }, { multi: true }) - assert.deepEqual({ age: 77 }, m._conditions); - assert.deepEqual({ name: 'pagemill' }, m._update); - assert.deepEqual({ overwrite: true, multi: true }, m.options); - }) - - describe('executes', function(){ - var id; - before(function (done) { - // TODO refactor to not use id - id = new mongo.ObjectID; - col.insert({ _id: id, name: 'mquery update', age: 1 }, { safe: true }, done); - }); - - after(function(done){ - col.remove({ _id: id }, done); - }) - - describe('when conds + doc + opts + callback passed', function(){ - it('works', function(done){ - var m = mquery(col).where({ _id: id }) - m.update({}, { name: 'Sparky' }, { safe: true }, function (err, num) { - assert.ifError(err); - assert.ok(1 === num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'Sparky'); - done(); - }) - }) - }) - }) - - describe('when conds + doc + callback passed', function(){ - it('works', function (done) { - var m = mquery(col).update({ _id: id }, { name: 'fairgrounds' }, function (err, num, doc) { - assert.ifError(err); - assert.ok(1, num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'fairgrounds'); - done(); - }) - }) - }) - }) - - describe('when doc + callback passed', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }).update({ name: 'changed' }, function (err, num, doc) { - assert.ifError(err); - assert.ok(1, num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'changed'); - done(); - }) - }) - }) - }) - - describe('when just callback passed', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true }); - m.update({ name: 'Frankenweenie' }); - m.update(function (err, num) { - assert.ifError(err); - assert.ok(1 === num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(doc.name, 'Frankenweenie'); - done(); - }) - }) - }) - }) - - describe('without a callback', function(){ - it('when forced by exec()', function(done){ - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, multi: true }); - m.update({ name: 'forced' }); - - var update = m._collection.update; - m._collection.update = function (conds, doc, opts, cb) { - m._collection.update = update; - - assert.ok(!opts.safe); - assert.ok(true === opts.multi); - assert.equal('forced', doc.$set.name); - done(); - } - - m.exec() - }) - }) - - describe('except when update doc is empty and missing overwrite flag', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true }); - m.update({ }, function (err, num) { - assert.ifError(err); - assert.ok(0 === num); - setTimeout(function(){ - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(3, mquery.utils.keys(doc).length); - assert.equal(id, doc._id.toString()); - assert.equal('Frankenweenie', doc.name); - done(); - }) - }, 300); - }) - }) - }); - - describe('when update doc is set with overwrite flag', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, overwrite: true }); - m.update({ all: 'yep', two: 2 }, function (err, num) { - assert.ifError(err); - assert.ok(1 === num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(3, mquery.utils.keys(doc).length); - assert.equal('yep', doc.all); - assert.equal(2, doc.two); - assert.equal(id, doc._id.toString()); - done(); - }) - }) - }) - }) - - describe('when update doc is empty with overwrite flag', function(){ - it('works', function (done) { - var m = mquery(col).where({ _id: id }); - m.setOptions({ safe: true, overwrite: true }); - m.update({ }, function (err, num) { - assert.ifError(err); - assert.ok(1 === num); - m.findOne(function (err, doc) { - assert.ifError(err); - assert.equal(1, mquery.utils.keys(doc).length); - assert.equal(id, doc._id.toString()); - done(); - }) - }) - }) - }) - - describe('when boolean (true) - exec()', function(){ - it('works', function(done){ - var m = mquery(col).where({ _id: id }); - m.update({ name: 'bool' }).update(true); - setTimeout(function () { - m.findOne(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal('bool', doc.name); - done(); - }) - }, 300) - }) - }) - }) - }) - - describe('remove', function(){ - describe('with 0 args', function(){ - var name = 'remove: no args test' - before(function(done){ - col.insert({ name: name }, { safe: true }, done) - }) - after(function(done){ - col.remove({ name: name }, { safe: true }, done) - }) - - it('does not execute', function(done){ - var remove = col.remove; - col.remove = function () { - col.remove = remove; - done(new Error('remove executed!')); - } - - var m = mquery(col).where({ name: name }).remove() - setTimeout(function () { - col.remove = remove; - done(); - }, 10); - }) - - it('chains', function(){ - var m = mquery(); - assert.equal(m, m.remove()); - }) - }) - - describe('with 1 argument', function(){ - var name = 'remove: 1 arg test' - before(function(done){ - col.insert({ name: name }, { safe: true }, done) - }) - after(function(done){ - col.remove({ name: name }, { safe: true }, done) - }) - - describe('that is a', function(){ - it('plain object', function(){ - var m = mquery(col).remove({ name: 'Whiskers' }); - m.remove({ color: '#fff' }) - assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); - }) - - it('query', function(){ - var q = mquery({ color: '#fff' }); - var m = mquery(col).remove({ name: 'Whiskers' }); - m.remove(q) - assert.deepEqual({ name: 'Whiskers', color: '#fff' }, m._conditions); - }) - - it('function', function(done){ - mquery(col, { safe: true }).where({name: name}).remove(function (err) { - assert.ifError(err); - mquery(col).findOne({ name: name }, function (err, doc) { - assert.ifError(err); - assert.equal(null, doc); - done(); - }) - }); - }) - - it('boolean (true) - execute', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - mquery(col).findOne({ name: name }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - mquery(col).remove(true); - setTimeout(function () { - mquery(col).find(function (err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(0, docs.length); - done(); - }) - }, 300) - }) - }) - }) - }) - }) - - describe('with 2 arguments', function(){ - var name = 'remove: 2 arg test' - beforeEach(function(done){ - col.remove({}, { safe: true }, function (err) { - assert.ifError(err); - col.insert([{ name: 'shelly' }, { name: name }], { safe: true }, function (err) { - assert.ifError(err); - mquery(col).find(function (err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }) - }) - }) - }) - - describe('plain object + callback', function(){ - it('works', function(done){ - mquery(col).remove({ name: name }, function (err) { - assert.ifError(err); - mquery(col).find(function (err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(1, docs.length); - assert.equal('shelly', docs[0].name); - done(); - }) - }); - }) - }) - - describe('mquery + callback', function(){ - it('works', function(done){ - var m = mquery({ name: name }); - mquery(col).remove(m, function (err) { - assert.ifError(err); - mquery(col).find(function (err, docs) { - assert.ifError(err); - assert.ok(docs); - assert.equal(1, docs.length); - assert.equal('shelly', docs[0].name); - done(); - }) - }); - }) - }) - }) - }) - - function validateFindAndModifyOptions (method) { - describe('validates its option', function(){ - it('sort', function(done){ - assert.doesNotThrow(function(){ - var m = mquery().sort('x')[method](); - }) - done(); - }) - - it('select', function(done){ - assert.doesNotThrow(function(){ - var m = mquery().select('x')[method](); - }) - done(); - }) - - it('limit', function(done){ - assert.throws(function(){ - var m = mquery().limit(3)[method](); - }, new RegExp('limit cannot be used with ' + method)); - done(); - }) - - it('skip', function(done){ - assert.throws(function(){ - var m = mquery().skip(3)[method](); - }, new RegExp('skip cannot be used with ' + method)); - done(); - }) - - it('batchSize', function(done){ - assert.throws(function(){ - var m = mquery({}, { batchSize: 3 })[method](); - }, new RegExp('batchSize cannot be used with ' + method)); - done(); - }) - - it('maxScan', function(done){ - assert.throws(function(){ - var m = mquery().maxScan(300)[method](); - }, new RegExp('maxScan cannot be used with ' + method)); - done(); - }) - - it('snapshot', function(done){ - assert.throws(function(){ - var m = mquery().snapshot()[method](); - }, new RegExp('snapshot cannot be used with ' + method)); - done(); - }) - - it('hint', function(done){ - assert.throws(function(){ - var m = mquery().hint({ x: 1 })[method](); - }, new RegExp('hint cannot be used with ' + method)); - done(); - }) - - it('tailable', function(done){ - assert.throws(function(){ - var m = mquery().tailable()[method](); - }, new RegExp('tailable cannot be used with ' + method)); - done(); - }) - - it('comment', function(done){ - assert.throws(function(){ - var m = mquery().comment('mquery')[method](); - }, new RegExp('comment cannot be used with ' + method)); - done(); - }) - }) - } - - describe('findOneAndUpdate', function(){ - var name = 'findOneAndUpdate + fn' - - validateFindAndModifyOptions('findOneAndUpdate'); - - describe('with 0 args', function(){ - it('makes no changes', function(){ - var m = mquery(); - var n = m.findOneAndUpdate(); - assert.deepEqual(m, n); - }) - }) - describe('with 1 arg', function(){ - describe('that is an object', function(){ - it('updates the doc', function(){ - var m = mquery(); - var n = m.findOneAndUpdate({ $set: { name: '1 arg' }}); - assert.deepEqual(n._update, { $set: { name: '1 arg' }}); - }) - }) - describe('that is a query', function(){ - it('updates the doc', function(){ - var m = mquery({ name: name }).update({ x: 1 }); - var n = mquery().findOneAndUpdate(m); - assert.deepEqual(n._update, { x: 1 }); - }) - }) - it('that is a function', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - var m = mquery({ name: name }).collection(col); - name = '1 arg'; - var n = m.update({ $set: { name: name }}); - n.findOneAndUpdate(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - done(); - }); - }) - }) - }) - describe('with 2 args', function(){ - it('conditions + update', function(){ - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { age: 100 }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ age: 100 }, m._update); - }) - it('query + update', function(){ - var n = mquery({ name: name }); - var m = mquery(col); - m.findOneAndUpdate(n, { age: 100 }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ age: 100 }, m._update); - }) - it('update + callback', function(done){ - var m = mquery(col).where({ name: name }); - m.findOneAndUpdate({ $inc: { age: 10 }}, function (err, doc) { - assert.ifError(err); - assert.equal(10, doc.age); - done(); - }); - }) - }) - describe('with 3 args', function(){ - it('conditions + update + options', function(){ - var m = mquery(); - var n = m.findOneAndUpdate({ name: name }, { works: true }, { new: false }); - assert.deepEqual({ name: name}, n._conditions); - assert.deepEqual({ works: true }, n._update); - assert.deepEqual({ new: false }, n.options); - }) - it('conditions + update + callback', function(done){ - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { works: true }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - assert.ok(true === doc.works); - done(); - }); - }) - }) - describe('with 4 args', function(){ - it('conditions + update + options + callback', function(done){ - var m = mquery(col); - m.findOneAndUpdate({ name: name }, { works: false }, { new: false }, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - assert.ok(true === doc.works); - done(); - }); - }) - }) - }) - - describe('findOneAndRemove', function(){ - var name = 'findOneAndRemove' - - validateFindAndModifyOptions('findOneAndRemove'); - - describe('with 0 args', function(){ - it('makes no changes', function(){ - var m = mquery(); - var n = m.findOneAndRemove(); - assert.deepEqual(m, n); - }) - }) - describe('with 1 arg', function(){ - describe('that is an object', function(){ - it('updates the doc', function(){ - var m = mquery(); - var n = m.findOneAndRemove({ name: '1 arg' }); - assert.deepEqual(n._conditions, { name: '1 arg' }); - }) - }) - describe('that is a query', function(){ - it('updates the doc', function(){ - var m = mquery({ name: name }); - var n = m.findOneAndRemove(m); - assert.deepEqual(n._conditions, { name: name }); - }) - }) - it('that is a function', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - var m = mquery({ name: name }).collection(col); - m.findOneAndRemove(function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - done(); - }); - }) - }) - }) - describe('with 2 args', function(){ - it('conditions + options', function(){ - var m = mquery(col); - m.findOneAndRemove({ name: name }, { new: false }); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ new: false }, m.options); - }) - it('query + options', function(){ - var n = mquery({ name: name }); - var m = mquery(col); - m.findOneAndRemove(n, { sort: { x: 1 }}); - assert.deepEqual({ name: name }, m._conditions); - assert.deepEqual({ sort: { 'x': 1 }}, m.options); - }) - it('conditions + callback', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - var m = mquery(col); - m.findOneAndRemove({ name: name }, function (err, doc) { - assert.ifError(err); - assert.equal(name, doc.name); - done(); - }); - }); - }) - it('query + callback', function(done){ - col.insert({ name: name }, { safe: true }, function (err) { - assert.ifError(err); - var n = mquery({ name: name }) - var m = mquery(col); - m.findOneAndRemove(n, function (err, doc) { - assert.ifError(err); - assert.equal(name, doc.name); - done(); - }); - }); - }) - }) - describe('with 3 args', function(){ - it('conditions + options + callback', function(done){ - name = 'findOneAndRemove + conds + options + cb'; - col.insert([{ name: name }, { name: 'a' }], { safe: true }, function (err) { - assert.ifError(err); - var m = mquery(col); - m.findOneAndRemove({ name: name }, { sort: { name: 1 }}, function (err, doc) { - assert.ifError(err); - assert.ok(doc); - assert.equal(name, doc.name); - done(); - }); - }) - }) - }) - }) - - describe('exec', function(){ - beforeEach(function(done){ - col.insert([{ name: 'exec', age: 1 }, { name: 'exec', age: 2 }], done); - }) - - afterEach(function(done){ - mquery(col).remove(done); - }) - - it('requires an op', function(){ - assert.throws(function () { - mquery().exec() - }, /Missing query type/); - }) - - it('find', function(done){ - var m = mquery(col).find({ name: 'exec' }); - m.exec(function (err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }) - }) - - it('findOne', function(done){ - var m = mquery(col).findOne({ age: 2 }); - m.exec(function (err, doc) { - assert.ifError(err); - assert.equal(2, doc.age); - done(); - }) - }) - - it('count', function(done){ - var m = mquery(col).count({ name: 'exec' }); - m.exec(function (err, count) { - assert.ifError(err); - assert.equal(2, count); - done(); - }) - }) - - it('distinct', function(done){ - var m = mquery({ name: 'exec' }); - m.collection(col); - m.distinct('age'); - m.exec(function (err, array) { - assert.ifError(err); - assert.ok(Array.isArray(array)); - assert.equal(2, array.length); - assert.equal(1, array[0]); - assert.equal(2, array[1]); - done(); - }); - }) - - describe('update', function(){ - var num; - - it('with a callback', function(done){ - var m = mquery(col); - m.where({ name: 'exec' }) - - m.count(function (err, _num) { - assert.ifError(err); - num = _num; - m.setOptions({ multi: true }) - m.update({ name: 'exec + update' }); - m.exec(function (err, res) { - assert.ifError(err); - assert.equal(num, res); - mquery(col).find({ name: 'exec + update' }, function (err, docs) { - assert.ifError(err); - assert.equal(num, docs.length); - done(); - }) - }) - }) - }) - - it('without a callback', function(done){ - var m = mquery(col) - m.where({ name: 'exec + update' }).setOptions({ multi: true }) - m.update({ name: 'exec' }); - - // unsafe write - m.exec(); - - setTimeout(function () { - mquery(col).find({ name: 'exec' }, function (err, docs) { - assert.ifError(err); - assert.equal(2, docs.length); - done(); - }) - }, 200) - }) - it('preserves key ordering', function(done) { - var m = mquery(col); - - var m2 = m.update({ _id : 'something' }, { '1' : 1, '2' : 2, '3' : 3}); - var doc = m2._updateForExec().$set; - var count = 0; - for (var i in doc) { - if (count == 0) { - assert.equal('1', i); - } else if (count == 1) { - assert.equal('2', i); - } else if (count ==2) { - assert.equal('3', i); - } - count++; - } - done(); - }); - }) - - describe('remove', function(){ - it('with a callback', function(done){ - var m = mquery(col).where({ age: 2 }).remove(); - m.exec(function (err, num) { - assert.ifError(err); - assert.equal(1, num); - done(); - }) - }) - - it('without a callback', function(done){ - var m = mquery(col).where({ age: 1 }).remove(); - m.exec(); - - setTimeout(function () { - mquery(col).where('name', 'exec').count(function(err, num) { - assert.equal(1, num); - done(); - }) - }, 200) - }) - }) - - describe('findOneAndUpdate', function(){ - it('with a callback', function(done){ - var m = mquery(col); - m.findOneAndUpdate({ name: 'exec', age: 1 }, { $set: { name: 'findOneAndUpdate' }}); - m.exec(function (err, doc) { - assert.ifError(err); - assert.equal('findOneAndUpdate', doc.name); - done(); - }); - }) - }) - - describe('findOneAndRemove', function(){ - it('with a callback', function(done){ - var m = mquery(col); - m.findOneAndRemove({ name: 'exec', age: 2 }); - m.exec(function (err, doc) { - assert.ifError(err); - assert.equal('exec', doc.name); - assert.equal(2, doc.age); - mquery(col).count({ name: 'exec' }, function (err, num) { - assert.ifError(err); - assert.equal(1, num); - done(); - }); - }); - }) - }) - }) - - function noDistinct (type) { - it('cannot be used with distinct()', function(done){ - assert.throws(function () { - mquery().distinct('name')[type](4); - }, new RegExp(type + ' cannot be used with distinct')); - done(); - }) - } - - function no (method, type) { - it('cannot be used with ' + method + '()', function(done){ - assert.throws(function () { - mquery()[method]()[type](4); - }, new RegExp(type + ' cannot be used with ' + method)); - done(); - }) - } - - // query internal - - describe('_updateForExec', function(){ - it('returns a clone of the update object with same key order #19', function(done){ - var update = {}; - update.$push = { n: { $each: [{x:10}], $slice: -1, $sort: {x:1}}}; - - var q = mquery().update({ x: 1 }, update); - - // capture original key order - var order = []; - for (var key in q._update.$push.n) { - order.push(key); - } - - // compare output - var doc = q._updateForExec(); - var i = 0; - for (var key in doc.$push.n) { - assert.equal(key, order[i]); - i++; - } - - done(); - }) - }) -}) diff --git a/node_modules/mongoose/node_modules/ms/.npmignore b/node_modules/mongoose/node_modules/ms/.npmignore deleted file mode 100644 index 3c3629e64..000000000 --- a/node_modules/mongoose/node_modules/ms/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/mongoose/node_modules/ms/Makefile b/node_modules/mongoose/node_modules/ms/Makefile deleted file mode 100644 index dded504de..000000000 --- a/node_modules/mongoose/node_modules/ms/Makefile +++ /dev/null @@ -1,8 +0,0 @@ - -test: - ./node_modules/.bin/mocha test/test.js - -test-browser: - ./node_modules/.bin/serve test/ - -.PHONY: test diff --git a/node_modules/mongoose/node_modules/ms/README.md b/node_modules/mongoose/node_modules/ms/README.md deleted file mode 100644 index c93d43f4b..000000000 --- a/node_modules/mongoose/node_modules/ms/README.md +++ /dev/null @@ -1,65 +0,0 @@ - -# ms.js - -Ever find yourself doing math in your head or writing `1000 * 60 * 60 …`? -Don't want to add obstrusive `Number` prototype extensions to your reusable -/ distributable modules and projects? - -`ms` is a tiny utility that you can leverage when your application needs to -accept a number of miliseconds as a parameter. - -If a number is supplied to `ms`, it returns it immediately (e.g: -If a string that contains the number is supplied, it returns it immediately as -a number (e.g: it returns `100` for `'100'`). - -However, if you pass a string with a number and a valid unit, hte number of -equivalent ms is returned. - -```js -ms('1d') // 86400000 -ms('10h') // 36000000 -ms('2h') // 7200000 -ms('1m') // 60000 -ms('5ms') // 5000 -ms('100') // '100' -ms(100) // 100 -``` - -## How to use - -### Node - -```js -require('ms') -``` - -### Browser - -```html - -``` - -## Credits - -(The MIT License) - -Copyright (c) 2011 Guillermo Rauch <guillermo@learnboost.com> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongoose/node_modules/ms/ms.js b/node_modules/mongoose/node_modules/ms/ms.js deleted file mode 100644 index b4621bcd5..000000000 --- a/node_modules/mongoose/node_modules/ms/ms.js +++ /dev/null @@ -1,35 +0,0 @@ -/** - -# ms.js - -No more painful `setTimeout(fn, 60 * 4 * 3 * 2 * 1 * Infinity * NaN * '☃')`. - - ms('2d') // 172800000 - ms('1.5h') // 5400000 - ms('1h') // 3600000 - ms('1m') // 60000 - ms('5s') // 5000 - ms('500ms') // 500 - ms('100') // '100' - ms(100) // 100 - -**/ - -(function (g) { - var r = /(\d*.?\d+)([mshd]+)/ - , _ = {} - - _.ms = 1; - _.s = 1000; - _.m = _.s * 60; - _.h = _.m * 60; - _.d = _.h * 24; - - function ms (s) { - if (s == Number(s)) return Number(s); - r.exec(s.toLowerCase()); - return RegExp.$1 * _[RegExp.$2]; - } - - g.top ? g.ms = ms : module.exports = ms; -})(this); diff --git a/node_modules/mongoose/node_modules/ms/package.json b/node_modules/mongoose/node_modules/ms/package.json deleted file mode 100644 index fef38c189..000000000 --- a/node_modules/mongoose/node_modules/ms/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "ms", - "version": "0.1.0", - "description": "Tiny ms conversion utility", - "main": "./ms", - "devDependencies": { - "mocha": "*", - "expect.js": "*", - "serve": "*" - }, - "readme": "\n# ms.js\n\nEver find yourself doing math in your head or writing `1000 * 60 * 60 …`?\nDon't want to add obstrusive `Number` prototype extensions to your reusable\n/ distributable modules and projects?\n\n`ms` is a tiny utility that you can leverage when your application needs to\naccept a number of miliseconds as a parameter.\n\nIf a number is supplied to `ms`, it returns it immediately (e.g:\nIf a string that contains the number is supplied, it returns it immediately as\na number (e.g: it returns `100` for `'100'`).\n\nHowever, if you pass a string with a number and a valid unit, hte number of\nequivalent ms is returned.\n\n```js\nms('1d') // 86400000\nms('10h') // 36000000\nms('2h') // 7200000\nms('1m') // 60000\nms('5ms') // 5000\nms('100') // '100'\nms(100) // 100\n```\n\n## How to use\n\n### Node\n\n```js\nrequire('ms')\n```\n\n### Browser\n\n```html\n\n```\n\n## Credits\n\n(The MIT License)\n\nCopyright (c) 2011 Guillermo Rauch <guillermo@learnboost.com>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "README.md", - "_id": "ms@0.1.0", - "dist": { - "shasum": "a9cafc1b4536e693677598b9b375690ab208fab8" - }, - "_from": "ms@0.1.0", - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.1.0.tgz" -} diff --git a/node_modules/mongoose/node_modules/ms/test/index.html b/node_modules/mongoose/node_modules/ms/test/index.html deleted file mode 100644 index 79edc4092..000000000 --- a/node_modules/mongoose/node_modules/ms/test/index.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - ms.js tests - - - - - - - - - - - - -
    - - diff --git a/node_modules/mongoose/node_modules/ms/test/support/jquery.js b/node_modules/mongoose/node_modules/ms/test/support/jquery.js deleted file mode 100644 index 8ccd0ea78..000000000 --- a/node_modules/mongoose/node_modules/ms/test/support/jquery.js +++ /dev/null @@ -1,9266 +0,0 @@ -/*! - * jQuery JavaScript Library v1.7.1 - * http://jquery.com/ - * - * Copyright 2011, John Resig - * Dual licensed under the MIT or GPL Version 2 licenses. - * http://jquery.org/license - * - * Includes Sizzle.js - * http://sizzlejs.com/ - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * - * Date: Mon Nov 21 21:11:03 2011 -0500 - */ -(function( window, undefined ) { - -// Use the correct document accordingly with window argument (sandbox) -var document = window.document, - navigator = window.navigator, - location = window.location; -var jQuery = (function() { - -// Define a local copy of jQuery -var jQuery = function( selector, context ) { - // The jQuery object is actually just the init constructor 'enhanced' - return new jQuery.fn.init( selector, context, rootjQuery ); - }, - - // Map over jQuery in case of overwrite - _jQuery = window.jQuery, - - // Map over the $ in case of overwrite - _$ = window.$, - - // A central reference to the root jQuery(document) - rootjQuery, - - // A simple way to check for HTML strings or ID strings - // Prioritize #id over to avoid XSS via location.hash (#9521) - quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, - - // Check if a string has a non-whitespace character in it - rnotwhite = /\S/, - - // Used for trimming whitespace - trimLeft = /^\s+/, - trimRight = /\s+$/, - - // Match a standalone tag - rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, - - // JSON RegExp - rvalidchars = /^[\],:{}\s]*$/, - rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, - rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, - rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, - - // Useragent RegExp - rwebkit = /(webkit)[ \/]([\w.]+)/, - ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, - rmsie = /(msie) ([\w.]+)/, - rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, - - // Matches dashed string for camelizing - rdashAlpha = /-([a-z]|[0-9])/ig, - rmsPrefix = /^-ms-/, - - // Used by jQuery.camelCase as callback to replace() - fcamelCase = function( all, letter ) { - return ( letter + "" ).toUpperCase(); - }, - - // Keep a UserAgent string for use with jQuery.browser - userAgent = navigator.userAgent, - - // For matching the engine and version of the browser - browserMatch, - - // The deferred used on DOM ready - readyList, - - // The ready event handler - DOMContentLoaded, - - // Save a reference to some core methods - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty, - push = Array.prototype.push, - slice = Array.prototype.slice, - trim = String.prototype.trim, - indexOf = Array.prototype.indexOf, - - // [[Class]] -> type pairs - class2type = {}; - -jQuery.fn = jQuery.prototype = { - constructor: jQuery, - init: function( selector, context, rootjQuery ) { - var match, elem, ret, doc; - - // Handle $(""), $(null), or $(undefined) - if ( !selector ) { - return this; - } - - // Handle $(DOMElement) - if ( selector.nodeType ) { - this.context = this[0] = selector; - this.length = 1; - return this; - } - - // The body element only exists once, optimize finding it - if ( selector === "body" && !context && document.body ) { - this.context = document; - this[0] = document.body; - this.selector = selector; - this.length = 1; - return this; - } - - // Handle HTML strings - if ( typeof selector === "string" ) { - // Are we dealing with HTML string or an ID? - if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { - // Assume that strings that start and end with <> are HTML and skip the regex check - match = [ null, selector, null ]; - - } else { - match = quickExpr.exec( selector ); - } - - // Verify a match, and that no context was specified for #id - if ( match && (match[1] || !context) ) { - - // HANDLE: $(html) -> $(array) - if ( match[1] ) { - context = context instanceof jQuery ? context[0] : context; - doc = ( context ? context.ownerDocument || context : document ); - - // If a single string is passed in and it's a single tag - // just do a createElement and skip the rest - ret = rsingleTag.exec( selector ); - - if ( ret ) { - if ( jQuery.isPlainObject( context ) ) { - selector = [ document.createElement( ret[1] ) ]; - jQuery.fn.attr.call( selector, context, true ); - - } else { - selector = [ doc.createElement( ret[1] ) ]; - } - - } else { - ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); - selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; - } - - return jQuery.merge( this, selector ); - - // HANDLE: $("#id") - } else { - elem = document.getElementById( match[2] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id !== match[2] ) { - return rootjQuery.find( selector ); - } - - // Otherwise, we inject the element directly into the jQuery object - this.length = 1; - this[0] = elem; - } - - this.context = document; - this.selector = selector; - return this; - } - - // HANDLE: $(expr, $(...)) - } else if ( !context || context.jquery ) { - return ( context || rootjQuery ).find( selector ); - - // HANDLE: $(expr, context) - // (which is just equivalent to: $(context).find(expr) - } else { - return this.constructor( context ).find( selector ); - } - - // HANDLE: $(function) - // Shortcut for document ready - } else if ( jQuery.isFunction( selector ) ) { - return rootjQuery.ready( selector ); - } - - if ( selector.selector !== undefined ) { - this.selector = selector.selector; - this.context = selector.context; - } - - return jQuery.makeArray( selector, this ); - }, - - // Start with an empty selector - selector: "", - - // The current version of jQuery being used - jquery: "1.7.1", - - // The default length of a jQuery object is 0 - length: 0, - - // The number of elements contained in the matched element set - size: function() { - return this.length; - }, - - toArray: function() { - return slice.call( this, 0 ); - }, - - // Get the Nth element in the matched element set OR - // Get the whole matched element set as a clean array - get: function( num ) { - return num == null ? - - // Return a 'clean' array - this.toArray() : - - // Return just the object - ( num < 0 ? this[ this.length + num ] : this[ num ] ); - }, - - // Take an array of elements and push it onto the stack - // (returning the new matched element set) - pushStack: function( elems, name, selector ) { - // Build a new jQuery matched element set - var ret = this.constructor(); - - if ( jQuery.isArray( elems ) ) { - push.apply( ret, elems ); - - } else { - jQuery.merge( ret, elems ); - } - - // Add the old object onto the stack (as a reference) - ret.prevObject = this; - - ret.context = this.context; - - if ( name === "find" ) { - ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; - } else if ( name ) { - ret.selector = this.selector + "." + name + "(" + selector + ")"; - } - - // Return the newly-formed element set - return ret; - }, - - // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); - }, - - ready: function( fn ) { - // Attach the listeners - jQuery.bindReady(); - - // Add the callback - readyList.add( fn ); - - return this; - }, - - eq: function( i ) { - i = +i; - return i === -1 ? - this.slice( i ) : - this.slice( i, i + 1 ); - }, - - first: function() { - return this.eq( 0 ); - }, - - last: function() { - return this.eq( -1 ); - }, - - slice: function() { - return this.pushStack( slice.apply( this, arguments ), - "slice", slice.call(arguments).join(",") ); - }, - - map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { - return callback.call( elem, i, elem ); - })); - }, - - end: function() { - return this.prevObject || this.constructor(null); - }, - - // For internal use only. - // Behaves like an Array's method, not like a jQuery method. - push: push, - sort: [].sort, - splice: [].splice -}; - -// Give the init function the jQuery prototype for later instantiation -jQuery.fn.init.prototype = jQuery.fn; - -jQuery.extend = jQuery.fn.extend = function() { - var options, name, src, copy, copyIsArray, clone, - target = arguments[0] || {}, - i = 1, - length = arguments.length, - deep = false; - - // Handle a deep copy situation - if ( typeof target === "boolean" ) { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - - // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { - target = {}; - } - - // extend jQuery itself if only one argument is passed - if ( length === i ) { - target = this; - --i; - } - - for ( ; i < length; i++ ) { - // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { - // Extend the base object - for ( name in options ) { - src = target[ name ]; - copy = options[ name ]; - - // Prevent never-ending loop - if ( target === copy ) { - continue; - } - - // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { - if ( copyIsArray ) { - copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; - - } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - target[ name ] = jQuery.extend( deep, clone, copy ); - - // Don't bring in undefined values - } else if ( copy !== undefined ) { - target[ name ] = copy; - } - } - } - } - - // Return the modified object - return target; -}; - -jQuery.extend({ - noConflict: function( deep ) { - if ( window.$ === jQuery ) { - window.$ = _$; - } - - if ( deep && window.jQuery === jQuery ) { - window.jQuery = _jQuery; - } - - return jQuery; - }, - - // Is the DOM ready to be used? Set to true once it occurs. - isReady: false, - - // A counter to track how many items to wait for before - // the ready event fires. See #6781 - readyWait: 1, - - // Hold (or release) the ready event - holdReady: function( hold ) { - if ( hold ) { - jQuery.readyWait++; - } else { - jQuery.ready( true ); - } - }, - - // Handle when the DOM is ready - ready: function( wait ) { - // Either a released hold or an DOMready/load event and not yet ready - if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( !document.body ) { - return setTimeout( jQuery.ready, 1 ); - } - - // Remember that the DOM is ready - jQuery.isReady = true; - - // If a normal DOM Ready event fired, decrement, and wait if need be - if ( wait !== true && --jQuery.readyWait > 0 ) { - return; - } - - // If there are functions bound, to execute - readyList.fireWith( document, [ jQuery ] ); - - // Trigger any bound ready events - if ( jQuery.fn.trigger ) { - jQuery( document ).trigger( "ready" ).off( "ready" ); - } - } - }, - - bindReady: function() { - if ( readyList ) { - return; - } - - readyList = jQuery.Callbacks( "once memory" ); - - // Catch cases where $(document).ready() is called after the - // browser event has already occurred. - if ( document.readyState === "complete" ) { - // Handle it asynchronously to allow scripts the opportunity to delay ready - return setTimeout( jQuery.ready, 1 ); - } - - // Mozilla, Opera and webkit nightlies currently support this event - if ( document.addEventListener ) { - // Use the handy event callback - document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - - // A fallback to window.onload, that will always work - window.addEventListener( "load", jQuery.ready, false ); - - // If IE event model is used - } else if ( document.attachEvent ) { - // ensure firing before onload, - // maybe late but safe also for iframes - document.attachEvent( "onreadystatechange", DOMContentLoaded ); - - // A fallback to window.onload, that will always work - window.attachEvent( "onload", jQuery.ready ); - - // If IE and not a frame - // continually check to see if the document is ready - var toplevel = false; - - try { - toplevel = window.frameElement == null; - } catch(e) {} - - if ( document.documentElement.doScroll && toplevel ) { - doScrollCheck(); - } - } - }, - - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). - isFunction: function( obj ) { - return jQuery.type(obj) === "function"; - }, - - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, - - // A crude way of determining if an object is a window - isWindow: function( obj ) { - return obj && typeof obj === "object" && "setInterval" in obj; - }, - - isNumeric: function( obj ) { - return !isNaN( parseFloat(obj) ) && isFinite( obj ); - }, - - type: function( obj ) { - return obj == null ? - String( obj ) : - class2type[ toString.call(obj) ] || "object"; - }, - - isPlainObject: function( obj ) { - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { - return false; - } - - try { - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - - var key; - for ( key in obj ) {} - - return key === undefined || hasOwn.call( obj, key ); - }, - - isEmptyObject: function( obj ) { - for ( var name in obj ) { - return false; - } - return true; - }, - - error: function( msg ) { - throw new Error( msg ); - }, - - parseJSON: function( data ) { - if ( typeof data !== "string" || !data ) { - return null; - } - - // Make sure leading/trailing whitespace is removed (IE can't handle it) - data = jQuery.trim( data ); - - // Attempt to parse using the native JSON parser first - if ( window.JSON && window.JSON.parse ) { - return window.JSON.parse( data ); - } - - // Make sure the incoming data is actual JSON - // Logic borrowed from http://json.org/json2.js - if ( rvalidchars.test( data.replace( rvalidescape, "@" ) - .replace( rvalidtokens, "]" ) - .replace( rvalidbraces, "")) ) { - - return ( new Function( "return " + data ) )(); - - } - jQuery.error( "Invalid JSON: " + data ); - }, - - // Cross-browser xml parsing - parseXML: function( data ) { - var xml, tmp; - try { - if ( window.DOMParser ) { // Standard - tmp = new DOMParser(); - xml = tmp.parseFromString( data , "text/xml" ); - } else { // IE - xml = new ActiveXObject( "Microsoft.XMLDOM" ); - xml.async = "false"; - xml.loadXML( data ); - } - } catch( e ) { - xml = undefined; - } - if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { - jQuery.error( "Invalid XML: " + data ); - } - return xml; - }, - - noop: function() {}, - - // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && rnotwhite.test( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } - }, - - // Convert dashed to camelCase; used by the css and data modules - // Microsoft forgot to hump their vendor prefix (#9572) - camelCase: function( string ) { - return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); - }, - - nodeName: function( elem, name ) { - return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); - }, - - // args is for internal usage only - each: function( object, callback, args ) { - var name, i = 0, - length = object.length, - isObj = length === undefined || jQuery.isFunction( object ); - - if ( args ) { - if ( isObj ) { - for ( name in object ) { - if ( callback.apply( object[ name ], args ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.apply( object[ i++ ], args ) === false ) { - break; - } - } - } - - // A special, fast, case for the most common use of each - } else { - if ( isObj ) { - for ( name in object ) { - if ( callback.call( object[ name ], name, object[ name ] ) === false ) { - break; - } - } - } else { - for ( ; i < length; ) { - if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { - break; - } - } - } - } - - return object; - }, - - // Use native String.trim function wherever possible - trim: trim ? - function( text ) { - return text == null ? - "" : - trim.call( text ); - } : - - // Otherwise use our own trimming functionality - function( text ) { - return text == null ? - "" : - text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); - }, - - // results is for internal usage only - makeArray: function( array, results ) { - var ret = results || []; - - if ( array != null ) { - // The window, strings (and functions) also have 'length' - // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 - var type = jQuery.type( array ); - - if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { - push.call( ret, array ); - } else { - jQuery.merge( ret, array ); - } - } - - return ret; - }, - - inArray: function( elem, array, i ) { - var len; - - if ( array ) { - if ( indexOf ) { - return indexOf.call( array, elem, i ); - } - - len = array.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in array && array[ i ] === elem ) { - return i; - } - } - } - - return -1; - }, - - merge: function( first, second ) { - var i = first.length, - j = 0; - - if ( typeof second.length === "number" ) { - for ( var l = second.length; j < l; j++ ) { - first[ i++ ] = second[ j ]; - } - - } else { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } - } - - first.length = i; - - return first; - }, - - grep: function( elems, callback, inv ) { - var ret = [], retVal; - inv = !!inv; - - // Go through the array, only saving the items - // that pass the validator function - for ( var i = 0, length = elems.length; i < length; i++ ) { - retVal = !!callback( elems[ i ], i ); - if ( inv !== retVal ) { - ret.push( elems[ i ] ); - } - } - - return ret; - }, - - // arg is for internal usage only - map: function( elems, callback, arg ) { - var value, key, ret = [], - i = 0, - length = elems.length, - // jquery objects are treated as arrays - isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; - - // Go through the array, translating each of the items to their - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback( elems[ i ], i, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - - // Go through every key on the object, - } else { - for ( key in elems ) { - value = callback( elems[ key ], key, arg ); - - if ( value != null ) { - ret[ ret.length ] = value; - } - } - } - - // Flatten any nested arrays - return ret.concat.apply( [], ret ); - }, - - // A global GUID counter for objects - guid: 1, - - // Bind a function to a context, optionally partially applying any - // arguments. - proxy: function( fn, context ) { - if ( typeof context === "string" ) { - var tmp = fn[ context ]; - context = fn; - fn = tmp; - } - - // Quick check to determine if target is callable, in the spec - // this throws a TypeError, but we will just return undefined. - if ( !jQuery.isFunction( fn ) ) { - return undefined; - } - - // Simulated bind - var args = slice.call( arguments, 2 ), - proxy = function() { - return fn.apply( context, args.concat( slice.call( arguments ) ) ); - }; - - // Set the guid of unique handler to the same of original handler, so it can be removed - proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; - - return proxy; - }, - - // Mutifunctional method to get and set values to a collection - // The value/s can optionally be executed if it's a function - access: function( elems, key, value, exec, fn, pass ) { - var length = elems.length; - - // Setting many attributes - if ( typeof key === "object" ) { - for ( var k in key ) { - jQuery.access( elems, k, key[k], exec, fn, value ); - } - return elems; - } - - // Setting one attribute - if ( value !== undefined ) { - // Optionally, function values get executed if exec is true - exec = !pass && exec && jQuery.isFunction(value); - - for ( var i = 0; i < length; i++ ) { - fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); - } - - return elems; - } - - // Getting an attribute - return length ? fn( elems[0], key ) : undefined; - }, - - now: function() { - return ( new Date() ).getTime(); - }, - - // Use of jQuery.browser is frowned upon. - // More details: http://docs.jquery.com/Utilities/jQuery.browser - uaMatch: function( ua ) { - ua = ua.toLowerCase(); - - var match = rwebkit.exec( ua ) || - ropera.exec( ua ) || - rmsie.exec( ua ) || - ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || - []; - - return { browser: match[1] || "", version: match[2] || "0" }; - }, - - sub: function() { - function jQuerySub( selector, context ) { - return new jQuerySub.fn.init( selector, context ); - } - jQuery.extend( true, jQuerySub, this ); - jQuerySub.superclass = this; - jQuerySub.fn = jQuerySub.prototype = this(); - jQuerySub.fn.constructor = jQuerySub; - jQuerySub.sub = this.sub; - jQuerySub.fn.init = function init( selector, context ) { - if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { - context = jQuerySub( context ); - } - - return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); - }; - jQuerySub.fn.init.prototype = jQuerySub.fn; - var rootjQuerySub = jQuerySub(document); - return jQuerySub; - }, - - browser: {} -}); - -// Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { - class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); - -browserMatch = jQuery.uaMatch( userAgent ); -if ( browserMatch.browser ) { - jQuery.browser[ browserMatch.browser ] = true; - jQuery.browser.version = browserMatch.version; -} - -// Deprecated, use jQuery.browser.webkit instead -if ( jQuery.browser.webkit ) { - jQuery.browser.safari = true; -} - -// IE doesn't match non-breaking spaces with \s -if ( rnotwhite.test( "\xA0" ) ) { - trimLeft = /^[\s\xA0]+/; - trimRight = /[\s\xA0]+$/; -} - -// All jQuery objects should point back to these -rootjQuery = jQuery(document); - -// Cleanup functions for the document ready method -if ( document.addEventListener ) { - DOMContentLoaded = function() { - document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); - jQuery.ready(); - }; - -} else if ( document.attachEvent ) { - DOMContentLoaded = function() { - // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). - if ( document.readyState === "complete" ) { - document.detachEvent( "onreadystatechange", DOMContentLoaded ); - jQuery.ready(); - } - }; -} - -// The DOM ready check for Internet Explorer -function doScrollCheck() { - if ( jQuery.isReady ) { - return; - } - - try { - // If IE is used, use the trick by Diego Perini - // http://javascript.nwbox.com/IEContentLoaded/ - document.documentElement.doScroll("left"); - } catch(e) { - setTimeout( doScrollCheck, 1 ); - return; - } - - // and execute any waiting functions - jQuery.ready(); -} - -return jQuery; - -})(); - - -// String to Object flags format cache -var flagsCache = {}; - -// Convert String-formatted flags into Object-formatted ones and store in cache -function createFlags( flags ) { - var object = flagsCache[ flags ] = {}, - i, length; - flags = flags.split( /\s+/ ); - for ( i = 0, length = flags.length; i < length; i++ ) { - object[ flags[i] ] = true; - } - return object; -} - -/* - * Create a callback list using the following parameters: - * - * flags: an optional list of space-separated flags that will change how - * the callback list behaves - * - * By default a callback list will act like an event callback list and can be - * "fired" multiple times. - * - * Possible flags: - * - * once: will ensure the callback list can only be fired once (like a Deferred) - * - * memory: will keep track of previous values and will call any callback added - * after the list has been fired right away with the latest "memorized" - * values (like a Deferred) - * - * unique: will ensure a callback can only be added once (no duplicate in the list) - * - * stopOnFalse: interrupt callings when a callback returns false - * - */ -jQuery.Callbacks = function( flags ) { - - // Convert flags from String-formatted to Object-formatted - // (we check in cache first) - flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; - - var // Actual callback list - list = [], - // Stack of fire calls for repeatable lists - stack = [], - // Last fire value (for non-forgettable lists) - memory, - // Flag to know if list is currently firing - firing, - // First callback to fire (used internally by add and fireWith) - firingStart, - // End of the loop when firing - firingLength, - // Index of currently firing callback (modified by remove if needed) - firingIndex, - // Add one or several callbacks to the list - add = function( args ) { - var i, - length, - elem, - type, - actual; - for ( i = 0, length = args.length; i < length; i++ ) { - elem = args[ i ]; - type = jQuery.type( elem ); - if ( type === "array" ) { - // Inspect recursively - add( elem ); - } else if ( type === "function" ) { - // Add if not in unique mode and callback is not in - if ( !flags.unique || !self.has( elem ) ) { - list.push( elem ); - } - } - } - }, - // Fire callbacks - fire = function( context, args ) { - args = args || []; - memory = !flags.memory || [ context, args ]; - firing = true; - firingIndex = firingStart || 0; - firingStart = 0; - firingLength = list.length; - for ( ; list && firingIndex < firingLength; firingIndex++ ) { - if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { - memory = true; // Mark as halted - break; - } - } - firing = false; - if ( list ) { - if ( !flags.once ) { - if ( stack && stack.length ) { - memory = stack.shift(); - self.fireWith( memory[ 0 ], memory[ 1 ] ); - } - } else if ( memory === true ) { - self.disable(); - } else { - list = []; - } - } - }, - // Actual Callbacks object - self = { - // Add a callback or a collection of callbacks to the list - add: function() { - if ( list ) { - var length = list.length; - add( arguments ); - // Do we need to add the callbacks to the - // current firing batch? - if ( firing ) { - firingLength = list.length; - // With memory, if we're not firing then - // we should call right away, unless previous - // firing was halted (stopOnFalse) - } else if ( memory && memory !== true ) { - firingStart = length; - fire( memory[ 0 ], memory[ 1 ] ); - } - } - return this; - }, - // Remove a callback from the list - remove: function() { - if ( list ) { - var args = arguments, - argIndex = 0, - argLength = args.length; - for ( ; argIndex < argLength ; argIndex++ ) { - for ( var i = 0; i < list.length; i++ ) { - if ( args[ argIndex ] === list[ i ] ) { - // Handle firingIndex and firingLength - if ( firing ) { - if ( i <= firingLength ) { - firingLength--; - if ( i <= firingIndex ) { - firingIndex--; - } - } - } - // Remove the element - list.splice( i--, 1 ); - // If we have some unicity property then - // we only need to do this once - if ( flags.unique ) { - break; - } - } - } - } - } - return this; - }, - // Control if a given callback is in the list - has: function( fn ) { - if ( list ) { - var i = 0, - length = list.length; - for ( ; i < length; i++ ) { - if ( fn === list[ i ] ) { - return true; - } - } - } - return false; - }, - // Remove all callbacks from the list - empty: function() { - list = []; - return this; - }, - // Have the list do nothing anymore - disable: function() { - list = stack = memory = undefined; - return this; - }, - // Is it disabled? - disabled: function() { - return !list; - }, - // Lock the list in its current state - lock: function() { - stack = undefined; - if ( !memory || memory === true ) { - self.disable(); - } - return this; - }, - // Is it locked? - locked: function() { - return !stack; - }, - // Call all callbacks with the given context and arguments - fireWith: function( context, args ) { - if ( stack ) { - if ( firing ) { - if ( !flags.once ) { - stack.push( [ context, args ] ); - } - } else if ( !( flags.once && memory ) ) { - fire( context, args ); - } - } - return this; - }, - // Call all the callbacks with the given arguments - fire: function() { - self.fireWith( this, arguments ); - return this; - }, - // To know if the callbacks have already been called at least once - fired: function() { - return !!memory; - } - }; - - return self; -}; - - - - -var // Static reference to slice - sliceDeferred = [].slice; - -jQuery.extend({ - - Deferred: function( func ) { - var doneList = jQuery.Callbacks( "once memory" ), - failList = jQuery.Callbacks( "once memory" ), - progressList = jQuery.Callbacks( "memory" ), - state = "pending", - lists = { - resolve: doneList, - reject: failList, - notify: progressList - }, - promise = { - done: doneList.add, - fail: failList.add, - progress: progressList.add, - - state: function() { - return state; - }, - - // Deprecated - isResolved: doneList.fired, - isRejected: failList.fired, - - then: function( doneCallbacks, failCallbacks, progressCallbacks ) { - deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); - return this; - }, - always: function() { - deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); - return this; - }, - pipe: function( fnDone, fnFail, fnProgress ) { - return jQuery.Deferred(function( newDefer ) { - jQuery.each( { - done: [ fnDone, "resolve" ], - fail: [ fnFail, "reject" ], - progress: [ fnProgress, "notify" ] - }, function( handler, data ) { - var fn = data[ 0 ], - action = data[ 1 ], - returned; - if ( jQuery.isFunction( fn ) ) { - deferred[ handler ](function() { - returned = fn.apply( this, arguments ); - if ( returned && jQuery.isFunction( returned.promise ) ) { - returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); - } else { - newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); - } - }); - } else { - deferred[ handler ]( newDefer[ action ] ); - } - }); - }).promise(); - }, - // Get a promise for this deferred - // If obj is provided, the promise aspect is added to the object - promise: function( obj ) { - if ( obj == null ) { - obj = promise; - } else { - for ( var key in promise ) { - obj[ key ] = promise[ key ]; - } - } - return obj; - } - }, - deferred = promise.promise({}), - key; - - for ( key in lists ) { - deferred[ key ] = lists[ key ].fire; - deferred[ key + "With" ] = lists[ key ].fireWith; - } - - // Handle state - deferred.done( function() { - state = "resolved"; - }, failList.disable, progressList.lock ).fail( function() { - state = "rejected"; - }, doneList.disable, progressList.lock ); - - // Call given func if any - if ( func ) { - func.call( deferred, deferred ); - } - - // All done! - return deferred; - }, - - // Deferred helper - when: function( firstParam ) { - var args = sliceDeferred.call( arguments, 0 ), - i = 0, - length = args.length, - pValues = new Array( length ), - count = length, - pCount = length, - deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? - firstParam : - jQuery.Deferred(), - promise = deferred.promise(); - function resolveFunc( i ) { - return function( value ) { - args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - if ( !( --count ) ) { - deferred.resolveWith( deferred, args ); - } - }; - } - function progressFunc( i ) { - return function( value ) { - pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; - deferred.notifyWith( promise, pValues ); - }; - } - if ( length > 1 ) { - for ( ; i < length; i++ ) { - if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { - args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); - } else { - --count; - } - } - if ( !count ) { - deferred.resolveWith( deferred, args ); - } - } else if ( deferred !== firstParam ) { - deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); - } - return promise; - } -}); - - - - -jQuery.support = (function() { - - var support, - all, - a, - select, - opt, - input, - marginDiv, - fragment, - tds, - events, - eventName, - i, - isSupported, - div = document.createElement( "div" ), - documentElement = document.documentElement; - - // Preliminary tests - div.setAttribute("className", "t"); - div.innerHTML = "
    a"; - - all = div.getElementsByTagName( "*" ); - a = div.getElementsByTagName( "a" )[ 0 ]; - - // Can't get basic test support - if ( !all || !all.length || !a ) { - return {}; - } - - // First batch of supports tests - select = document.createElement( "select" ); - opt = select.appendChild( document.createElement("option") ); - input = div.getElementsByTagName( "input" )[ 0 ]; - - support = { - // IE strips leading whitespace when .innerHTML is used - leadingWhitespace: ( div.firstChild.nodeType === 3 ), - - // Make sure that tbody elements aren't automatically inserted - // IE will insert them into empty tables - tbody: !div.getElementsByTagName("tbody").length, - - // Make sure that link elements get serialized correctly by innerHTML - // This requires a wrapper element in IE - htmlSerialize: !!div.getElementsByTagName("link").length, - - // Get the style information from getAttribute - // (IE uses .cssText instead) - style: /top/.test( a.getAttribute("style") ), - - // Make sure that URLs aren't manipulated - // (IE normalizes it by default) - hrefNormalized: ( a.getAttribute("href") === "/a" ), - - // Make sure that element opacity exists - // (IE uses filter instead) - // Use a regex to work around a WebKit issue. See #5145 - opacity: /^0.55/.test( a.style.opacity ), - - // Verify style float existence - // (IE uses styleFloat instead of cssFloat) - cssFloat: !!a.style.cssFloat, - - // Make sure that if no value is specified for a checkbox - // that it defaults to "on". - // (WebKit defaults to "" instead) - checkOn: ( input.value === "on" ), - - // Make sure that a selected-by-default option has a working selected property. - // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) - optSelected: opt.selected, - - // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) - getSetAttribute: div.className !== "t", - - // Tests for enctype support on a form(#6743) - enctype: !!document.createElement("form").enctype, - - // Makes sure cloning an html5 element does not cause problems - // Where outerHTML is undefined, this still works - html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", - - // Will be defined later - submitBubbles: true, - changeBubbles: true, - focusinBubbles: false, - deleteExpando: true, - noCloneEvent: true, - inlineBlockNeedsLayout: false, - shrinkWrapBlocks: false, - reliableMarginRight: true - }; - - // Make sure checked status is properly cloned - input.checked = true; - support.noCloneChecked = input.cloneNode( true ).checked; - - // Make sure that the options inside disabled selects aren't marked as disabled - // (WebKit marks them as disabled) - select.disabled = true; - support.optDisabled = !opt.disabled; - - // Test to see if it's possible to delete an expando from an element - // Fails in Internet Explorer - try { - delete div.test; - } catch( e ) { - support.deleteExpando = false; - } - - if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { - div.attachEvent( "onclick", function() { - // Cloning a node shouldn't copy over any - // bound event handlers (IE does this) - support.noCloneEvent = false; - }); - div.cloneNode( true ).fireEvent( "onclick" ); - } - - // Check if a radio maintains its value - // after being appended to the DOM - input = document.createElement("input"); - input.value = "t"; - input.setAttribute("type", "radio"); - support.radioValue = input.value === "t"; - - input.setAttribute("checked", "checked"); - div.appendChild( input ); - fragment = document.createDocumentFragment(); - fragment.appendChild( div.lastChild ); - - // WebKit doesn't clone checked state correctly in fragments - support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; - - // Check if a disconnected checkbox will retain its checked - // value of true after appended to the DOM (IE6/7) - support.appendChecked = input.checked; - - fragment.removeChild( input ); - fragment.appendChild( div ); - - div.innerHTML = ""; - - // Check if div with explicit width and no margin-right incorrectly - // gets computed margin-right based on width of container. For more - // info see bug #3333 - // Fails in WebKit before Feb 2011 nightlies - // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right - if ( window.getComputedStyle ) { - marginDiv = document.createElement( "div" ); - marginDiv.style.width = "0"; - marginDiv.style.marginRight = "0"; - div.style.width = "2px"; - div.appendChild( marginDiv ); - support.reliableMarginRight = - ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; - } - - // Technique from Juriy Zaytsev - // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ - // We only care about the case where non-standard event systems - // are used, namely in IE. Short-circuiting here helps us to - // avoid an eval call (in setAttribute) which can cause CSP - // to go haywire. See: https://developer.mozilla.org/en/Security/CSP - if ( div.attachEvent ) { - for( i in { - submit: 1, - change: 1, - focusin: 1 - }) { - eventName = "on" + i; - isSupported = ( eventName in div ); - if ( !isSupported ) { - div.setAttribute( eventName, "return;" ); - isSupported = ( typeof div[ eventName ] === "function" ); - } - support[ i + "Bubbles" ] = isSupported; - } - } - - fragment.removeChild( div ); - - // Null elements to avoid leaks in IE - fragment = select = opt = marginDiv = div = input = null; - - // Run tests that need a body at doc ready - jQuery(function() { - var container, outer, inner, table, td, offsetSupport, - conMarginTop, ptlm, vb, style, html, - body = document.getElementsByTagName("body")[0]; - - if ( !body ) { - // Return for frameset docs that don't have a body - return; - } - - conMarginTop = 1; - ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; - vb = "visibility:hidden;border:0;"; - style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; - html = "
    " + - "" + - "
    "; - - container = document.createElement("div"); - container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; - body.insertBefore( container, body.firstChild ); - - // Construct the test element - div = document.createElement("div"); - container.appendChild( div ); - - // Check if table cells still have offsetWidth/Height when they are set - // to display:none and there are still other visible table cells in a - // table row; if so, offsetWidth/Height are not reliable for use when - // determining if an element has been hidden directly using - // display:none (it is still safe to use offsets if a parent element is - // hidden; don safety goggles and see bug #4512 for more information). - // (only IE 8 fails this test) - div.innerHTML = "
    t
    "; - tds = div.getElementsByTagName( "td" ); - isSupported = ( tds[ 0 ].offsetHeight === 0 ); - - tds[ 0 ].style.display = ""; - tds[ 1 ].style.display = "none"; - - // Check if empty table cells still have offsetWidth/Height - // (IE <= 8 fail this test) - support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); - - // Figure out if the W3C box model works as expected - div.innerHTML = ""; - div.style.width = div.style.paddingLeft = "1px"; - jQuery.boxModel = support.boxModel = div.offsetWidth === 2; - - if ( typeof div.style.zoom !== "undefined" ) { - // Check if natively block-level elements act like inline-block - // elements when setting their display to 'inline' and giving - // them layout - // (IE < 8 does this) - div.style.display = "inline"; - div.style.zoom = 1; - support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); - - // Check if elements with layout shrink-wrap their children - // (IE 6 does this) - div.style.display = ""; - div.innerHTML = "
    "; - support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); - } - - div.style.cssText = ptlm + vb; - div.innerHTML = html; - - outer = div.firstChild; - inner = outer.firstChild; - td = outer.nextSibling.firstChild.firstChild; - - offsetSupport = { - doesNotAddBorder: ( inner.offsetTop !== 5 ), - doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) - }; - - inner.style.position = "fixed"; - inner.style.top = "20px"; - - // safari subtracts parent border width here which is 5px - offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); - inner.style.position = inner.style.top = ""; - - outer.style.overflow = "hidden"; - outer.style.position = "relative"; - - offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); - offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); - - body.removeChild( container ); - div = container = null; - - jQuery.extend( support, offsetSupport ); - }); - - return support; -})(); - - - - -var rbrace = /^(?:\{.*\}|\[.*\])$/, - rmultiDash = /([A-Z])/g; - -jQuery.extend({ - cache: {}, - - // Please use with caution - uuid: 0, - - // Unique for each copy of jQuery on the page - // Non-digits removed to match rinlinejQuery - expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), - - // The following elements throw uncatchable exceptions if you - // attempt to add expando properties to them. - noData: { - "embed": true, - // Ban all objects except for Flash (which handle expandos) - "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", - "applet": true - }, - - hasData: function( elem ) { - elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; - return !!elem && !isEmptyDataObject( elem ); - }, - - data: function( elem, name, data, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var privateCache, thisCache, ret, - internalKey = jQuery.expando, - getByName = typeof name === "string", - - // We have to handle DOM nodes and JS objects differently because IE6-7 - // can't GC object references properly across the DOM-JS boundary - isNode = elem.nodeType, - - // Only DOM nodes need the global jQuery cache; JS object data is - // attached directly to the object so GC can occur automatically - cache = isNode ? jQuery.cache : elem, - - // Only defining an ID for JS objects if its cache already exists allows - // the code to shortcut on the same path as a DOM node with no cache - id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, - isEvents = name === "events"; - - // Avoid doing any more work than we need to when trying to get data on an - // object that has no data at all - if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { - return; - } - - if ( !id ) { - // Only DOM nodes need a new unique ID for each element since their data - // ends up in the global cache - if ( isNode ) { - elem[ internalKey ] = id = ++jQuery.uuid; - } else { - id = internalKey; - } - } - - if ( !cache[ id ] ) { - cache[ id ] = {}; - - // Avoids exposing jQuery metadata on plain JS objects when the object - // is serialized using JSON.stringify - if ( !isNode ) { - cache[ id ].toJSON = jQuery.noop; - } - } - - // An object can be passed to jQuery.data instead of a key/value pair; this gets - // shallow copied over onto the existing cache - if ( typeof name === "object" || typeof name === "function" ) { - if ( pvt ) { - cache[ id ] = jQuery.extend( cache[ id ], name ); - } else { - cache[ id ].data = jQuery.extend( cache[ id ].data, name ); - } - } - - privateCache = thisCache = cache[ id ]; - - // jQuery data() is stored in a separate object inside the object's internal data - // cache in order to avoid key collisions between internal data and user-defined - // data. - if ( !pvt ) { - if ( !thisCache.data ) { - thisCache.data = {}; - } - - thisCache = thisCache.data; - } - - if ( data !== undefined ) { - thisCache[ jQuery.camelCase( name ) ] = data; - } - - // Users should not attempt to inspect the internal events object using jQuery.data, - // it is undocumented and subject to change. But does anyone listen? No. - if ( isEvents && !thisCache[ name ] ) { - return privateCache.events; - } - - // Check for both converted-to-camel and non-converted data property names - // If a data property was specified - if ( getByName ) { - - // First Try to find as-is property data - ret = thisCache[ name ]; - - // Test for null|undefined property data - if ( ret == null ) { - - // Try to find the camelCased property - ret = thisCache[ jQuery.camelCase( name ) ]; - } - } else { - ret = thisCache; - } - - return ret; - }, - - removeData: function( elem, name, pvt /* Internal Use Only */ ) { - if ( !jQuery.acceptData( elem ) ) { - return; - } - - var thisCache, i, l, - - // Reference to internal data cache key - internalKey = jQuery.expando, - - isNode = elem.nodeType, - - // See jQuery.data for more information - cache = isNode ? jQuery.cache : elem, - - // See jQuery.data for more information - id = isNode ? elem[ internalKey ] : internalKey; - - // If there is already no cache entry for this object, there is no - // purpose in continuing - if ( !cache[ id ] ) { - return; - } - - if ( name ) { - - thisCache = pvt ? cache[ id ] : cache[ id ].data; - - if ( thisCache ) { - - // Support array or space separated string names for data keys - if ( !jQuery.isArray( name ) ) { - - // try the string as a key before any manipulation - if ( name in thisCache ) { - name = [ name ]; - } else { - - // split the camel cased version by spaces unless a key with the spaces exists - name = jQuery.camelCase( name ); - if ( name in thisCache ) { - name = [ name ]; - } else { - name = name.split( " " ); - } - } - } - - for ( i = 0, l = name.length; i < l; i++ ) { - delete thisCache[ name[i] ]; - } - - // If there is no data left in the cache, we want to continue - // and let the cache object itself get destroyed - if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { - return; - } - } - } - - // See jQuery.data for more information - if ( !pvt ) { - delete cache[ id ].data; - - // Don't destroy the parent cache unless the internal data object - // had been the only thing left in it - if ( !isEmptyDataObject(cache[ id ]) ) { - return; - } - } - - // Browsers that fail expando deletion also refuse to delete expandos on - // the window, but it will allow it on all other JS objects; other browsers - // don't care - // Ensure that `cache` is not a window object #10080 - if ( jQuery.support.deleteExpando || !cache.setInterval ) { - delete cache[ id ]; - } else { - cache[ id ] = null; - } - - // We destroyed the cache and need to eliminate the expando on the node to avoid - // false lookups in the cache for entries that no longer exist - if ( isNode ) { - // IE does not allow us to delete expando properties from nodes, - // nor does it have a removeAttribute function on Document nodes; - // we must handle all of these cases - if ( jQuery.support.deleteExpando ) { - delete elem[ internalKey ]; - } else if ( elem.removeAttribute ) { - elem.removeAttribute( internalKey ); - } else { - elem[ internalKey ] = null; - } - } - }, - - // For internal use only. - _data: function( elem, name, data ) { - return jQuery.data( elem, name, data, true ); - }, - - // A method for determining if a DOM node can handle the data expando - acceptData: function( elem ) { - if ( elem.nodeName ) { - var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; - - if ( match ) { - return !(match === true || elem.getAttribute("classid") !== match); - } - } - - return true; - } -}); - -jQuery.fn.extend({ - data: function( key, value ) { - var parts, attr, name, - data = null; - - if ( typeof key === "undefined" ) { - if ( this.length ) { - data = jQuery.data( this[0] ); - - if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { - attr = this[0].attributes; - for ( var i = 0, l = attr.length; i < l; i++ ) { - name = attr[i].name; - - if ( name.indexOf( "data-" ) === 0 ) { - name = jQuery.camelCase( name.substring(5) ); - - dataAttr( this[0], name, data[ name ] ); - } - } - jQuery._data( this[0], "parsedAttrs", true ); - } - } - - return data; - - } else if ( typeof key === "object" ) { - return this.each(function() { - jQuery.data( this, key ); - }); - } - - parts = key.split("."); - parts[1] = parts[1] ? "." + parts[1] : ""; - - if ( value === undefined ) { - data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); - - // Try to fetch any internally stored data first - if ( data === undefined && this.length ) { - data = jQuery.data( this[0], key ); - data = dataAttr( this[0], key, data ); - } - - return data === undefined && parts[1] ? - this.data( parts[0] ) : - data; - - } else { - return this.each(function() { - var self = jQuery( this ), - args = [ parts[0], value ]; - - self.triggerHandler( "setData" + parts[1] + "!", args ); - jQuery.data( this, key, value ); - self.triggerHandler( "changeData" + parts[1] + "!", args ); - }); - } - }, - - removeData: function( key ) { - return this.each(function() { - jQuery.removeData( this, key ); - }); - } -}); - -function dataAttr( elem, key, data ) { - // If nothing was found internally, try to fetch any - // data from the HTML5 data-* attribute - if ( data === undefined && elem.nodeType === 1 ) { - - var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); - - data = elem.getAttribute( name ); - - if ( typeof data === "string" ) { - try { - data = data === "true" ? true : - data === "false" ? false : - data === "null" ? null : - jQuery.isNumeric( data ) ? parseFloat( data ) : - rbrace.test( data ) ? jQuery.parseJSON( data ) : - data; - } catch( e ) {} - - // Make sure we set the data so it isn't changed later - jQuery.data( elem, key, data ); - - } else { - data = undefined; - } - } - - return data; -} - -// checks a cache object for emptiness -function isEmptyDataObject( obj ) { - for ( var name in obj ) { - - // if the public data object is empty, the private is still empty - if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { - continue; - } - if ( name !== "toJSON" ) { - return false; - } - } - - return true; -} - - - - -function handleQueueMarkDefer( elem, type, src ) { - var deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - defer = jQuery._data( elem, deferDataKey ); - if ( defer && - ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && - ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { - // Give room for hard-coded callbacks to fire first - // and eventually mark/queue something else on the element - setTimeout( function() { - if ( !jQuery._data( elem, queueDataKey ) && - !jQuery._data( elem, markDataKey ) ) { - jQuery.removeData( elem, deferDataKey, true ); - defer.fire(); - } - }, 0 ); - } -} - -jQuery.extend({ - - _mark: function( elem, type ) { - if ( elem ) { - type = ( type || "fx" ) + "mark"; - jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); - } - }, - - _unmark: function( force, elem, type ) { - if ( force !== true ) { - type = elem; - elem = force; - force = false; - } - if ( elem ) { - type = type || "fx"; - var key = type + "mark", - count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); - if ( count ) { - jQuery._data( elem, key, count ); - } else { - jQuery.removeData( elem, key, true ); - handleQueueMarkDefer( elem, type, "mark" ); - } - } - }, - - queue: function( elem, type, data ) { - var q; - if ( elem ) { - type = ( type || "fx" ) + "queue"; - q = jQuery._data( elem, type ); - - // Speed up dequeue by getting out quickly if this is just a lookup - if ( data ) { - if ( !q || jQuery.isArray(data) ) { - q = jQuery._data( elem, type, jQuery.makeArray(data) ); - } else { - q.push( data ); - } - } - return q || []; - } - }, - - dequeue: function( elem, type ) { - type = type || "fx"; - - var queue = jQuery.queue( elem, type ), - fn = queue.shift(), - hooks = {}; - - // If the fx queue is dequeued, always remove the progress sentinel - if ( fn === "inprogress" ) { - fn = queue.shift(); - } - - if ( fn ) { - // Add a progress sentinel to prevent the fx queue from being - // automatically dequeued - if ( type === "fx" ) { - queue.unshift( "inprogress" ); - } - - jQuery._data( elem, type + ".run", hooks ); - fn.call( elem, function() { - jQuery.dequeue( elem, type ); - }, hooks ); - } - - if ( !queue.length ) { - jQuery.removeData( elem, type + "queue " + type + ".run", true ); - handleQueueMarkDefer( elem, type, "queue" ); - } - } -}); - -jQuery.fn.extend({ - queue: function( type, data ) { - if ( typeof type !== "string" ) { - data = type; - type = "fx"; - } - - if ( data === undefined ) { - return jQuery.queue( this[0], type ); - } - return this.each(function() { - var queue = jQuery.queue( this, type, data ); - - if ( type === "fx" && queue[0] !== "inprogress" ) { - jQuery.dequeue( this, type ); - } - }); - }, - dequeue: function( type ) { - return this.each(function() { - jQuery.dequeue( this, type ); - }); - }, - // Based off of the plugin by Clint Helfers, with permission. - // http://blindsignals.com/index.php/2009/07/jquery-delay/ - delay: function( time, type ) { - time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; - type = type || "fx"; - - return this.queue( type, function( next, hooks ) { - var timeout = setTimeout( next, time ); - hooks.stop = function() { - clearTimeout( timeout ); - }; - }); - }, - clearQueue: function( type ) { - return this.queue( type || "fx", [] ); - }, - // Get a promise resolved when queues of a certain type - // are emptied (fx is the type by default) - promise: function( type, object ) { - if ( typeof type !== "string" ) { - object = type; - type = undefined; - } - type = type || "fx"; - var defer = jQuery.Deferred(), - elements = this, - i = elements.length, - count = 1, - deferDataKey = type + "defer", - queueDataKey = type + "queue", - markDataKey = type + "mark", - tmp; - function resolve() { - if ( !( --count ) ) { - defer.resolveWith( elements, [ elements ] ); - } - } - while( i-- ) { - if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || - ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || - jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && - jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { - count++; - tmp.add( resolve ); - } - } - resolve(); - return defer.promise(); - } -}); - - - - -var rclass = /[\n\t\r]/g, - rspace = /\s+/, - rreturn = /\r/g, - rtype = /^(?:button|input)$/i, - rfocusable = /^(?:button|input|object|select|textarea)$/i, - rclickable = /^a(?:rea)?$/i, - rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, - getSetAttribute = jQuery.support.getSetAttribute, - nodeHook, boolHook, fixSpecified; - -jQuery.fn.extend({ - attr: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.attr ); - }, - - removeAttr: function( name ) { - return this.each(function() { - jQuery.removeAttr( this, name ); - }); - }, - - prop: function( name, value ) { - return jQuery.access( this, name, value, true, jQuery.prop ); - }, - - removeProp: function( name ) { - name = jQuery.propFix[ name ] || name; - return this.each(function() { - // try/catch handles cases where IE balks (such as removing a property on window) - try { - this[ name ] = undefined; - delete this[ name ]; - } catch( e ) {} - }); - }, - - addClass: function( value ) { - var classNames, i, l, elem, - setClass, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).addClass( value.call(this, j, this.className) ); - }); - } - - if ( value && typeof value === "string" ) { - classNames = value.split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 ) { - if ( !elem.className && classNames.length === 1 ) { - elem.className = value; - - } else { - setClass = " " + elem.className + " "; - - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { - setClass += classNames[ c ] + " "; - } - } - elem.className = jQuery.trim( setClass ); - } - } - } - } - - return this; - }, - - removeClass: function( value ) { - var classNames, i, l, elem, className, c, cl; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( j ) { - jQuery( this ).removeClass( value.call(this, j, this.className) ); - }); - } - - if ( (value && typeof value === "string") || value === undefined ) { - classNames = ( value || "" ).split( rspace ); - - for ( i = 0, l = this.length; i < l; i++ ) { - elem = this[ i ]; - - if ( elem.nodeType === 1 && elem.className ) { - if ( value ) { - className = (" " + elem.className + " ").replace( rclass, " " ); - for ( c = 0, cl = classNames.length; c < cl; c++ ) { - className = className.replace(" " + classNames[ c ] + " ", " "); - } - elem.className = jQuery.trim( className ); - - } else { - elem.className = ""; - } - } - } - } - - return this; - }, - - toggleClass: function( value, stateVal ) { - var type = typeof value, - isBool = typeof stateVal === "boolean"; - - if ( jQuery.isFunction( value ) ) { - return this.each(function( i ) { - jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); - }); - } - - return this.each(function() { - if ( type === "string" ) { - // toggle individual class names - var className, - i = 0, - self = jQuery( this ), - state = stateVal, - classNames = value.split( rspace ); - - while ( (className = classNames[ i++ ]) ) { - // check each className given, space seperated list - state = isBool ? state : !self.hasClass( className ); - self[ state ? "addClass" : "removeClass" ]( className ); - } - - } else if ( type === "undefined" || type === "boolean" ) { - if ( this.className ) { - // store className if set - jQuery._data( this, "__className__", this.className ); - } - - // toggle whole className - this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; - } - }); - }, - - hasClass: function( selector ) { - var className = " " + selector + " ", - i = 0, - l = this.length; - for ( ; i < l; i++ ) { - if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { - return true; - } - } - - return false; - }, - - val: function( value ) { - var hooks, ret, isFunction, - elem = this[0]; - - if ( !arguments.length ) { - if ( elem ) { - hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; - - if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { - return ret; - } - - ret = elem.value; - - return typeof ret === "string" ? - // handle most common string cases - ret.replace(rreturn, "") : - // handle cases where value is null/undef or number - ret == null ? "" : ret; - } - - return; - } - - isFunction = jQuery.isFunction( value ); - - return this.each(function( i ) { - var self = jQuery(this), val; - - if ( this.nodeType !== 1 ) { - return; - } - - if ( isFunction ) { - val = value.call( this, i, self.val() ); - } else { - val = value; - } - - // Treat null/undefined as ""; convert numbers to string - if ( val == null ) { - val = ""; - } else if ( typeof val === "number" ) { - val += ""; - } else if ( jQuery.isArray( val ) ) { - val = jQuery.map(val, function ( value ) { - return value == null ? "" : value + ""; - }); - } - - hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; - - // If set returns undefined, fall back to normal setting - if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { - this.value = val; - } - }); - } -}); - -jQuery.extend({ - valHooks: { - option: { - get: function( elem ) { - // attributes.value is undefined in Blackberry 4.7 but - // uses .value. See #6932 - var val = elem.attributes.value; - return !val || val.specified ? elem.value : elem.text; - } - }, - select: { - get: function( elem ) { - var value, i, max, option, - index = elem.selectedIndex, - values = [], - options = elem.options, - one = elem.type === "select-one"; - - // Nothing was selected - if ( index < 0 ) { - return null; - } - - // Loop through all the selected options - i = one ? index : 0; - max = one ? index + 1 : options.length; - for ( ; i < max; i++ ) { - option = options[ i ]; - - // Don't return options that are disabled or in a disabled optgroup - if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && - (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { - - // Get the specific value for the option - value = jQuery( option ).val(); - - // We don't need an array for one selects - if ( one ) { - return value; - } - - // Multi-Selects return an array - values.push( value ); - } - } - - // Fixes Bug #2551 -- select.val() broken in IE after form.reset() - if ( one && !values.length && options.length ) { - return jQuery( options[ index ] ).val(); - } - - return values; - }, - - set: function( elem, value ) { - var values = jQuery.makeArray( value ); - - jQuery(elem).find("option").each(function() { - this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; - }); - - if ( !values.length ) { - elem.selectedIndex = -1; - } - return values; - } - } - }, - - attrFn: { - val: true, - css: true, - html: true, - text: true, - data: true, - width: true, - height: true, - offset: true - }, - - attr: function( elem, name, value, pass ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set attributes on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - if ( pass && name in jQuery.attrFn ) { - return jQuery( elem )[ name ]( value ); - } - - // Fallback to prop when attributes are not supported - if ( typeof elem.getAttribute === "undefined" ) { - return jQuery.prop( elem, name, value ); - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - // All attributes are lowercase - // Grab necessary hook if one is defined - if ( notxml ) { - name = name.toLowerCase(); - hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); - } - - if ( value !== undefined ) { - - if ( value === null ) { - jQuery.removeAttr( elem, name ); - return; - - } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - elem.setAttribute( name, "" + value ); - return value; - } - - } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - - ret = elem.getAttribute( name ); - - // Non-existent attributes return null, we normalize to undefined - return ret === null ? - undefined : - ret; - } - }, - - removeAttr: function( elem, value ) { - var propName, attrNames, name, l, - i = 0; - - if ( value && elem.nodeType === 1 ) { - attrNames = value.toLowerCase().split( rspace ); - l = attrNames.length; - - for ( ; i < l; i++ ) { - name = attrNames[ i ]; - - if ( name ) { - propName = jQuery.propFix[ name ] || name; - - // See #9699 for explanation of this approach (setting first, then removal) - jQuery.attr( elem, name, "" ); - elem.removeAttribute( getSetAttribute ? name : propName ); - - // Set corresponding property to false for boolean attributes - if ( rboolean.test( name ) && propName in elem ) { - elem[ propName ] = false; - } - } - } - } - }, - - attrHooks: { - type: { - set: function( elem, value ) { - // We can't allow the type property to be changed (since it causes problems in IE) - if ( rtype.test( elem.nodeName ) && elem.parentNode ) { - jQuery.error( "type property can't be changed" ); - } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { - // Setting the type on a radio button after the value resets the value in IE6-9 - // Reset value to it's default in case type is set after value - // This is for element creation - var val = elem.value; - elem.setAttribute( "type", value ); - if ( val ) { - elem.value = val; - } - return value; - } - } - }, - // Use the value property for back compat - // Use the nodeHook for button elements in IE6/7 (#1954) - value: { - get: function( elem, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.get( elem, name ); - } - return name in elem ? - elem.value : - null; - }, - set: function( elem, value, name ) { - if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { - return nodeHook.set( elem, value, name ); - } - // Does not return so that setAttribute is also used - elem.value = value; - } - } - }, - - propFix: { - tabindex: "tabIndex", - readonly: "readOnly", - "for": "htmlFor", - "class": "className", - maxlength: "maxLength", - cellspacing: "cellSpacing", - cellpadding: "cellPadding", - rowspan: "rowSpan", - colspan: "colSpan", - usemap: "useMap", - frameborder: "frameBorder", - contenteditable: "contentEditable" - }, - - prop: function( elem, name, value ) { - var ret, hooks, notxml, - nType = elem.nodeType; - - // don't get/set properties on text, comment and attribute nodes - if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { - return; - } - - notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); - - if ( notxml ) { - // Fix name and attach hooks - name = jQuery.propFix[ name ] || name; - hooks = jQuery.propHooks[ name ]; - } - - if ( value !== undefined ) { - if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { - return ret; - - } else { - return ( elem[ name ] = value ); - } - - } else { - if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { - return ret; - - } else { - return elem[ name ]; - } - } - }, - - propHooks: { - tabIndex: { - get: function( elem ) { - // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set - // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ - var attributeNode = elem.getAttributeNode("tabindex"); - - return attributeNode && attributeNode.specified ? - parseInt( attributeNode.value, 10 ) : - rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? - 0 : - undefined; - } - } - } -}); - -// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) -jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; - -// Hook for boolean attributes -boolHook = { - get: function( elem, name ) { - // Align boolean attributes with corresponding properties - // Fall back to attribute presence where some booleans are not supported - var attrNode, - property = jQuery.prop( elem, name ); - return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? - name.toLowerCase() : - undefined; - }, - set: function( elem, value, name ) { - var propName; - if ( value === false ) { - // Remove boolean attributes when set to false - jQuery.removeAttr( elem, name ); - } else { - // value is true since we know at this point it's type boolean and not false - // Set boolean attributes to the same name and set the DOM property - propName = jQuery.propFix[ name ] || name; - if ( propName in elem ) { - // Only set the IDL specifically if it already exists on the element - elem[ propName ] = true; - } - - elem.setAttribute( name, name.toLowerCase() ); - } - return name; - } -}; - -// IE6/7 do not support getting/setting some attributes with get/setAttribute -if ( !getSetAttribute ) { - - fixSpecified = { - name: true, - id: true - }; - - // Use this for any attribute in IE6/7 - // This fixes almost every IE6/7 issue - nodeHook = jQuery.valHooks.button = { - get: function( elem, name ) { - var ret; - ret = elem.getAttributeNode( name ); - return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? - ret.nodeValue : - undefined; - }, - set: function( elem, value, name ) { - // Set the existing or create a new attribute node - var ret = elem.getAttributeNode( name ); - if ( !ret ) { - ret = document.createAttribute( name ); - elem.setAttributeNode( ret ); - } - return ( ret.nodeValue = value + "" ); - } - }; - - // Apply the nodeHook to tabindex - jQuery.attrHooks.tabindex.set = nodeHook.set; - - // Set width and height to auto instead of 0 on empty string( Bug #8150 ) - // This is for removals - jQuery.each([ "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - set: function( elem, value ) { - if ( value === "" ) { - elem.setAttribute( name, "auto" ); - return value; - } - } - }); - }); - - // Set contenteditable to false on removals(#10429) - // Setting to empty string throws an error as an invalid value - jQuery.attrHooks.contenteditable = { - get: nodeHook.get, - set: function( elem, value, name ) { - if ( value === "" ) { - value = "false"; - } - nodeHook.set( elem, value, name ); - } - }; -} - - -// Some attributes require a special call on IE -if ( !jQuery.support.hrefNormalized ) { - jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { - jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { - get: function( elem ) { - var ret = elem.getAttribute( name, 2 ); - return ret === null ? undefined : ret; - } - }); - }); -} - -if ( !jQuery.support.style ) { - jQuery.attrHooks.style = { - get: function( elem ) { - // Return undefined in the case of empty string - // Normalize to lowercase since IE uppercases css property names - return elem.style.cssText.toLowerCase() || undefined; - }, - set: function( elem, value ) { - return ( elem.style.cssText = "" + value ); - } - }; -} - -// Safari mis-reports the default selected property of an option -// Accessing the parent's selectedIndex property fixes it -if ( !jQuery.support.optSelected ) { - jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { - get: function( elem ) { - var parent = elem.parentNode; - - if ( parent ) { - parent.selectedIndex; - - // Make sure that it also works with optgroups, see #5701 - if ( parent.parentNode ) { - parent.parentNode.selectedIndex; - } - } - return null; - } - }); -} - -// IE6/7 call enctype encoding -if ( !jQuery.support.enctype ) { - jQuery.propFix.enctype = "encoding"; -} - -// Radios and checkboxes getter/setter -if ( !jQuery.support.checkOn ) { - jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = { - get: function( elem ) { - // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified - return elem.getAttribute("value") === null ? "on" : elem.value; - } - }; - }); -} -jQuery.each([ "radio", "checkbox" ], function() { - jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { - set: function( elem, value ) { - if ( jQuery.isArray( value ) ) { - return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); - } - } - }); -}); - - - - -var rformElems = /^(?:textarea|input|select)$/i, - rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, - rhoverHack = /\bhover(\.\S+)?\b/, - rkeyEvent = /^key/, - rmouseEvent = /^(?:mouse|contextmenu)|click/, - rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, - rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, - quickParse = function( selector ) { - var quick = rquickIs.exec( selector ); - if ( quick ) { - // 0 1 2 3 - // [ _, tag, id, class ] - quick[1] = ( quick[1] || "" ).toLowerCase(); - quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); - } - return quick; - }, - quickIs = function( elem, m ) { - var attrs = elem.attributes || {}; - return ( - (!m[1] || elem.nodeName.toLowerCase() === m[1]) && - (!m[2] || (attrs.id || {}).value === m[2]) && - (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) - ); - }, - hoverHack = function( events ) { - return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); - }; - -/* - * Helper functions for managing events -- not part of the public interface. - * Props to Dean Edwards' addEvent library for many of the ideas. - */ -jQuery.event = { - - add: function( elem, types, handler, data, selector ) { - - var elemData, eventHandle, events, - t, tns, type, namespaces, handleObj, - handleObjIn, quick, handlers, special; - - // Don't attach events to noData or text/comment nodes (allow plain objects tho) - if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { - return; - } - - // Caller can pass in an object of custom data in lieu of the handler - if ( handler.handler ) { - handleObjIn = handler; - handler = handleObjIn.handler; - } - - // Make sure that the handler has a unique ID, used to find/remove it later - if ( !handler.guid ) { - handler.guid = jQuery.guid++; - } - - // Init the element's event structure and main handler, if this is the first - events = elemData.events; - if ( !events ) { - elemData.events = events = {}; - } - eventHandle = elemData.handle; - if ( !eventHandle ) { - elemData.handle = eventHandle = function( e ) { - // Discard the second event of a jQuery.event.trigger() and - // when an event is called after a page has unloaded - return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? - jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : - undefined; - }; - // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events - eventHandle.elem = elem; - } - - // Handle multiple events separated by a space - // jQuery(...).bind("mouseover mouseout", fn); - types = jQuery.trim( hoverHack(types) ).split( " " ); - for ( t = 0; t < types.length; t++ ) { - - tns = rtypenamespace.exec( types[t] ) || []; - type = tns[1]; - namespaces = ( tns[2] || "" ).split( "." ).sort(); - - // If event changes its type, use the special event handlers for the changed type - special = jQuery.event.special[ type ] || {}; - - // If selector defined, determine special event api type, otherwise given type - type = ( selector ? special.delegateType : special.bindType ) || type; - - // Update special based on newly reset type - special = jQuery.event.special[ type ] || {}; - - // handleObj is passed to all event handlers - handleObj = jQuery.extend({ - type: type, - origType: tns[1], - data: data, - handler: handler, - guid: handler.guid, - selector: selector, - quick: quickParse( selector ), - namespace: namespaces.join(".") - }, handleObjIn ); - - // Init the event handler queue if we're the first - handlers = events[ type ]; - if ( !handlers ) { - handlers = events[ type ] = []; - handlers.delegateCount = 0; - - // Only use addEventListener/attachEvent if the special events handler returns false - if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { - // Bind the global event handler to the element - if ( elem.addEventListener ) { - elem.addEventListener( type, eventHandle, false ); - - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, eventHandle ); - } - } - } - - if ( special.add ) { - special.add.call( elem, handleObj ); - - if ( !handleObj.handler.guid ) { - handleObj.handler.guid = handler.guid; - } - } - - // Add to the element's handler list, delegates in front - if ( selector ) { - handlers.splice( handlers.delegateCount++, 0, handleObj ); - } else { - handlers.push( handleObj ); - } - - // Keep track of which events have ever been used, for event optimization - jQuery.event.global[ type ] = true; - } - - // Nullify elem to prevent memory leaks in IE - elem = null; - }, - - global: {}, - - // Detach an event or set of events from an element - remove: function( elem, types, handler, selector, mappedTypes ) { - - var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), - t, tns, type, origType, namespaces, origCount, - j, events, special, handle, eventType, handleObj; - - if ( !elemData || !(events = elemData.events) ) { - return; - } - - // Once for each type.namespace in types; type may be omitted - types = jQuery.trim( hoverHack( types || "" ) ).split(" "); - for ( t = 0; t < types.length; t++ ) { - tns = rtypenamespace.exec( types[t] ) || []; - type = origType = tns[1]; - namespaces = tns[2]; - - // Unbind all events (on this namespace, if provided) for the element - if ( !type ) { - for ( type in events ) { - jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); - } - continue; - } - - special = jQuery.event.special[ type ] || {}; - type = ( selector? special.delegateType : special.bindType ) || type; - eventType = events[ type ] || []; - origCount = eventType.length; - namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - - // Remove matching events - for ( j = 0; j < eventType.length; j++ ) { - handleObj = eventType[ j ]; - - if ( ( mappedTypes || origType === handleObj.origType ) && - ( !handler || handler.guid === handleObj.guid ) && - ( !namespaces || namespaces.test( handleObj.namespace ) ) && - ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { - eventType.splice( j--, 1 ); - - if ( handleObj.selector ) { - eventType.delegateCount--; - } - if ( special.remove ) { - special.remove.call( elem, handleObj ); - } - } - } - - // Remove generic event handler if we removed something and no more handlers exist - // (avoids potential for endless recursion during removal of special event handlers) - if ( eventType.length === 0 && origCount !== eventType.length ) { - if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { - jQuery.removeEvent( elem, type, elemData.handle ); - } - - delete events[ type ]; - } - } - - // Remove the expando if it's no longer used - if ( jQuery.isEmptyObject( events ) ) { - handle = elemData.handle; - if ( handle ) { - handle.elem = null; - } - - // removeData also checks for emptiness and clears the expando if empty - // so use it instead of delete - jQuery.removeData( elem, [ "events", "handle" ], true ); - } - }, - - // Events that are safe to short-circuit if no handlers are attached. - // Native DOM events should not be added, they may have inline handlers. - customEvent: { - "getData": true, - "setData": true, - "changeData": true - }, - - trigger: function( event, data, elem, onlyHandlers ) { - // Don't do events on text and comment nodes - if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { - return; - } - - // Event object or event type - var type = event.type || event, - namespaces = [], - cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; - - // focus/blur morphs to focusin/out; ensure we're not firing them right now - if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { - return; - } - - if ( type.indexOf( "!" ) >= 0 ) { - // Exclusive events trigger only for the exact event (no namespaces) - type = type.slice(0, -1); - exclusive = true; - } - - if ( type.indexOf( "." ) >= 0 ) { - // Namespaced trigger; create a regexp to match event type in handle() - namespaces = type.split("."); - type = namespaces.shift(); - namespaces.sort(); - } - - if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { - // No jQuery handlers for this event type, and it can't have inline handlers - return; - } - - // Caller can pass in an Event, Object, or just an event type string - event = typeof event === "object" ? - // jQuery.Event object - event[ jQuery.expando ] ? event : - // Object literal - new jQuery.Event( type, event ) : - // Just the event type (string) - new jQuery.Event( type ); - - event.type = type; - event.isTrigger = true; - event.exclusive = exclusive; - event.namespace = namespaces.join( "." ); - event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; - ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; - - // Handle a global trigger - if ( !elem ) { - - // TODO: Stop taunting the data cache; remove global events and always attach to document - cache = jQuery.cache; - for ( i in cache ) { - if ( cache[ i ].events && cache[ i ].events[ type ] ) { - jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); - } - } - return; - } - - // Clean up the event in case it is being reused - event.result = undefined; - if ( !event.target ) { - event.target = elem; - } - - // Clone any incoming data and prepend the event, creating the handler arg list - data = data != null ? jQuery.makeArray( data ) : []; - data.unshift( event ); - - // Allow special events to draw outside the lines - special = jQuery.event.special[ type ] || {}; - if ( special.trigger && special.trigger.apply( elem, data ) === false ) { - return; - } - - // Determine event propagation path in advance, per W3C events spec (#9951) - // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) - eventPath = [[ elem, special.bindType || type ]]; - if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { - - bubbleType = special.delegateType || type; - cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; - old = null; - for ( ; cur; cur = cur.parentNode ) { - eventPath.push([ cur, bubbleType ]); - old = cur; - } - - // Only add window if we got to document (e.g., not plain obj or detached DOM) - if ( old && old === elem.ownerDocument ) { - eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); - } - } - - // Fire handlers on the event path - for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { - - cur = eventPath[i][0]; - event.type = eventPath[i][1]; - - handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); - if ( handle ) { - handle.apply( cur, data ); - } - // Note that this is a bare JS function and not a jQuery handler - handle = ontype && cur[ ontype ]; - if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { - event.preventDefault(); - } - } - event.type = type; - - // If nobody prevented the default action, do it now - if ( !onlyHandlers && !event.isDefaultPrevented() ) { - - if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && - !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { - - // Call a native DOM method on the target with the same name name as the event. - // Can't use an .isFunction() check here because IE6/7 fails that test. - // Don't do default actions on window, that's where global variables be (#6170) - // IE<9 dies on focus/blur to hidden element (#1486) - if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { - - // Don't re-trigger an onFOO event when we call its FOO() method - old = elem[ ontype ]; - - if ( old ) { - elem[ ontype ] = null; - } - - // Prevent re-triggering of the same event, since we already bubbled it above - jQuery.event.triggered = type; - elem[ type ](); - jQuery.event.triggered = undefined; - - if ( old ) { - elem[ ontype ] = old; - } - } - } - } - - return event.result; - }, - - dispatch: function( event ) { - - // Make a writable jQuery.Event from the native event object - event = jQuery.event.fix( event || window.event ); - - var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), - delegateCount = handlers.delegateCount, - args = [].slice.call( arguments, 0 ), - run_all = !event.exclusive && !event.namespace, - handlerQueue = [], - i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; - - // Use the fix-ed jQuery.Event rather than the (read-only) native event - args[0] = event; - event.delegateTarget = this; - - // Determine handlers that should run if there are delegated events - // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) - if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { - - // Pregenerate a single jQuery object for reuse with .is() - jqcur = jQuery(this); - jqcur.context = this.ownerDocument || this; - - for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { - selMatch = {}; - matches = []; - jqcur[0] = cur; - for ( i = 0; i < delegateCount; i++ ) { - handleObj = handlers[ i ]; - sel = handleObj.selector; - - if ( selMatch[ sel ] === undefined ) { - selMatch[ sel ] = ( - handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) - ); - } - if ( selMatch[ sel ] ) { - matches.push( handleObj ); - } - } - if ( matches.length ) { - handlerQueue.push({ elem: cur, matches: matches }); - } - } - } - - // Add the remaining (directly-bound) handlers - if ( handlers.length > delegateCount ) { - handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); - } - - // Run delegates first; they may want to stop propagation beneath us - for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { - matched = handlerQueue[ i ]; - event.currentTarget = matched.elem; - - for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { - handleObj = matched.matches[ j ]; - - // Triggered event must either 1) be non-exclusive and have no namespace, or - // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). - if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { - - event.data = handleObj.data; - event.handleObj = handleObj; - - ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) - .apply( matched.elem, args ); - - if ( ret !== undefined ) { - event.result = ret; - if ( ret === false ) { - event.preventDefault(); - event.stopPropagation(); - } - } - } - } - } - - return event.result; - }, - - // Includes some event props shared by KeyEvent and MouseEvent - // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** - props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), - - fixHooks: {}, - - keyHooks: { - props: "char charCode key keyCode".split(" "), - filter: function( event, original ) { - - // Add which for key events - if ( event.which == null ) { - event.which = original.charCode != null ? original.charCode : original.keyCode; - } - - return event; - } - }, - - mouseHooks: { - props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), - filter: function( event, original ) { - var eventDoc, doc, body, - button = original.button, - fromElement = original.fromElement; - - // Calculate pageX/Y if missing and clientX/Y available - if ( event.pageX == null && original.clientX != null ) { - eventDoc = event.target.ownerDocument || document; - doc = eventDoc.documentElement; - body = eventDoc.body; - - event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); - event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); - } - - // Add relatedTarget, if necessary - if ( !event.relatedTarget && fromElement ) { - event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; - } - - // Add which for click: 1 === left; 2 === middle; 3 === right - // Note: button is not normalized, so don't use it - if ( !event.which && button !== undefined ) { - event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); - } - - return event; - } - }, - - fix: function( event ) { - if ( event[ jQuery.expando ] ) { - return event; - } - - // Create a writable copy of the event object and normalize some properties - var i, prop, - originalEvent = event, - fixHook = jQuery.event.fixHooks[ event.type ] || {}, - copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; - - event = jQuery.Event( originalEvent ); - - for ( i = copy.length; i; ) { - prop = copy[ --i ]; - event[ prop ] = originalEvent[ prop ]; - } - - // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) - if ( !event.target ) { - event.target = originalEvent.srcElement || document; - } - - // Target should not be a text node (#504, Safari) - if ( event.target.nodeType === 3 ) { - event.target = event.target.parentNode; - } - - // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) - if ( event.metaKey === undefined ) { - event.metaKey = event.ctrlKey; - } - - return fixHook.filter? fixHook.filter( event, originalEvent ) : event; - }, - - special: { - ready: { - // Make sure the ready event is setup - setup: jQuery.bindReady - }, - - load: { - // Prevent triggered image.load events from bubbling to window.load - noBubble: true - }, - - focus: { - delegateType: "focusin" - }, - blur: { - delegateType: "focusout" - }, - - beforeunload: { - setup: function( data, namespaces, eventHandle ) { - // We only want to do this special case on windows - if ( jQuery.isWindow( this ) ) { - this.onbeforeunload = eventHandle; - } - }, - - teardown: function( namespaces, eventHandle ) { - if ( this.onbeforeunload === eventHandle ) { - this.onbeforeunload = null; - } - } - } - }, - - simulate: function( type, elem, event, bubble ) { - // Piggyback on a donor event to simulate a different one. - // Fake originalEvent to avoid donor's stopPropagation, but if the - // simulated event prevents default then we do the same on the donor. - var e = jQuery.extend( - new jQuery.Event(), - event, - { type: type, - isSimulated: true, - originalEvent: {} - } - ); - if ( bubble ) { - jQuery.event.trigger( e, null, elem ); - } else { - jQuery.event.dispatch.call( elem, e ); - } - if ( e.isDefaultPrevented() ) { - event.preventDefault(); - } - } -}; - -// Some plugins are using, but it's undocumented/deprecated and will be removed. -// The 1.7 special event interface should provide all the hooks needed now. -jQuery.event.handle = jQuery.event.dispatch; - -jQuery.removeEvent = document.removeEventListener ? - function( elem, type, handle ) { - if ( elem.removeEventListener ) { - elem.removeEventListener( type, handle, false ); - } - } : - function( elem, type, handle ) { - if ( elem.detachEvent ) { - elem.detachEvent( "on" + type, handle ); - } - }; - -jQuery.Event = function( src, props ) { - // Allow instantiation without the 'new' keyword - if ( !(this instanceof jQuery.Event) ) { - return new jQuery.Event( src, props ); - } - - // Event object - if ( src && src.type ) { - this.originalEvent = src; - this.type = src.type; - - // Events bubbling up the document may have been marked as prevented - // by a handler lower down the tree; reflect the correct value. - this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || - src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; - - // Event type - } else { - this.type = src; - } - - // Put explicitly provided properties onto the event object - if ( props ) { - jQuery.extend( this, props ); - } - - // Create a timestamp if incoming event doesn't have one - this.timeStamp = src && src.timeStamp || jQuery.now(); - - // Mark it as fixed - this[ jQuery.expando ] = true; -}; - -function returnFalse() { - return false; -} -function returnTrue() { - return true; -} - -// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding -// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html -jQuery.Event.prototype = { - preventDefault: function() { - this.isDefaultPrevented = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - - // if preventDefault exists run it on the original event - if ( e.preventDefault ) { - e.preventDefault(); - - // otherwise set the returnValue property of the original event to false (IE) - } else { - e.returnValue = false; - } - }, - stopPropagation: function() { - this.isPropagationStopped = returnTrue; - - var e = this.originalEvent; - if ( !e ) { - return; - } - // if stopPropagation exists run it on the original event - if ( e.stopPropagation ) { - e.stopPropagation(); - } - // otherwise set the cancelBubble property of the original event to true (IE) - e.cancelBubble = true; - }, - stopImmediatePropagation: function() { - this.isImmediatePropagationStopped = returnTrue; - this.stopPropagation(); - }, - isDefaultPrevented: returnFalse, - isPropagationStopped: returnFalse, - isImmediatePropagationStopped: returnFalse -}; - -// Create mouseenter/leave events using mouseover/out and event-time checks -jQuery.each({ - mouseenter: "mouseover", - mouseleave: "mouseout" -}, function( orig, fix ) { - jQuery.event.special[ orig ] = { - delegateType: fix, - bindType: fix, - - handle: function( event ) { - var target = this, - related = event.relatedTarget, - handleObj = event.handleObj, - selector = handleObj.selector, - ret; - - // For mousenter/leave call the handler if related is outside the target. - // NB: No relatedTarget if the mouse left/entered the browser window - if ( !related || (related !== target && !jQuery.contains( target, related )) ) { - event.type = handleObj.origType; - ret = handleObj.handler.apply( this, arguments ); - event.type = fix; - } - return ret; - } - }; -}); - -// IE submit delegation -if ( !jQuery.support.submitBubbles ) { - - jQuery.event.special.submit = { - setup: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Lazy-add a submit handler when a descendant form may potentially be submitted - jQuery.event.add( this, "click._submit keypress._submit", function( e ) { - // Node name check avoids a VML-related crash in IE (#9807) - var elem = e.target, - form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; - if ( form && !form._submit_attached ) { - jQuery.event.add( form, "submit._submit", function( event ) { - // If form was submitted by the user, bubble the event up the tree - if ( this.parentNode && !event.isTrigger ) { - jQuery.event.simulate( "submit", this.parentNode, event, true ); - } - }); - form._submit_attached = true; - } - }); - // return undefined since we don't need an event listener - }, - - teardown: function() { - // Only need this for delegated form submit events - if ( jQuery.nodeName( this, "form" ) ) { - return false; - } - - // Remove delegated handlers; cleanData eventually reaps submit handlers attached above - jQuery.event.remove( this, "._submit" ); - } - }; -} - -// IE change delegation and checkbox/radio fix -if ( !jQuery.support.changeBubbles ) { - - jQuery.event.special.change = { - - setup: function() { - - if ( rformElems.test( this.nodeName ) ) { - // IE doesn't fire change on a check/radio until blur; trigger it on click - // after a propertychange. Eat the blur-change in special.change.handle. - // This still fires onchange a second time for check/radio after blur. - if ( this.type === "checkbox" || this.type === "radio" ) { - jQuery.event.add( this, "propertychange._change", function( event ) { - if ( event.originalEvent.propertyName === "checked" ) { - this._just_changed = true; - } - }); - jQuery.event.add( this, "click._change", function( event ) { - if ( this._just_changed && !event.isTrigger ) { - this._just_changed = false; - jQuery.event.simulate( "change", this, event, true ); - } - }); - } - return false; - } - // Delegated event; lazy-add a change handler on descendant inputs - jQuery.event.add( this, "beforeactivate._change", function( e ) { - var elem = e.target; - - if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { - jQuery.event.add( elem, "change._change", function( event ) { - if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { - jQuery.event.simulate( "change", this.parentNode, event, true ); - } - }); - elem._change_attached = true; - } - }); - }, - - handle: function( event ) { - var elem = event.target; - - // Swallow native change events from checkbox/radio, we already triggered them above - if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { - return event.handleObj.handler.apply( this, arguments ); - } - }, - - teardown: function() { - jQuery.event.remove( this, "._change" ); - - return rformElems.test( this.nodeName ); - } - }; -} - -// Create "bubbling" focus and blur events -if ( !jQuery.support.focusinBubbles ) { - jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { - - // Attach a single capturing handler while someone wants focusin/focusout - var attaches = 0, - handler = function( event ) { - jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); - }; - - jQuery.event.special[ fix ] = { - setup: function() { - if ( attaches++ === 0 ) { - document.addEventListener( orig, handler, true ); - } - }, - teardown: function() { - if ( --attaches === 0 ) { - document.removeEventListener( orig, handler, true ); - } - } - }; - }); -} - -jQuery.fn.extend({ - - on: function( types, selector, data, fn, /*INTERNAL*/ one ) { - var origFn, type; - - // Types can be a map of types/handlers - if ( typeof types === "object" ) { - // ( types-Object, selector, data ) - if ( typeof selector !== "string" ) { - // ( types-Object, data ) - data = selector; - selector = undefined; - } - for ( type in types ) { - this.on( type, selector, data, types[ type ], one ); - } - return this; - } - - if ( data == null && fn == null ) { - // ( types, fn ) - fn = selector; - data = selector = undefined; - } else if ( fn == null ) { - if ( typeof selector === "string" ) { - // ( types, selector, fn ) - fn = data; - data = undefined; - } else { - // ( types, data, fn ) - fn = data; - data = selector; - selector = undefined; - } - } - if ( fn === false ) { - fn = returnFalse; - } else if ( !fn ) { - return this; - } - - if ( one === 1 ) { - origFn = fn; - fn = function( event ) { - // Can use an empty set, since event contains the info - jQuery().off( event ); - return origFn.apply( this, arguments ); - }; - // Use same guid so caller can remove using origFn - fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); - } - return this.each( function() { - jQuery.event.add( this, types, fn, data, selector ); - }); - }, - one: function( types, selector, data, fn ) { - return this.on.call( this, types, selector, data, fn, 1 ); - }, - off: function( types, selector, fn ) { - if ( types && types.preventDefault && types.handleObj ) { - // ( event ) dispatched jQuery.Event - var handleObj = types.handleObj; - jQuery( types.delegateTarget ).off( - handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, - handleObj.selector, - handleObj.handler - ); - return this; - } - if ( typeof types === "object" ) { - // ( types-object [, selector] ) - for ( var type in types ) { - this.off( type, selector, types[ type ] ); - } - return this; - } - if ( selector === false || typeof selector === "function" ) { - // ( types [, fn] ) - fn = selector; - selector = undefined; - } - if ( fn === false ) { - fn = returnFalse; - } - return this.each(function() { - jQuery.event.remove( this, types, fn, selector ); - }); - }, - - bind: function( types, data, fn ) { - return this.on( types, null, data, fn ); - }, - unbind: function( types, fn ) { - return this.off( types, null, fn ); - }, - - live: function( types, data, fn ) { - jQuery( this.context ).on( types, this.selector, data, fn ); - return this; - }, - die: function( types, fn ) { - jQuery( this.context ).off( types, this.selector || "**", fn ); - return this; - }, - - delegate: function( selector, types, data, fn ) { - return this.on( types, selector, data, fn ); - }, - undelegate: function( selector, types, fn ) { - // ( namespace ) or ( selector, types [, fn] ) - return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); - }, - - trigger: function( type, data ) { - return this.each(function() { - jQuery.event.trigger( type, data, this ); - }); - }, - triggerHandler: function( type, data ) { - if ( this[0] ) { - return jQuery.event.trigger( type, data, this[0], true ); - } - }, - - toggle: function( fn ) { - // Save reference to arguments for access in closure - var args = arguments, - guid = fn.guid || jQuery.guid++, - i = 0, - toggler = function( event ) { - // Figure out which function to execute - var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; - jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); - - // Make sure that clicks stop - event.preventDefault(); - - // and execute the function - return args[ lastToggle ].apply( this, arguments ) || false; - }; - - // link all the functions, so any of them can unbind this click handler - toggler.guid = guid; - while ( i < args.length ) { - args[ i++ ].guid = guid; - } - - return this.click( toggler ); - }, - - hover: function( fnOver, fnOut ) { - return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); - } -}); - -jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + - "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + - "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { - - // Handle event binding - jQuery.fn[ name ] = function( data, fn ) { - if ( fn == null ) { - fn = data; - data = null; - } - - return arguments.length > 0 ? - this.on( name, null, data, fn ) : - this.trigger( name ); - }; - - if ( jQuery.attrFn ) { - jQuery.attrFn[ name ] = true; - } - - if ( rkeyEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; - } - - if ( rmouseEvent.test( name ) ) { - jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; - } -}); - - - -/*! - * Sizzle CSS Selector Engine - * Copyright 2011, The Dojo Foundation - * Released under the MIT, BSD, and GPL Licenses. - * More information: http://sizzlejs.com/ - */ -(function(){ - -var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, - expando = "sizcache" + (Math.random() + '').replace('.', ''), - done = 0, - toString = Object.prototype.toString, - hasDuplicate = false, - baseHasDuplicate = true, - rBackslash = /\\/g, - rReturn = /\r\n/g, - rNonWord = /\W/; - -// Here we check if the JavaScript engine is using some sort of -// optimization where it does not always call our comparision -// function. If that is the case, discard the hasDuplicate value. -// Thus far that includes Google Chrome. -[0, 0].sort(function() { - baseHasDuplicate = false; - return 0; -}); - -var Sizzle = function( selector, context, results, seed ) { - results = results || []; - context = context || document; - - var origContext = context; - - if ( context.nodeType !== 1 && context.nodeType !== 9 ) { - return []; - } - - if ( !selector || typeof selector !== "string" ) { - return results; - } - - var m, set, checkSet, extra, ret, cur, pop, i, - prune = true, - contextXML = Sizzle.isXML( context ), - parts = [], - soFar = selector; - - // Reset the position of the chunker regexp (start from head) - do { - chunker.exec( "" ); - m = chunker.exec( soFar ); - - if ( m ) { - soFar = m[3]; - - parts.push( m[1] ); - - if ( m[2] ) { - extra = m[3]; - break; - } - } - } while ( m ); - - if ( parts.length > 1 && origPOS.exec( selector ) ) { - - if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { - set = posProcess( parts[0] + parts[1], context, seed ); - - } else { - set = Expr.relative[ parts[0] ] ? - [ context ] : - Sizzle( parts.shift(), context ); - - while ( parts.length ) { - selector = parts.shift(); - - if ( Expr.relative[ selector ] ) { - selector += parts.shift(); - } - - set = posProcess( selector, set, seed ); - } - } - - } else { - // Take a shortcut and set the context if the root selector is an ID - // (but not if it'll be faster if the inner selector is an ID) - if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && - Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { - - ret = Sizzle.find( parts.shift(), context, contextXML ); - context = ret.expr ? - Sizzle.filter( ret.expr, ret.set )[0] : - ret.set[0]; - } - - if ( context ) { - ret = seed ? - { expr: parts.pop(), set: makeArray(seed) } : - Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); - - set = ret.expr ? - Sizzle.filter( ret.expr, ret.set ) : - ret.set; - - if ( parts.length > 0 ) { - checkSet = makeArray( set ); - - } else { - prune = false; - } - - while ( parts.length ) { - cur = parts.pop(); - pop = cur; - - if ( !Expr.relative[ cur ] ) { - cur = ""; - } else { - pop = parts.pop(); - } - - if ( pop == null ) { - pop = context; - } - - Expr.relative[ cur ]( checkSet, pop, contextXML ); - } - - } else { - checkSet = parts = []; - } - } - - if ( !checkSet ) { - checkSet = set; - } - - if ( !checkSet ) { - Sizzle.error( cur || selector ); - } - - if ( toString.call(checkSet) === "[object Array]" ) { - if ( !prune ) { - results.push.apply( results, checkSet ); - - } else if ( context && context.nodeType === 1 ) { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { - results.push( set[i] ); - } - } - - } else { - for ( i = 0; checkSet[i] != null; i++ ) { - if ( checkSet[i] && checkSet[i].nodeType === 1 ) { - results.push( set[i] ); - } - } - } - - } else { - makeArray( checkSet, results ); - } - - if ( extra ) { - Sizzle( extra, origContext, results, seed ); - Sizzle.uniqueSort( results ); - } - - return results; -}; - -Sizzle.uniqueSort = function( results ) { - if ( sortOrder ) { - hasDuplicate = baseHasDuplicate; - results.sort( sortOrder ); - - if ( hasDuplicate ) { - for ( var i = 1; i < results.length; i++ ) { - if ( results[i] === results[ i - 1 ] ) { - results.splice( i--, 1 ); - } - } - } - } - - return results; -}; - -Sizzle.matches = function( expr, set ) { - return Sizzle( expr, null, null, set ); -}; - -Sizzle.matchesSelector = function( node, expr ) { - return Sizzle( expr, null, null, [node] ).length > 0; -}; - -Sizzle.find = function( expr, context, isXML ) { - var set, i, len, match, type, left; - - if ( !expr ) { - return []; - } - - for ( i = 0, len = Expr.order.length; i < len; i++ ) { - type = Expr.order[i]; - - if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { - left = match[1]; - match.splice( 1, 1 ); - - if ( left.substr( left.length - 1 ) !== "\\" ) { - match[1] = (match[1] || "").replace( rBackslash, "" ); - set = Expr.find[ type ]( match, context, isXML ); - - if ( set != null ) { - expr = expr.replace( Expr.match[ type ], "" ); - break; - } - } - } - } - - if ( !set ) { - set = typeof context.getElementsByTagName !== "undefined" ? - context.getElementsByTagName( "*" ) : - []; - } - - return { set: set, expr: expr }; -}; - -Sizzle.filter = function( expr, set, inplace, not ) { - var match, anyFound, - type, found, item, filter, left, - i, pass, - old = expr, - result = [], - curLoop = set, - isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); - - while ( expr && set.length ) { - for ( type in Expr.filter ) { - if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { - filter = Expr.filter[ type ]; - left = match[1]; - - anyFound = false; - - match.splice(1,1); - - if ( left.substr( left.length - 1 ) === "\\" ) { - continue; - } - - if ( curLoop === result ) { - result = []; - } - - if ( Expr.preFilter[ type ] ) { - match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); - - if ( !match ) { - anyFound = found = true; - - } else if ( match === true ) { - continue; - } - } - - if ( match ) { - for ( i = 0; (item = curLoop[i]) != null; i++ ) { - if ( item ) { - found = filter( item, match, i, curLoop ); - pass = not ^ found; - - if ( inplace && found != null ) { - if ( pass ) { - anyFound = true; - - } else { - curLoop[i] = false; - } - - } else if ( pass ) { - result.push( item ); - anyFound = true; - } - } - } - } - - if ( found !== undefined ) { - if ( !inplace ) { - curLoop = result; - } - - expr = expr.replace( Expr.match[ type ], "" ); - - if ( !anyFound ) { - return []; - } - - break; - } - } - } - - // Improper expression - if ( expr === old ) { - if ( anyFound == null ) { - Sizzle.error( expr ); - - } else { - break; - } - } - - old = expr; - } - - return curLoop; -}; - -Sizzle.error = function( msg ) { - throw new Error( "Syntax error, unrecognized expression: " + msg ); -}; - -/** - * Utility function for retreiving the text value of an array of DOM nodes - * @param {Array|Element} elem - */ -var getText = Sizzle.getText = function( elem ) { - var i, node, - nodeType = elem.nodeType, - ret = ""; - - if ( nodeType ) { - if ( nodeType === 1 || nodeType === 9 ) { - // Use textContent || innerText for elements - if ( typeof elem.textContent === 'string' ) { - return elem.textContent; - } else if ( typeof elem.innerText === 'string' ) { - // Replace IE's carriage returns - return elem.innerText.replace( rReturn, '' ); - } else { - // Traverse it's children - for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { - ret += getText( elem ); - } - } - } else if ( nodeType === 3 || nodeType === 4 ) { - return elem.nodeValue; - } - } else { - - // If no nodeType, this is expected to be an array - for ( i = 0; (node = elem[i]); i++ ) { - // Do not traverse comment nodes - if ( node.nodeType !== 8 ) { - ret += getText( node ); - } - } - } - return ret; -}; - -var Expr = Sizzle.selectors = { - order: [ "ID", "NAME", "TAG" ], - - match: { - ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, - NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, - ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, - TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, - CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, - POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, - PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ - }, - - leftMatch: {}, - - attrMap: { - "class": "className", - "for": "htmlFor" - }, - - attrHandle: { - href: function( elem ) { - return elem.getAttribute( "href" ); - }, - type: function( elem ) { - return elem.getAttribute( "type" ); - } - }, - - relative: { - "+": function(checkSet, part){ - var isPartStr = typeof part === "string", - isTag = isPartStr && !rNonWord.test( part ), - isPartStrNotTag = isPartStr && !isTag; - - if ( isTag ) { - part = part.toLowerCase(); - } - - for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { - if ( (elem = checkSet[i]) ) { - while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} - - checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? - elem || false : - elem === part; - } - } - - if ( isPartStrNotTag ) { - Sizzle.filter( part, checkSet, true ); - } - }, - - ">": function( checkSet, part ) { - var elem, - isPartStr = typeof part === "string", - i = 0, - l = checkSet.length; - - if ( isPartStr && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - var parent = elem.parentNode; - checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; - } - } - - } else { - for ( ; i < l; i++ ) { - elem = checkSet[i]; - - if ( elem ) { - checkSet[i] = isPartStr ? - elem.parentNode : - elem.parentNode === part; - } - } - - if ( isPartStr ) { - Sizzle.filter( part, checkSet, true ); - } - } - }, - - "": function(checkSet, part, isXML){ - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); - }, - - "~": function( checkSet, part, isXML ) { - var nodeCheck, - doneName = done++, - checkFn = dirCheck; - - if ( typeof part === "string" && !rNonWord.test( part ) ) { - part = part.toLowerCase(); - nodeCheck = part; - checkFn = dirNodeCheck; - } - - checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); - } - }, - - find: { - ID: function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - return m && m.parentNode ? [m] : []; - } - }, - - NAME: function( match, context ) { - if ( typeof context.getElementsByName !== "undefined" ) { - var ret = [], - results = context.getElementsByName( match[1] ); - - for ( var i = 0, l = results.length; i < l; i++ ) { - if ( results[i].getAttribute("name") === match[1] ) { - ret.push( results[i] ); - } - } - - return ret.length === 0 ? null : ret; - } - }, - - TAG: function( match, context ) { - if ( typeof context.getElementsByTagName !== "undefined" ) { - return context.getElementsByTagName( match[1] ); - } - } - }, - preFilter: { - CLASS: function( match, curLoop, inplace, result, not, isXML ) { - match = " " + match[1].replace( rBackslash, "" ) + " "; - - if ( isXML ) { - return match; - } - - for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { - if ( elem ) { - if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { - if ( !inplace ) { - result.push( elem ); - } - - } else if ( inplace ) { - curLoop[i] = false; - } - } - } - - return false; - }, - - ID: function( match ) { - return match[1].replace( rBackslash, "" ); - }, - - TAG: function( match, curLoop ) { - return match[1].replace( rBackslash, "" ).toLowerCase(); - }, - - CHILD: function( match ) { - if ( match[1] === "nth" ) { - if ( !match[2] ) { - Sizzle.error( match[0] ); - } - - match[2] = match[2].replace(/^\+|\s*/g, ''); - - // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' - var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( - match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || - !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); - - // calculate the numbers (first)n+(last) including if they are negative - match[2] = (test[1] + (test[2] || 1)) - 0; - match[3] = test[3] - 0; - } - else if ( match[2] ) { - Sizzle.error( match[0] ); - } - - // TODO: Move to normal caching system - match[0] = done++; - - return match; - }, - - ATTR: function( match, curLoop, inplace, result, not, isXML ) { - var name = match[1] = match[1].replace( rBackslash, "" ); - - if ( !isXML && Expr.attrMap[name] ) { - match[1] = Expr.attrMap[name]; - } - - // Handle if an un-quoted value was used - match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); - - if ( match[2] === "~=" ) { - match[4] = " " + match[4] + " "; - } - - return match; - }, - - PSEUDO: function( match, curLoop, inplace, result, not ) { - if ( match[1] === "not" ) { - // If we're dealing with a complex expression, or a simple one - if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { - match[3] = Sizzle(match[3], null, null, curLoop); - - } else { - var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); - - if ( !inplace ) { - result.push.apply( result, ret ); - } - - return false; - } - - } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { - return true; - } - - return match; - }, - - POS: function( match ) { - match.unshift( true ); - - return match; - } - }, - - filters: { - enabled: function( elem ) { - return elem.disabled === false && elem.type !== "hidden"; - }, - - disabled: function( elem ) { - return elem.disabled === true; - }, - - checked: function( elem ) { - return elem.checked === true; - }, - - selected: function( elem ) { - // Accessing this property makes selected-by-default - // options in Safari work properly - if ( elem.parentNode ) { - elem.parentNode.selectedIndex; - } - - return elem.selected === true; - }, - - parent: function( elem ) { - return !!elem.firstChild; - }, - - empty: function( elem ) { - return !elem.firstChild; - }, - - has: function( elem, i, match ) { - return !!Sizzle( match[3], elem ).length; - }, - - header: function( elem ) { - return (/h\d/i).test( elem.nodeName ); - }, - - text: function( elem ) { - var attr = elem.getAttribute( "type" ), type = elem.type; - // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) - // use getAttribute instead to test this case - return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); - }, - - radio: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; - }, - - checkbox: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; - }, - - file: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; - }, - - password: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; - }, - - submit: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "submit" === elem.type; - }, - - image: function( elem ) { - return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; - }, - - reset: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return (name === "input" || name === "button") && "reset" === elem.type; - }, - - button: function( elem ) { - var name = elem.nodeName.toLowerCase(); - return name === "input" && "button" === elem.type || name === "button"; - }, - - input: function( elem ) { - return (/input|select|textarea|button/i).test( elem.nodeName ); - }, - - focus: function( elem ) { - return elem === elem.ownerDocument.activeElement; - } - }, - setFilters: { - first: function( elem, i ) { - return i === 0; - }, - - last: function( elem, i, match, array ) { - return i === array.length - 1; - }, - - even: function( elem, i ) { - return i % 2 === 0; - }, - - odd: function( elem, i ) { - return i % 2 === 1; - }, - - lt: function( elem, i, match ) { - return i < match[3] - 0; - }, - - gt: function( elem, i, match ) { - return i > match[3] - 0; - }, - - nth: function( elem, i, match ) { - return match[3] - 0 === i; - }, - - eq: function( elem, i, match ) { - return match[3] - 0 === i; - } - }, - filter: { - PSEUDO: function( elem, match, i, array ) { - var name = match[1], - filter = Expr.filters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - - } else if ( name === "contains" ) { - return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; - - } else if ( name === "not" ) { - var not = match[3]; - - for ( var j = 0, l = not.length; j < l; j++ ) { - if ( not[j] === elem ) { - return false; - } - } - - return true; - - } else { - Sizzle.error( name ); - } - }, - - CHILD: function( elem, match ) { - var first, last, - doneName, parent, cache, - count, diff, - type = match[1], - node = elem; - - switch ( type ) { - case "only": - case "first": - while ( (node = node.previousSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - if ( type === "first" ) { - return true; - } - - node = elem; - - case "last": - while ( (node = node.nextSibling) ) { - if ( node.nodeType === 1 ) { - return false; - } - } - - return true; - - case "nth": - first = match[2]; - last = match[3]; - - if ( first === 1 && last === 0 ) { - return true; - } - - doneName = match[0]; - parent = elem.parentNode; - - if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { - count = 0; - - for ( node = parent.firstChild; node; node = node.nextSibling ) { - if ( node.nodeType === 1 ) { - node.nodeIndex = ++count; - } - } - - parent[ expando ] = doneName; - } - - diff = elem.nodeIndex - last; - - if ( first === 0 ) { - return diff === 0; - - } else { - return ( diff % first === 0 && diff / first >= 0 ); - } - } - }, - - ID: function( elem, match ) { - return elem.nodeType === 1 && elem.getAttribute("id") === match; - }, - - TAG: function( elem, match ) { - return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; - }, - - CLASS: function( elem, match ) { - return (" " + (elem.className || elem.getAttribute("class")) + " ") - .indexOf( match ) > -1; - }, - - ATTR: function( elem, match ) { - var name = match[1], - result = Sizzle.attr ? - Sizzle.attr( elem, name ) : - Expr.attrHandle[ name ] ? - Expr.attrHandle[ name ]( elem ) : - elem[ name ] != null ? - elem[ name ] : - elem.getAttribute( name ), - value = result + "", - type = match[2], - check = match[4]; - - return result == null ? - type === "!=" : - !type && Sizzle.attr ? - result != null : - type === "=" ? - value === check : - type === "*=" ? - value.indexOf(check) >= 0 : - type === "~=" ? - (" " + value + " ").indexOf(check) >= 0 : - !check ? - value && result !== false : - type === "!=" ? - value !== check : - type === "^=" ? - value.indexOf(check) === 0 : - type === "$=" ? - value.substr(value.length - check.length) === check : - type === "|=" ? - value === check || value.substr(0, check.length + 1) === check + "-" : - false; - }, - - POS: function( elem, match, i, array ) { - var name = match[2], - filter = Expr.setFilters[ name ]; - - if ( filter ) { - return filter( elem, i, match, array ); - } - } - } -}; - -var origPOS = Expr.match.POS, - fescape = function(all, num){ - return "\\" + (num - 0 + 1); - }; - -for ( var type in Expr.match ) { - Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); - Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); -} - -var makeArray = function( array, results ) { - array = Array.prototype.slice.call( array, 0 ); - - if ( results ) { - results.push.apply( results, array ); - return results; - } - - return array; -}; - -// Perform a simple check to determine if the browser is capable of -// converting a NodeList to an array using builtin methods. -// Also verifies that the returned array holds DOM nodes -// (which is not the case in the Blackberry browser) -try { - Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; - -// Provide a fallback method if it does not work -} catch( e ) { - makeArray = function( array, results ) { - var i = 0, - ret = results || []; - - if ( toString.call(array) === "[object Array]" ) { - Array.prototype.push.apply( ret, array ); - - } else { - if ( typeof array.length === "number" ) { - for ( var l = array.length; i < l; i++ ) { - ret.push( array[i] ); - } - - } else { - for ( ; array[i]; i++ ) { - ret.push( array[i] ); - } - } - } - - return ret; - }; -} - -var sortOrder, siblingCheck; - -if ( document.documentElement.compareDocumentPosition ) { - sortOrder = function( a, b ) { - if ( a === b ) { - hasDuplicate = true; - return 0; - } - - if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { - return a.compareDocumentPosition ? -1 : 1; - } - - return a.compareDocumentPosition(b) & 4 ? -1 : 1; - }; - -} else { - sortOrder = function( a, b ) { - // The nodes are identical, we can exit early - if ( a === b ) { - hasDuplicate = true; - return 0; - - // Fallback to using sourceIndex (in IE) if it's available on both nodes - } else if ( a.sourceIndex && b.sourceIndex ) { - return a.sourceIndex - b.sourceIndex; - } - - var al, bl, - ap = [], - bp = [], - aup = a.parentNode, - bup = b.parentNode, - cur = aup; - - // If the nodes are siblings (or identical) we can do a quick check - if ( aup === bup ) { - return siblingCheck( a, b ); - - // If no parents were found then the nodes are disconnected - } else if ( !aup ) { - return -1; - - } else if ( !bup ) { - return 1; - } - - // Otherwise they're somewhere else in the tree so we need - // to build up a full list of the parentNodes for comparison - while ( cur ) { - ap.unshift( cur ); - cur = cur.parentNode; - } - - cur = bup; - - while ( cur ) { - bp.unshift( cur ); - cur = cur.parentNode; - } - - al = ap.length; - bl = bp.length; - - // Start walking down the tree looking for a discrepancy - for ( var i = 0; i < al && i < bl; i++ ) { - if ( ap[i] !== bp[i] ) { - return siblingCheck( ap[i], bp[i] ); - } - } - - // We ended someplace up the tree so do a sibling check - return i === al ? - siblingCheck( a, bp[i], -1 ) : - siblingCheck( ap[i], b, 1 ); - }; - - siblingCheck = function( a, b, ret ) { - if ( a === b ) { - return ret; - } - - var cur = a.nextSibling; - - while ( cur ) { - if ( cur === b ) { - return -1; - } - - cur = cur.nextSibling; - } - - return 1; - }; -} - -// Check to see if the browser returns elements by name when -// querying by getElementById (and provide a workaround) -(function(){ - // We're going to inject a fake input element with a specified name - var form = document.createElement("div"), - id = "script" + (new Date()).getTime(), - root = document.documentElement; - - form.innerHTML = ""; - - // Inject it into the root element, check its status, and remove it quickly - root.insertBefore( form, root.firstChild ); - - // The workaround has to do additional checks after a getElementById - // Which slows things down for other browsers (hence the branching) - if ( document.getElementById( id ) ) { - Expr.find.ID = function( match, context, isXML ) { - if ( typeof context.getElementById !== "undefined" && !isXML ) { - var m = context.getElementById(match[1]); - - return m ? - m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? - [m] : - undefined : - []; - } - }; - - Expr.filter.ID = function( elem, match ) { - var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); - - return elem.nodeType === 1 && node && node.nodeValue === match; - }; - } - - root.removeChild( form ); - - // release memory in IE - root = form = null; -})(); - -(function(){ - // Check to see if the browser returns only elements - // when doing getElementsByTagName("*") - - // Create a fake element - var div = document.createElement("div"); - div.appendChild( document.createComment("") ); - - // Make sure no comments are found - if ( div.getElementsByTagName("*").length > 0 ) { - Expr.find.TAG = function( match, context ) { - var results = context.getElementsByTagName( match[1] ); - - // Filter out possible comments - if ( match[1] === "*" ) { - var tmp = []; - - for ( var i = 0; results[i]; i++ ) { - if ( results[i].nodeType === 1 ) { - tmp.push( results[i] ); - } - } - - results = tmp; - } - - return results; - }; - } - - // Check to see if an attribute returns normalized href attributes - div.innerHTML = ""; - - if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && - div.firstChild.getAttribute("href") !== "#" ) { - - Expr.attrHandle.href = function( elem ) { - return elem.getAttribute( "href", 2 ); - }; - } - - // release memory in IE - div = null; -})(); - -if ( document.querySelectorAll ) { - (function(){ - var oldSizzle = Sizzle, - div = document.createElement("div"), - id = "__sizzle__"; - - div.innerHTML = "

    "; - - // Safari can't handle uppercase or unicode characters when - // in quirks mode. - if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { - return; - } - - Sizzle = function( query, context, extra, seed ) { - context = context || document; - - // Only use querySelectorAll on non-XML documents - // (ID selectors don't work in non-HTML documents) - if ( !seed && !Sizzle.isXML(context) ) { - // See if we find a selector to speed up - var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); - - if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { - // Speed-up: Sizzle("TAG") - if ( match[1] ) { - return makeArray( context.getElementsByTagName( query ), extra ); - - // Speed-up: Sizzle(".CLASS") - } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { - return makeArray( context.getElementsByClassName( match[2] ), extra ); - } - } - - if ( context.nodeType === 9 ) { - // Speed-up: Sizzle("body") - // The body element only exists once, optimize finding it - if ( query === "body" && context.body ) { - return makeArray( [ context.body ], extra ); - - // Speed-up: Sizzle("#ID") - } else if ( match && match[3] ) { - var elem = context.getElementById( match[3] ); - - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document #6963 - if ( elem && elem.parentNode ) { - // Handle the case where IE and Opera return items - // by name instead of ID - if ( elem.id === match[3] ) { - return makeArray( [ elem ], extra ); - } - - } else { - return makeArray( [], extra ); - } - } - - try { - return makeArray( context.querySelectorAll(query), extra ); - } catch(qsaError) {} - - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - var oldContext = context, - old = context.getAttribute( "id" ), - nid = old || id, - hasParent = context.parentNode, - relativeHierarchySelector = /^\s*[+~]/.test( query ); - - if ( !old ) { - context.setAttribute( "id", nid ); - } else { - nid = nid.replace( /'/g, "\\$&" ); - } - if ( relativeHierarchySelector && hasParent ) { - context = context.parentNode; - } - - try { - if ( !relativeHierarchySelector || hasParent ) { - return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); - } - - } catch(pseudoError) { - } finally { - if ( !old ) { - oldContext.removeAttribute( "id" ); - } - } - } - } - - return oldSizzle(query, context, extra, seed); - }; - - for ( var prop in oldSizzle ) { - Sizzle[ prop ] = oldSizzle[ prop ]; - } - - // release memory in IE - div = null; - })(); -} - -(function(){ - var html = document.documentElement, - matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; - - if ( matches ) { - // Check to see if it's possible to do matchesSelector - // on a disconnected node (IE 9 fails this) - var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), - pseudoWorks = false; - - try { - // This should fail with an exception - // Gecko does not error, returns false instead - matches.call( document.documentElement, "[test!='']:sizzle" ); - - } catch( pseudoError ) { - pseudoWorks = true; - } - - Sizzle.matchesSelector = function( node, expr ) { - // Make sure that attribute selectors are quoted - expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); - - if ( !Sizzle.isXML( node ) ) { - try { - if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { - var ret = matches.call( node, expr ); - - // IE 9's matchesSelector returns false on disconnected nodes - if ( ret || !disconnectedMatch || - // As well, disconnected nodes are said to be in a document - // fragment in IE 9, so check for that - node.document && node.document.nodeType !== 11 ) { - return ret; - } - } - } catch(e) {} - } - - return Sizzle(expr, null, null, [node]).length > 0; - }; - } -})(); - -(function(){ - var div = document.createElement("div"); - - div.innerHTML = "
    "; - - // Opera can't find a second classname (in 9.6) - // Also, make sure that getElementsByClassName actually exists - if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { - return; - } - - // Safari caches class attributes, doesn't catch changes (in 3.2) - div.lastChild.className = "e"; - - if ( div.getElementsByClassName("e").length === 1 ) { - return; - } - - Expr.order.splice(1, 0, "CLASS"); - Expr.find.CLASS = function( match, context, isXML ) { - if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { - return context.getElementsByClassName(match[1]); - } - }; - - // release memory in IE - div = null; -})(); - -function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 && !isXML ){ - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( elem.nodeName.toLowerCase() === cur ) { - match = elem; - break; - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { - for ( var i = 0, l = checkSet.length; i < l; i++ ) { - var elem = checkSet[i]; - - if ( elem ) { - var match = false; - - elem = elem[dir]; - - while ( elem ) { - if ( elem[ expando ] === doneName ) { - match = checkSet[elem.sizset]; - break; - } - - if ( elem.nodeType === 1 ) { - if ( !isXML ) { - elem[ expando ] = doneName; - elem.sizset = i; - } - - if ( typeof cur !== "string" ) { - if ( elem === cur ) { - match = true; - break; - } - - } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { - match = elem; - break; - } - } - - elem = elem[dir]; - } - - checkSet[i] = match; - } - } -} - -if ( document.documentElement.contains ) { - Sizzle.contains = function( a, b ) { - return a !== b && (a.contains ? a.contains(b) : true); - }; - -} else if ( document.documentElement.compareDocumentPosition ) { - Sizzle.contains = function( a, b ) { - return !!(a.compareDocumentPosition(b) & 16); - }; - -} else { - Sizzle.contains = function() { - return false; - }; -} - -Sizzle.isXML = function( elem ) { - // documentElement is verified for cases where it doesn't yet exist - // (such as loading iframes in IE - #4833) - var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; - - return documentElement ? documentElement.nodeName !== "HTML" : false; -}; - -var posProcess = function( selector, context, seed ) { - var match, - tmpSet = [], - later = "", - root = context.nodeType ? [context] : context; - - // Position selectors must be done after the filter - // And so must :not(positional) so we move all PSEUDOs to the end - while ( (match = Expr.match.PSEUDO.exec( selector )) ) { - later += match[0]; - selector = selector.replace( Expr.match.PSEUDO, "" ); - } - - selector = Expr.relative[selector] ? selector + "*" : selector; - - for ( var i = 0, l = root.length; i < l; i++ ) { - Sizzle( selector, root[i], tmpSet, seed ); - } - - return Sizzle.filter( later, tmpSet ); -}; - -// EXPOSE -// Override sizzle attribute retrieval -Sizzle.attr = jQuery.attr; -Sizzle.selectors.attrMap = {}; -jQuery.find = Sizzle; -jQuery.expr = Sizzle.selectors; -jQuery.expr[":"] = jQuery.expr.filters; -jQuery.unique = Sizzle.uniqueSort; -jQuery.text = Sizzle.getText; -jQuery.isXMLDoc = Sizzle.isXML; -jQuery.contains = Sizzle.contains; - - -})(); - - -var runtil = /Until$/, - rparentsprev = /^(?:parents|prevUntil|prevAll)/, - // Note: This RegExp should be improved, or likely pulled from Sizzle - rmultiselector = /,/, - isSimple = /^.[^:#\[\.,]*$/, - slice = Array.prototype.slice, - POS = jQuery.expr.match.POS, - // methods guaranteed to produce a unique set when starting from a unique set - guaranteedUnique = { - children: true, - contents: true, - next: true, - prev: true - }; - -jQuery.fn.extend({ - find: function( selector ) { - var self = this, - i, l; - - if ( typeof selector !== "string" ) { - return jQuery( selector ).filter(function() { - for ( i = 0, l = self.length; i < l; i++ ) { - if ( jQuery.contains( self[ i ], this ) ) { - return true; - } - } - }); - } - - var ret = this.pushStack( "", "find", selector ), - length, n, r; - - for ( i = 0, l = this.length; i < l; i++ ) { - length = ret.length; - jQuery.find( selector, this[i], ret ); - - if ( i > 0 ) { - // Make sure that the results are unique - for ( n = length; n < ret.length; n++ ) { - for ( r = 0; r < length; r++ ) { - if ( ret[r] === ret[n] ) { - ret.splice(n--, 1); - break; - } - } - } - } - } - - return ret; - }, - - has: function( target ) { - var targets = jQuery( target ); - return this.filter(function() { - for ( var i = 0, l = targets.length; i < l; i++ ) { - if ( jQuery.contains( this, targets[i] ) ) { - return true; - } - } - }); - }, - - not: function( selector ) { - return this.pushStack( winnow(this, selector, false), "not", selector); - }, - - filter: function( selector ) { - return this.pushStack( winnow(this, selector, true), "filter", selector ); - }, - - is: function( selector ) { - return !!selector && ( - typeof selector === "string" ? - // If this is a positional selector, check membership in the returned set - // so $("p:first").is("p:last") won't return true for a doc with two "p". - POS.test( selector ) ? - jQuery( selector, this.context ).index( this[0] ) >= 0 : - jQuery.filter( selector, this ).length > 0 : - this.filter( selector ).length > 0 ); - }, - - closest: function( selectors, context ) { - var ret = [], i, l, cur = this[0]; - - // Array (deprecated as of jQuery 1.7) - if ( jQuery.isArray( selectors ) ) { - var level = 1; - - while ( cur && cur.ownerDocument && cur !== context ) { - for ( i = 0; i < selectors.length; i++ ) { - - if ( jQuery( cur ).is( selectors[ i ] ) ) { - ret.push({ selector: selectors[ i ], elem: cur, level: level }); - } - } - - cur = cur.parentNode; - level++; - } - - return ret; - } - - // String - var pos = POS.test( selectors ) || typeof selectors !== "string" ? - jQuery( selectors, context || this.context ) : - 0; - - for ( i = 0, l = this.length; i < l; i++ ) { - cur = this[i]; - - while ( cur ) { - if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { - ret.push( cur ); - break; - - } else { - cur = cur.parentNode; - if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { - break; - } - } - } - } - - ret = ret.length > 1 ? jQuery.unique( ret ) : ret; - - return this.pushStack( ret, "closest", selectors ); - }, - - // Determine the position of an element within - // the matched set of elements - index: function( elem ) { - - // No argument, return index in parent - if ( !elem ) { - return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; - } - - // index in selector - if ( typeof elem === "string" ) { - return jQuery.inArray( this[0], jQuery( elem ) ); - } - - // Locate the position of the desired element - return jQuery.inArray( - // If it receives a jQuery object, the first element is used - elem.jquery ? elem[0] : elem, this ); - }, - - add: function( selector, context ) { - var set = typeof selector === "string" ? - jQuery( selector, context ) : - jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), - all = jQuery.merge( this.get(), set ); - - return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? - all : - jQuery.unique( all ) ); - }, - - andSelf: function() { - return this.add( this.prevObject ); - } -}); - -// A painfully simple check to see if an element is disconnected -// from a document (should be improved, where feasible). -function isDisconnected( node ) { - return !node || !node.parentNode || node.parentNode.nodeType === 11; -} - -jQuery.each({ - parent: function( elem ) { - var parent = elem.parentNode; - return parent && parent.nodeType !== 11 ? parent : null; - }, - parents: function( elem ) { - return jQuery.dir( elem, "parentNode" ); - }, - parentsUntil: function( elem, i, until ) { - return jQuery.dir( elem, "parentNode", until ); - }, - next: function( elem ) { - return jQuery.nth( elem, 2, "nextSibling" ); - }, - prev: function( elem ) { - return jQuery.nth( elem, 2, "previousSibling" ); - }, - nextAll: function( elem ) { - return jQuery.dir( elem, "nextSibling" ); - }, - prevAll: function( elem ) { - return jQuery.dir( elem, "previousSibling" ); - }, - nextUntil: function( elem, i, until ) { - return jQuery.dir( elem, "nextSibling", until ); - }, - prevUntil: function( elem, i, until ) { - return jQuery.dir( elem, "previousSibling", until ); - }, - siblings: function( elem ) { - return jQuery.sibling( elem.parentNode.firstChild, elem ); - }, - children: function( elem ) { - return jQuery.sibling( elem.firstChild ); - }, - contents: function( elem ) { - return jQuery.nodeName( elem, "iframe" ) ? - elem.contentDocument || elem.contentWindow.document : - jQuery.makeArray( elem.childNodes ); - } -}, function( name, fn ) { - jQuery.fn[ name ] = function( until, selector ) { - var ret = jQuery.map( this, fn, until ); - - if ( !runtil.test( name ) ) { - selector = until; - } - - if ( selector && typeof selector === "string" ) { - ret = jQuery.filter( selector, ret ); - } - - ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; - - if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { - ret = ret.reverse(); - } - - return this.pushStack( ret, name, slice.call( arguments ).join(",") ); - }; -}); - -jQuery.extend({ - filter: function( expr, elems, not ) { - if ( not ) { - expr = ":not(" + expr + ")"; - } - - return elems.length === 1 ? - jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : - jQuery.find.matches(expr, elems); - }, - - dir: function( elem, dir, until ) { - var matched = [], - cur = elem[ dir ]; - - while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { - if ( cur.nodeType === 1 ) { - matched.push( cur ); - } - cur = cur[dir]; - } - return matched; - }, - - nth: function( cur, result, dir, elem ) { - result = result || 1; - var num = 0; - - for ( ; cur; cur = cur[dir] ) { - if ( cur.nodeType === 1 && ++num === result ) { - break; - } - } - - return cur; - }, - - sibling: function( n, elem ) { - var r = []; - - for ( ; n; n = n.nextSibling ) { - if ( n.nodeType === 1 && n !== elem ) { - r.push( n ); - } - } - - return r; - } -}); - -// Implement the identical functionality for filter and not -function winnow( elements, qualifier, keep ) { - - // Can't pass null or undefined to indexOf in Firefox 4 - // Set to 0 to skip string check - qualifier = qualifier || 0; - - if ( jQuery.isFunction( qualifier ) ) { - return jQuery.grep(elements, function( elem, i ) { - var retVal = !!qualifier.call( elem, i, elem ); - return retVal === keep; - }); - - } else if ( qualifier.nodeType ) { - return jQuery.grep(elements, function( elem, i ) { - return ( elem === qualifier ) === keep; - }); - - } else if ( typeof qualifier === "string" ) { - var filtered = jQuery.grep(elements, function( elem ) { - return elem.nodeType === 1; - }); - - if ( isSimple.test( qualifier ) ) { - return jQuery.filter(qualifier, filtered, !keep); - } else { - qualifier = jQuery.filter( qualifier, filtered ); - } - } - - return jQuery.grep(elements, function( elem, i ) { - return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; - }); -} - - - - -function createSafeFragment( document ) { - var list = nodeNames.split( "|" ), - safeFrag = document.createDocumentFragment(); - - if ( safeFrag.createElement ) { - while ( list.length ) { - safeFrag.createElement( - list.pop() - ); - } - } - return safeFrag; -} - -var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + - "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", - rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, - rleadingWhitespace = /^\s+/, - rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, - rtagName = /<([\w:]+)/, - rtbody = /", "" ], - legend: [ 1, "
    ", "
    " ], - thead: [ 1, "", "
    " ], - tr: [ 2, "", "
    " ], - td: [ 3, "", "
    " ], - col: [ 2, "", "
    " ], - area: [ 1, "", "" ], - _default: [ 0, "", "" ] - }, - safeFragment = createSafeFragment( document ); - -wrapMap.optgroup = wrapMap.option; -wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; -wrapMap.th = wrapMap.td; - -// IE can't serialize and + + + {{> facebook}} + + + + + +
    + + + + + + + +
    +

        About

    +
    +
    + + +
    +
    +
    + +
    +

    Project

    +

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ut pellentesque + lorem, sed condimentum risus. Nam aliquam lacus vel neque ullamcorper + lacinia. Maecenas ultricies lacinia euismod. Proin non aliquet enim. + Morbi tempor semper magna et condimentum. Donec blandit, + lectus sit amet rutrum pulvinar, libero tortor imperdiet elit, + sit amet elementum justo augue eget nunc. Ut vitae urna eu magna + ornare dictum. Quisque nec mattis ex, a tempor enim. In ut rhoncus +

    + +

    Creator

    +
    +
    +
    + Lorem Pixel image + +
    +
    +

    Name

    +

    Role

    +

    description

    +
    + + + +
    +
    +
    +
    +
    + + + + +
    + + + + diff --git a/views/activity.handlebars b/views/activity.handlebars new file mode 100644 index 000000000..8d75e7bc1 --- /dev/null +++ b/views/activity.handlebars @@ -0,0 +1,76 @@ + + + + + + Activity Page + {{!-- --}} + + + + + + + + + + + {{#each toLog}} +
    +
    +
    +

    {{Activity}}

    +
    + +
    +

    {{Description}}

    +

    0:00

    +
    + +
    + {{/each}} +
    +
    +
    + + + + + + +
    +
    +
    + +
    + + {{!-- js --}} + + + {{!-- --}} + + + + + \ No newline at end of file diff --git a/views/complete.handlebars b/views/complete.handlebars new file mode 100644 index 000000000..4afa0216a --- /dev/null +++ b/views/complete.handlebars @@ -0,0 +1,108 @@ + + + + + + + + + Completion Screen + + +
    +
    + +

    Complete

    + +
    +
    + + +
    +
    +
    +
    + +
    +
    + + +
    +
    +

    Yay! You completed your first activity

    +
    +
    +
    +
    + + + +

    + {{!--
    + + +
    --}} + +
    + +
    + {{!-- js --}} + + + + {{!-- --}} + {{!-- --}} + + + + + \ No newline at end of file diff --git a/views/filter.handlebars b/views/filter.handlebars new file mode 100644 index 000000000..5428845a7 --- /dev/null +++ b/views/filter.handlebars @@ -0,0 +1,152 @@ + + + Filter + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + +







    + + +

    + How long would your break be? +

    + +



    + + +
    + + + + +

    10 min

    +
    + +
    + + + + +

    20 min

    +
    + +
    + + + + +

    30 min

    +
    + +
    + + + + +

    1 hour

    +
    + +
    + + + +

    1 hour

    +
    + +
    + + + +

     No preference

    +
    + +
    + + + + + + + + + + \ No newline at end of file diff --git a/views/filter2.handlebars b/views/filter2.handlebars new file mode 100644 index 000000000..edd847801 --- /dev/null +++ b/views/filter2.handlebars @@ -0,0 +1,114 @@ + + + Filter + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + +







    + + +

    + What will you be interested in?
    (Select all that apply) +

    + +



    + + +

    Exercise

    +

    Music

    +

    Creative

    +

    Productivity

    +

    Art

    +

    Nature

    +

    Cooking

    +

    Relaxation

    +

    Learning

    + + + +
    + + + + + + \ No newline at end of file diff --git a/views/filter3.handlebars b/views/filter3.handlebars new file mode 100644 index 000000000..de39b65d6 --- /dev/null +++ b/views/filter3.handlebars @@ -0,0 +1,149 @@ + + + Filter + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + +







    + +

    + Would you prefer...? +

    + +



    + + +
    +

    Outdoor

    +
    + +
    +

    Indoor

    +
    + +
    + + + +

     No preference

    +
    + +
    + + +
    + + + + + + + +
    + Let's do it! +
    + +
    + + + + + + + + + + + + + + \ No newline at end of file diff --git a/views/filtered.handlebars b/views/filtered.handlebars new file mode 100644 index 000000000..ac783e3b2 --- /dev/null +++ b/views/filtered.handlebars @@ -0,0 +1,90 @@ + + + + + + Activity for you + {{!-- --}} + + + + + + + + + + + + + + + + + +
    + + +
    +
    + + {{#each activites}} + {{!--
    + +
    --}} + + Unsplash image + +

    {{Activity}}

    +

    {{Description}}Ten minute of sun salutations with Instructor Nina. +

    {{minTime}} min

    +
    + {{/each}} +
    + +
    +
    +
    + + + + + + +
    +
    +
    + +
    + + {{!-- js --}} + + {{!-- --}} + + + + + \ No newline at end of file diff --git a/views/index.handlebars b/views/index.handlebars old mode 100644 new mode 100755 index 7fef0f9e9..c96663cdc --- a/views/index.handlebars +++ b/views/index.handlebars @@ -1,8 +1,136 @@ + - Test Page + HCI Project Portfolio + + + + + + + + + + + + + + + + + + {{!-- {{> facebook}} + + --}} + + -Begin here (or replace this with any static code already written). + +
    + + + + + + + +
    +

        Activity log

    +
    +
    + + +
    +
    +
    + + + + + + +







    + + {{#each toLog}} +
    +
    +
    + +

    {{Activity}}

    + +
    +

    {{minTime}} minutes

    +
    + Unsplash image +
    +
    +

    {{Description}}

    +
    +
    + + +
    +
    + {{/each}} + + + +
    +
    + +
    +
    +
    + +
    + + + diff --git a/views/logIn.handlebars b/views/logIn.handlebars new file mode 100644 index 000000000..b9ddc762f --- /dev/null +++ b/views/logIn.handlebars @@ -0,0 +1,94 @@ + + + + + LogIn + + + + + + + + {{!-- + + + {{> facebook}} + --}} + + + + +
    +
    +
    +

    Lacuna

    +

    Matata

    +
    +
    +
    +
    + +
    +
    + pic +
    +
    + +
    +
    +
    +
    + + + We'll never share your email with anyone else. +
    +
    + + +
    + {{!--
    + + +
    --}} + + + + +
    +
    +
    + + + {{!-- --}} + + + {{!--

    + + +

    --}} + + + + {{!-- js --}} + + {{!-- + --}} + + + + + + + + + + \ No newline at end of file diff --git a/views/partials/facebook.handlebars b/views/partials/facebook.handlebars new file mode 100644 index 000000000..2011ad664 --- /dev/null +++ b/views/partials/facebook.handlebars @@ -0,0 +1,42 @@ + + + + + \ No newline at end of file diff --git a/views/project.handlebars b/views/project.handlebars new file mode 100644 index 000000000..df26ce68e --- /dev/null +++ b/views/project.handlebars @@ -0,0 +1,65 @@ + + + + Project + + + + + + + + + + + + +
    +
    +

    {{projectName}}

    +

    one-sentence description of project

    +
    + +

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus enim diam, adipiscing sodales sem ut, tristique suscipit odio. Nam mollis ipsum et venenatis euismod. Aliquam erat volutpat. Praesent placerat condimentum tristique. Morbi egestas dapibus viverra. Mauris sit amet dignissim risus, non elementum eros. Donec urna dui, placerat et feugiat non, vulputate in ipsum. Quisque dignissim pulvinar nisi. Quisque feugiat commodo dolor nec suscipit. Donec pretium scelerisque aliquet. Vivamus vitae turpis metus. Sed lobortis vitae orci sed gravida. Donec euismod ipsum sagittis pellentesque pellentesque. Aenean at lorem nec leo consequat tincidunt. Maecenas sit amet felis vel ante dictum suscipit quis nec magna. Sed augue velit, imperdiet quis mi a, porta aliquet urna.

    + +

    Phasellus at neque eget sapien elementum sollicitudin. In odio mauris, pulvinar quis turpis sed, faucibus tristique leo. Phasellus a volutpat tortor. Nunc blandit imperdiet iaculis. Nam purus orci, placerat in venenatis ut, ultrices id dolor. Duis ornare erat lectus, at posuere justo mollis eu. Duis dictum feugiat imperdiet. Praesent vitae orci in eros semper lacinia a ut arcu. Cras vitae sapien et erat faucibus imperdiet nec a turpis. Integer at egestas ipsum, sed suscipit eros.

    + +
    +
    + + + + + + + + + + + + + + + +
    User + Salient need +
    SchoolteacherWants to know what music students are listening to so he can integrate it into his lessons.
    Student 5th gradeDesire to be seen as a tastemaker for her friends. Hears about new music from older sister in middle school.
    +
    +
    + Lorem Pixel image +
    +
    + +

    Sed vitae ultricies magna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Fusce pulvinar sapien eget lacus volutpat suscipit. Duis bibendum condimentum sapien, quis vulputate turpis ultricies sit amet. Quisque sollicitudin vitae ipsum vel scelerisque. Aliquam facilisis eros eros, in ultricies erat aliquam nec. Suspendisse nec egestas arcu. Sed nec malesuada turpis. Proin eu lorem sed mauris bibendum consectetur sit amet mattis arcu. Aliquam porta ligula in nulla ullamcorper, at pulvinar diam porta.

    + +

    Back »

    + + + + + + + diff --git a/views/reminder.handlebars b/views/reminder.handlebars new file mode 100644 index 000000000..e7fd98475 --- /dev/null +++ b/views/reminder.handlebars @@ -0,0 +1,82 @@ + + + + + + + Document + + + + + + + +
    +
    +

        Reminders

    +
    +
    + + +
    +
    +
    + {{!-- reminders --}} +
    +

    How often do you want to get new ideas?

    +
    + +
    + +
    +
    +
    + +
    +

    When do you want to get new ideas

    +
    + +
    + +
    +
    +
    + + +
    + {{!-- js --}} + + + + + \ No newline at end of file diff --git a/views/setting.handlebars b/views/setting.handlebars new file mode 100644 index 000000000..5b5e8ac6c --- /dev/null +++ b/views/setting.handlebars @@ -0,0 +1,133 @@ + + + + + Settings + + + + + + + + + + + + + + + + + +
    +
    + +

    Setting

    + +
    +
    + + +
    +
    +
    +
    + +
    + +
    +
    +

    Profile

    +
    +
    + +
    +
    +

    Reminders

    +

    How often do you want to get new ideas?

    +
    + +
    + +
    +
    +
    +
    +

    When do you want to get new ideas?

    +
    + +
    + +
    +
    +
    +
    + +
    + +
    + +
    + + {{!-- js --}} + + + + + +